Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions cmd/editor/diagnostics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package editor

import (
"encoding/json"
"fmt"
"io"

editoripc "github.com/kloudkit/ws-cli/internals/editor"
"github.com/kloudkit/ws-cli/internals/styles"
"github.com/spf13/cobra"
)

var diagnosticsCmd = &cobra.Command{
Use: "diagnostics",
Short: "Show language diagnostics for the workspace (or a single file)",
RunE: func(cmd *cobra.Command, args []string) error {
uri, _ := cmd.Flags().GetString("uri")

body, err := editoripc.FetchDiagnostics(uri)
if err != nil {
return err
}

return emit(cmd, body, renderDiagnostics)
},
}

func renderDiagnostics(out io.Writer, body []byte) error {
var files []editoripc.DiagnosticFile
if err := json.Unmarshal(body, &files); err != nil {
return fmt.Errorf("error parsing diagnostics response: %w", err)
}

total := 0
for _, file := range files {
total += len(file.Items)
}

if total == 0 {
styles.PrintSuccess(out, "No diagnostics")
return nil
}

fmt.Fprintf(out, "%s\n", styles.TitleWithCount("Diagnostics", total))

for _, file := range files {
if len(file.Items) == 0 {
continue
}

fmt.Fprintf(out, "%s\n", styles.SubHeader().Render(file.URI))

rows := make([][]string, len(file.Items))
for i, item := range file.Items {
location := fmt.Sprintf("%d:%d", item.Range.Start.Line+1, item.Range.Start.Character+1)
rows[i] = []string{item.Severity.Label, location, item.Source, item.Message}
}

fmt.Fprintf(out, "%s\n", styles.Table("Severity", "Location", "Source", "Message").Rows(rows...).Render())
}

return nil
}

func init() {
diagnosticsCmd.Flags().String("uri", "", "Filter to a single file (URI or absolute path)")

EditorCmd.AddCommand(diagnosticsCmd)
}
46 changes: 46 additions & 0 deletions cmd/editor/editor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package editor

import (
"errors"
"fmt"
"io"
"strings"

"github.com/kloudkit/ws-cli/internals/config"
"github.com/kloudkit/ws-cli/internals/env"
"github.com/spf13/cobra"
)

var errNoEditorOverSSH = errors.New(
"the editor commands are not available over SSH — there is no editor session to act on",
)

var EditorCmd = &cobra.Command{
Use: "editor",
Short: "Inspect and drive the active editor session",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if env.IsSSHSession() {
return errNoEditorOverSSH
}

return config.Bootstrap()
},
}

func emit(cmd *cobra.Command, body []byte, render func(io.Writer, []byte) error) error {
out := cmd.OutOrStdout()

if raw, _ := cmd.Flags().GetBool("raw"); raw {
if len(body) > 0 {
fmt.Fprintln(out, strings.TrimSpace(string(body)))
}

return nil
}

return render(out, body)
}

func init() {
EditorCmd.PersistentFlags().Bool("raw", false, "Output the raw JSON response without styling")
}
42 changes: 42 additions & 0 deletions cmd/editor/editor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package editor

import (
"testing"

"gotest.tools/v3/assert"
)

func TestPersistentPreRunEBlocksSSH(t *testing.T) {
t.Setenv("SSH_CONNECTION", "1.2.3.4 51000 5.6.7.8 22")

err := EditorCmd.PersistentPreRunE(EditorCmd, nil)
assert.ErrorContains(t, err, "SSH")
}

func TestParseSelection(t *testing.T) {
t.Run("SinglePositionIsEmptyRange", func(t *testing.T) {
got, err := parseSelection("12:5")
assert.NilError(t, err)

assert.Equal(t, got.Start.Line, 11)
assert.Equal(t, got.Start.Character, 4)
assert.Equal(t, got.End, got.Start)
})

t.Run("Range", func(t *testing.T) {
got, err := parseSelection("1:1-3:8")
assert.NilError(t, err)

assert.Equal(t, got.Start.Line, 0)
assert.Equal(t, got.Start.Character, 0)
assert.Equal(t, got.End.Line, 2)
assert.Equal(t, got.End.Character, 7)
})

t.Run("Invalid", func(t *testing.T) {
for _, bad := range []string{"", "5", "abc:1", "1:0", "0:1", "1:2-bogus"} {
_, err := parseSelection(bad)
assert.ErrorContains(t, err, "invalid selection", "input %q should fail", bad)
}
})
}
64 changes: 64 additions & 0 deletions cmd/editor/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package editor

import (
"encoding/json"
"fmt"
"io"

editoripc "github.com/kloudkit/ws-cli/internals/editor"
"github.com/kloudkit/ws-cli/internals/styles"
"github.com/spf13/cobra"
)

var listCmd = &cobra.Command{
Use: "list",
Short: "List the currently open editor tabs",
RunE: func(cmd *cobra.Command, args []string) error {
body, err := editoripc.FetchEditors()
if err != nil {
return err
}

return emit(cmd, body, renderEditors)
},
}

