Example #1
0
func (a *App) cmdSetHost(ctx *service.CommandContext) {
	ctx.RequireExactlyNArgs(2)
	err := a.loadConfig()
	if err != nil {
		// todo: more helpful error if config.json does not exist
		ctx.Fatal(err.Error())
	}

	host, dest := ctx.Args[0], ctx.Args[1]
	u, err := url.Parse(dest)
	if err != nil {
		ctx.Fatal("failed to parse dest url: %s", err)
	}
	us := u.String()
	// todo: check if host already exists

	found := false
	for _, e := range a.config.Entries {
		if e.Source == host {
			fmt.Printf("replacing existing entry for %s: %s\n", host, *e.DestHost)
			e.DestHost = &us
			found = true
		}
	}
	if !found {
		a.config.Entries = append(a.config.Entries, Entry{
			Source:   host,
			DestHost: &us,
		})
	}
	b, err := json.MarshalIndent(a.config, "", "  ")
	if err != nil {
		ctx.Fatal(err.Error())
	}
	err = ioutil.WriteFile(a.configPath(), b, os.ModePerm)
	if err != nil {
		ctx.Fatal(err.Error())
	}
	fmt.Printf("registered: %s => %s\n", host, u.String())
}