File: rename.go

package info (click to toggle)
golang-github-clbanning-mxj 2.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,200 kB
  • sloc: xml: 176; makefile: 4
file content (61 lines) | stat: -rw-r--r-- 1,525 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package mxj

import (
	"errors"
	"strings"
)

// RenameKey renames a key in a Map.
// It works only for nested maps. 
// It doesn't work for cases when the key is in a list.
func (mv Map) RenameKey(path string, newName string) error {
	var v bool
	var err error
	if v, err = mv.Exists(path); err == nil && !v {
		return errors.New("RenameKey: path not found: " + path)
	} else if err != nil {
		return err
	}
	if v, err = mv.Exists(parentPath(path) + "." + newName); err == nil && v {
		return errors.New("RenameKey: key already exists: " + newName)
	} else if err != nil {
		return err
	}

	m := map[string]interface{}(mv)
	return renameKey(m, path, newName)
}

func renameKey(m interface{}, path string, newName string) error {
	val, err := prevValueByPath(m, path)
	if err != nil {
		return err
	}

	oldName := lastKey(path)
	val[newName] = val[oldName]
	delete(val, oldName)

	return nil
}

// returns a value which contains a last key in the path
// For example: prevValueByPath("a.b.c", {a{b{c: 3}}}) returns {c: 3}
func prevValueByPath(m interface{}, path string) (map[string]interface{}, error) {
	keys := strings.Split(path, ".")

	switch mValue := m.(type) {
	case map[string]interface{}:
		for key, value := range mValue {
			if key == keys[0] {
				if len(keys) == 1 {
					return mValue, nil
				} else {
					// keep looking for the full path to the key
					return prevValueByPath(value, strings.Join(keys[1:], "."))
				}
			}
		}
	}
	return nil, errors.New("prevValueByPath: didn't find path – " + path)
}