func renderEditors(out io.Writer, body []byte) error {
var tabs []editoripc.Tab
if err := json.Unmarshal(body, &tabs); err != nil {
return fmt.Errorf("error parsing editor response: %w", err)
}

if len(tabs) == 0 {
styles.PrintWarning(out, "No open editors")
return nil
}

fmt.Fprintf(out, "%s\n", styles.TitleWithCount("Open Editors", len(tabs)))

rows := make([][]string, len(tabs))
for i, tab := range tabs {
language := "-"
if tab.LanguageID != nil {
language = *tab.LanguageID
}

rows[i] = []string{tab.Path, language, check(tab.Active), check(tab.Dirty)}
}

fmt.Fprintf(out, "%s\n", styles.Table("Path", "Language", "Active", "Dirty").Rows(rows...).Render())

return nil
}

func check(value bool) string {
if value {
return "✓"
}

return ""
}

func init() {
EditorCmd.AddCommand(listCmd)
}
85 changes: 85 additions & 0 deletions cmd/editor/open.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package editor

import (
"fmt"
"strconv"
"strings"

editoripc "github.com/kloudkit/ws-cli/internals/editor"
"github.com/spf13/cobra"
)

var openCmd = &cobra.Command{
Use: "open <file>",
Short: "Open a file in the editor",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
newWindow, _ := cmd.Flags().GetBool("new-window")
preview, _ := cmd.Flags().GetBool("preview")
selection, _ := cmd.Flags().GetString("selection")

req := editoripc.OpenRequest{
Path: args[0],
Window: "reuse",
Preview: preview,
}

if newWindow {
req.Window = "new"
}

if selection != "" {
parsed, err := parseSelection(selection)
if err != nil {
return err
}

req.Selection = parsed
}

return editoripc.Open(req)
},
}

func parseSelection(value string) (*editoripc.Range, error) {
start, end, found := strings.Cut(value, "-")

from, err := parsePosition(start)
if err != nil {
return nil, err
}

to := from
if found {
if to, err = parsePosition(end); err != nil {
return nil, err
}
}

return &editoripc.Range{Start: from, End: to}, nil
}

func parsePosition(value string) (editoripc.Position, error) {
rawLine, rawCol, ok := strings.Cut(value, ":")
line, errLine := strconv.Atoi(rawLine)
col, errCol := strconv.Atoi(rawCol)

if !ok || errLine != nil || errCol != nil || line < 1 || col < 1 {
return editoripc.Position{}, fmt.Errorf(
"invalid selection %q (want LINE:COL[-LINE:COL], 1-based)", value,
)
}

return editoripc.Position{Line: line - 1, Character: col - 1}, nil
}

func init() {
openCmd.Flags().Bool("reuse-window", false, "Open in the current window as a tab (default)")
openCmd.Flags().Bool("new-window", false, "Open in a new window")
openCmd.Flags().Bool("preview", false, "Open as a preview tab (reuse-window only)")
openCmd.Flags().String("selection", "", "Select a range: LINE:COL[-LINE:COL] (1-based)")

openCmd.MarkFlagsMutuallyExclusive("reuse-window", "new-window")

EditorCmd.AddCommand(openCmd)
}
53 changes: 53 additions & 0 deletions cmd/editor/selection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package editor

import (
"encoding/json"
"fmt"
"io"

editoripc "github.com/kloudkit/ws-cli/internals/editor"
"github.com/kloudkit/ws-cli/internals/styles"
"github.com/spf13/cobra"
)

var selectionCmd = &cobra.Command{
Use: "selection",
Short: "Show the active editor's current selection",
RunE: func(cmd *cobra.Command, args []string) error {
body, err := editoripc.FetchSelection()
if err != nil {
return err
}

return emit(cmd, body, renderSelection)
},
}

func renderSelection(out io.Writer, body []byte) error {
if len(body) == 0 {
styles.PrintWarning(out, "No active selection")
return nil
}

var selection editoripc.Selection
if err := json.Unmarshal(body, &selection); err != nil {
return fmt.Errorf("error parsing selection response: %w", err)
}

location := fmt.Sprintf(
"%d:%d-%d:%d",
selection.Range.Start.Line+1, selection.Range.Start.Character+1,
selection.Range.End.Line+1, selection.Range.End.Character+1,
)

styles.PrintTitle(out, "Selection")
styles.PrintKeyValue(out, "Path", selection.Path)
styles.PrintKeyValue(out, "Range", location)
styles.PrintKeyCode(out, "Text", selection.Text)

return nil
}

func init() {
EditorCmd.AddCommand(selectionCmd)
}
2 changes: 1 addition & 1 deletion cmd/info/version.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package info

var Version = "0.0.65"
var Version = "0.0.66"
8 changes: 3 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"charm.land/fang/v2"
"github.com/kloudkit/ws-cli/cmd/clip"
"github.com/kloudkit/ws-cli/cmd/editor"
"github.com/kloudkit/ws-cli/cmd/feature"
"github.com/kloudkit/ws-cli/cmd/info"
"github.com/kloudkit/ws-cli/cmd/log"
Expand All @@ -26,11 +27,7 @@ var rootCmd = &cobra.Command{
Aliases: []string{"ws"},
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := config.RequireWorkspace(); err != nil {
return err
}
_, err := config.LoadEnvReference()
return err
return config.Bootstrap()
},
}

Expand All @@ -51,6 +48,7 @@ func Execute() {
func init() {
rootCmd.AddCommand(
clip.ClipCmd,
editor.EditorCmd,
feature.FeatureCmd,
serve.ServeCmd,
show.ShowCmd,
Expand Down
Loading
Loading