Skip to content

Commit

Permalink
Move part of the code to pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Apr 17, 2022
1 parent aa0964a commit bf166fa
Show file tree
Hide file tree
Showing 21 changed files with 552 additions and 513 deletions.
26 changes: 0 additions & 26 deletions dict.go

This file was deleted.

66 changes: 34 additions & 32 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,23 @@ package main
import (
"encoding/json"
"fmt"
. "github.com/antonmedv/fx/pkg/dict"
. "github.com/antonmedv/fx/pkg/json"
"github.com/antonmedv/fx/pkg/reducer"
. "github.com/antonmedv/fx/pkg/theme"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/mattn/go-isatty"
"github.com/muesli/termenv"
"golang.org/x/term"
"io/fs"
"os"
"path"
"io/fs"
"runtime/pprof"
"strings"
)

type number = json.Number

func main() {
cpuProfile := os.Getenv("CPU_PROFILE")
if cpuProfile != "" {
Expand All @@ -35,12 +37,12 @@ func main() {
if !ok {
themeId = "1"
}
theme, ok := themes[themeId]
theme, ok := Themes[themeId]
if !ok {
theme = themes["1"]
theme = Themes["1"]
}
if termenv.ColorProfile() == termenv.Ascii {
theme = themes["0"]
theme = Themes["0"]
}

filePath := ""
Expand Down Expand Up @@ -71,40 +73,40 @@ func main() {
os.Exit(1)
}
dec.UseNumber()
jsonObject, err := parse(dec)
jsonObject, err := Parse(dec)
if err != nil {
panic(err)
}

tty := isatty.IsTerminal(os.Stdout.Fd())
if len(args) > 0 || !tty {
if len(args) > 0 && args[0] == "--print-code" {
fmt.Print(generateCode(args[1:]))
fmt.Print(reducer.GenerateCode(args[1:]))
return
}
reduce(jsonObject, args, theme)
reducer.Reduce(jsonObject, args, theme)
return
}

expand := map[string]bool{
"": true,
}
if array, ok := jsonObject.(array); ok {
if array, ok := jsonObject.(Array); ok {
for i := range array {
expand[accessor("", i)] = true
}
}
parents := map[string]string{}
children := map[string][]string{}
canBeExpanded := map[string]bool{}
dfs(jsonObject, func(it iterator) {
parents[it.path] = it.parent
children[it.parent] = append(children[it.parent], it.path)
switch it.object.(type) {
case *dict:
canBeExpanded[it.path] = len(it.object.(*dict).keys) > 0
case array:
canBeExpanded[it.path] = len(it.object.(array)) > 0
Dfs(jsonObject, func(it Iterator) {
parents[it.Path] = it.Parent
children[it.Parent] = append(children[it.Parent], it.Path)
switch it.Object.(type) {
case *Dict:
canBeExpanded[it.Path] = len(it.Object.(*Dict).Keys) > 0
case Array:
canBeExpanded[it.Path] = len(it.Object.(Array)) > 0
}
})

Expand Down Expand Up @@ -152,7 +154,7 @@ type model struct {
json interface{}
lines []string

mouseWheelDelta int // number of lines the mouse wheel will scroll
mouseWheelDelta int // Number of lines the mouse wheel will scroll
offset int // offset is the vertical scroll position

keyMap KeyMap
Expand All @@ -161,9 +163,9 @@ type model struct {
expandedPaths map[string]bool // set of expanded paths
canBeExpanded map[string]bool // set of path => can be expanded (i.e. dict or array)
paths []string // array of paths on screen
pathToLineNumber map[string]int // map of path => line number
pathToLineNumber map[string]int // map of path => line Number
pathToIndex map[string]int // map of path => index in m.paths
lineNumberToPath map[int]string // map of line number => path
lineNumberToPath map[int]string // map of line Number => path
parents map[string]string // map of subpath => parent path
children map[string][]string // map of path => child paths
nextSiblings, prevSiblings map[string]string // map of path => sibling path
Expand Down Expand Up @@ -342,10 +344,10 @@ func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.render()

case key.Matches(msg, m.keyMap.ExpandAll):
dfs(m.json, func(it iterator) {
switch it.object.(type) {
case *dict, array:
m.expandedPaths[it.path] = true
Dfs(m.json, func(it Iterator) {
switch it.Object.(type) {
case *Dict, Array:
m.expandedPaths[it.Path] = true
}
})
m.render()
Expand Down Expand Up @@ -400,13 +402,13 @@ func (m *model) View() string {
if m.showHelp {
statusBar := "Press Esc or q to close help."
statusBar += strings.Repeat(" ", max(0, m.width-width(statusBar)))
statusBar = m.theme.statusBar(statusBar)
statusBar = m.theme.StatusBar(statusBar)
return strings.Join(lines, "\n") + extraLines + "\n" + statusBar
}
statusBar := m.cursorPath() + " "
statusBar += strings.Repeat(" ", max(0, m.width-width(statusBar)-width(m.fileName)))
statusBar += m.fileName
statusBar = m.theme.statusBar(statusBar)
statusBar = m.theme.StatusBar(statusBar)
output := strings.Join(lines, "\n") + extraLines + "\n" + statusBar
if m.searchInput.Focused() {
output += "\n/" + m.searchInput.View()
Expand Down Expand Up @@ -506,22 +508,22 @@ func (m *model) collapseRecursively(path string) {

func (m *model) collectSiblings(v interface{}, path string) {
switch v.(type) {
case *dict:
case *Dict:
prev := ""
for _, k := range v.(*dict).keys {
for _, k := range v.(*Dict).Keys {
subpath := path + "." + k
if prev != "" {
m.nextSiblings[prev] = subpath
m.prevSiblings[subpath] = prev
}
prev = subpath
value, _ := v.(*dict).get(k)
value, _ := v.(*Dict).Get(k)
m.collectSiblings(value, subpath)
}

case array:
case Array:
prev := ""
for i, value := range v.(array) {
for i, value := range v.(Array) {
subpath := fmt.Sprintf("%v[%v]", path, i)
if prev != "" {
m.nextSiblings[prev] = subpath
Expand Down
50 changes: 0 additions & 50 deletions parse_test.go

This file was deleted.

26 changes: 26 additions & 0 deletions pkg/dict/dict.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package dict

type Dict struct {
Keys []string
Values map[string]interface{}
}

func NewDict() *Dict {
return &Dict{
Keys: make([]string, 0),
Values: make(map[string]interface{}),
}
}

func (d *Dict) Get(key string) (interface{}, bool) {
val, exists := d.Values[key]
return val, exists
}

func (d *Dict) Set(key string, value interface{}) {
_, exists := d.Values[key]
if !exists {
d.Keys = append(d.Keys, key)
}
d.Values[key] = value
}
28 changes: 14 additions & 14 deletions dict_test.go → pkg/dict/dict_test.go
Original file line number Diff line number Diff line change
@@ -1,58 +1,58 @@
package main
package dict

import "testing"

func Test_dict(t *testing.T) {
d := newDict()
d.set("number", 3)
v, _ := d.get("number")
d := NewDict()
d.Set("number", 3)
v, _ := d.Get("number")
if v.(int) != 3 {
t.Error("Set number")
}
// string
d.set("string", "x")
v, _ = d.get("string")
d.Set("string", "x")
v, _ = d.Get("string")
if v.(string) != "x" {
t.Error("Set string")
}
// string slice
d.set("strings", []string{
d.Set("strings", []string{
"t",
"u",
})
v, _ = d.get("strings")
v, _ = d.Get("strings")
if v.([]string)[0] != "t" {
t.Error("Set strings first index")
}
if v.([]string)[1] != "u" {
t.Error("Set strings second index")
}
// mixed slice
d.set("mixed", []interface{}{
d.Set("mixed", []interface{}{
1,
"1",
})
v, _ = d.get("mixed")
v, _ = d.Get("mixed")
if v.([]interface{})[0].(int) != 1 {
t.Error("Set mixed int")
}
if v.([]interface{})[1].(string) != "1" {
t.Error("Set mixed string")
}
// overriding existing key
d.set("number", 4)
v, _ = d.get("number")
d.Set("number", 4)
v, _ = d.Get("number")
if v.(int) != 4 {
t.Error("Override existing key")
}
// keys
// Keys
expectedKeys := []string{
"number",
"string",
"strings",
"mixed",
}
for i, key := range d.keys {
for i, key := range d.Keys {
if key != expectedKeys[i] {
t.Error("Keys method", key, "!=", expectedKeys[i])
}
Expand Down
15 changes: 7 additions & 8 deletions parse.go → pkg/json/parse.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package main
package json

import (
"encoding/json"
. "github.com/antonmedv/fx/pkg/dict"
)

func parse(dec *json.Decoder) (interface{}, error) {
func Parse(dec *json.Decoder) (interface{}, error) {
token, err := dec.Token()
if err != nil {
return nil, err
Expand All @@ -20,8 +21,8 @@ func parse(dec *json.Decoder) (interface{}, error) {
return token, nil
}

func decodeDict(dec *json.Decoder) (*dict, error) {
d := newDict()
func decodeDict(dec *json.Decoder) (*Dict, error) {
d := NewDict()
for {
token, err := dec.Token()
if err != nil {
Expand Down Expand Up @@ -50,14 +51,12 @@ func decodeDict(dec *json.Decoder) (*dict, error) {
}
}
}
d.set(key, value)
d.Set(key, value)
}
}

type array = []interface{}

func decodeArray(dec *json.Decoder) ([]interface{}, error) {
slice := make(array, 0)
slice := make(Array, 0)
for index := 0; ; index++ {
token, err := dec.Token()
if err != nil {
Expand Down
Loading

0 comments on commit bf166fa

Please sign in to comment.