|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + |
| 8 | + "github.com/facebookgo/stackerr" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +type migrateCmd struct { |
| 13 | + retainMaster bool |
| 14 | +} |
| 15 | + |
| 16 | +func (m *migrateCmd) upgradeLegacy(e *env, c config) (*parseConfig, error) { |
| 17 | + p := c.getProjectConfig() |
| 18 | + if p.Type != legacyParseFormat { |
| 19 | + return nil, stackerr.New("Already using the preferred config format.") |
| 20 | + } |
| 21 | + p.Type = parseFormat |
| 22 | + config, ok := (c).(*parseConfig) |
| 23 | + if !ok { |
| 24 | + return nil, stackerr.Newf("Unexpected config format: %d", p.Type) |
| 25 | + } |
| 26 | + if !m.retainMaster { |
| 27 | + for _, app := range config.Applications { |
| 28 | + app.MasterKey = "" |
| 29 | + } |
| 30 | + } |
| 31 | + return config, nil |
| 32 | +} |
| 33 | + |
| 34 | +func (m *migrateCmd) run(e *env) error { |
| 35 | + c, err := configFromDir(e.Root) |
| 36 | + if err != nil { |
| 37 | + return err |
| 38 | + } |
| 39 | + |
| 40 | + c, err = m.upgradeLegacy(e, c) |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + localErr := storeConfig(e, c) |
| 45 | + projectErr := storeProjectConfig(e, c) |
| 46 | + if localErr == nil && projectErr == nil { |
| 47 | + legacy := filepath.Join(e.Root, legacyConfigFile) |
| 48 | + err := os.Remove(legacy) |
| 49 | + if err != nil { |
| 50 | + fmt.Fprintf(e.Err, "Could not delete: %q. Please remove this file manually.\n", legacy) |
| 51 | + } |
| 52 | + } else { |
| 53 | + local := filepath.Join(e.Root, parseLocal) |
| 54 | + err := os.Remove(local) |
| 55 | + if err != nil { |
| 56 | + fmt.Fprintf(e.Err, "Failed to clean up: %q. Please remove this file manually.\n", local) |
| 57 | + } |
| 58 | + project := filepath.Join(e.Root, parseProject) |
| 59 | + err = os.Remove(project) |
| 60 | + if err != nil { |
| 61 | + fmt.Fprintf(e.Err, "Failed to clean up: %q. Please remove this file manually.\n", project) |
| 62 | + } |
| 63 | + } |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +func newMigrateCmd(e *env) *cobra.Command { |
| 68 | + var m migrateCmd |
| 69 | + cmd := &cobra.Command{ |
| 70 | + Use: "migrate", |
| 71 | + Short: "Migrate project config format to preferred format", |
| 72 | + Long: `Use this on projects with legacy config format to migrate |
| 73 | +to the preferred format. |
| 74 | +`, |
| 75 | + Run: runNoArgs(e, m.run), |
| 76 | + } |
| 77 | + cmd.Flags().BoolVarP(&m.retainMaster, "retain", "r", m.retainMaster, |
| 78 | + "Retain any master keys present in config during migration") |
| 79 | + return cmd |
| 80 | +} |
0 commit comments