Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow printing SCIP index as JSON #147

Merged
merged 9 commits into from
May 3, 2023
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
2 changes: 1 addition & 1 deletion cmd/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func convertCommand() cli.Command {
Name: "to",
Usage: "Output path for LSIF index",
Destination: &convertFlags.to,
Value: "dump.lsif",
Value: "dump.lsif",
},
},
Action: func(c *cli.Context) error {
Expand Down
37 changes: 29 additions & 8 deletions cmd/print.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,59 @@
package main

import (
"io"
"math"

"github.com/k0kubun/pp/v3"
"github.com/urfave/cli/v2"
"math"
"google.golang.org/protobuf/encoding/protojson"

"github.com/sourcegraph/sourcegraph/lib/errors"
)

func printCommand() cli.Command {
var json bool
snapshot := cli.Command{
Name: "print",
Usage: "Print a SCIP index in a human-readable format for debugging",
Description: `WARNING: The output may change over time.
Do not rely on the output of this command in scripts`,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "json",
Usage: "Output in JSON format",
Destination: &json,
},
},
Action: func(c *cli.Context) error {
indexPath := c.Args().Get(0)
if indexPath == "" {
return errors.New("missing argument for path to SCIP index")
}
return printMain(indexPath)
return printMain(indexPath, json, c.App.Writer)
},
}
return snapshot
}

func printMain(indexPath string) error {
func printMain(indexPath string, json bool, out io.Writer) error {
index, err := readFromOption(indexPath)
if err != nil {
return err
}
pp.BufferFoldThreshold = math.MaxInt
prettyPrinter := pp.New()
prettyPrinter.SetExportedOnly(true)
_, err = prettyPrinter.Print(index)
return err
if json {
pp.BufferFoldThreshold = math.MaxInt

options := protojson.MarshalOptions{}

jsonBytes, err := options.Marshal(index)
out.Write(jsonBytes)
return err
} else {
prettyPrinter := pp.New()
prettyPrinter.SetExportedOnly(true)
prettyPrinter.SetOutput(out)
_, err = prettyPrinter.Print(index)
return err
}
}
69 changes: 69 additions & 0 deletions cmd/print_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"testing"

"github.com/sourcegraph/scip/bindings/go/scip"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)

func TestJSONPrinting(t *testing.T) {
app := scipApp()
// Redirect CLI writer to a buffer
var buff bytes.Buffer
app.Writer = io.Writer(&buff)
idx := makeIndex([]string{"a"}, stringMap{"f": {"b"}}, stringMap{"f": {"a", "b"}})

idx.Metadata = &scip.Metadata{ProjectRoot: "howdy"}

// Serialise SCIP index
indexBytes, err := proto.Marshal(idx)

// Write SCIP index to a temp file
dir := os.TempDir()
file, err := ioutil.TempFile(dir, "scip-cli-json-test*.scip")
if err != nil {
log.Fatal(err)
}
defer os.Remove(file.Name())

_, fErr := file.Write(indexBytes)
if fErr != nil {
log.Fatal(fErr)
}

// Run the JSON command with the temporary file
runErr := app.Run([]string{"scip", "print", "--json", file.Name()})
if runErr != nil {
log.Fatal(runErr)
}

type JsonIndex struct {
Metadata struct {
ProjectRoot string `json:"projectRoot"`
}
Documents []struct {
RelativePath string `json:"relativePath"`
} `json:"documents"`
}

var roundtripResult JsonIndex

bytes := buff.Bytes()

jsonErr := json.Unmarshal(bytes, &roundtripResult)
if jsonErr != nil {
log.Fatal(jsonErr)
}

require.Equal(t, roundtripResult.Metadata.ProjectRoot, "howdy")
require.Equal(t, len(roundtripResult.Documents), 1)
require.Equal(t, roundtripResult.Documents[0].RelativePath, "f")
}
20 changes: 18 additions & 2 deletions docs/CLI.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# SCIP CLI Reference

<!--toc:start-->

- [SCIP CLI Reference](#scip-cli-reference)
- [`scip convert`](#scip-convert)
- [`scip lint`](#scip-lint)
- [`scip print`](#scip-print)
- [`scip snapshot`](#scip-snapshot)
- [`scip stats`](#scip-stats)
<!--toc:end-->

```
NAME:
scip - SCIP Code Intelligence Protocol CLI
Expand All @@ -26,6 +36,7 @@ COMMANDS:
GLOBAL OPTIONS:
--help, -h show help (default: false)
--version, -v print the version (default: false)

```

## `scip convert`
Expand Down Expand Up @@ -78,6 +89,7 @@ DESCRIPTION:

OPTIONS:
--help, -h show help (default: false)
--json Output in JSON format (default: false)
```

## `scip snapshot`
Expand All @@ -96,8 +108,12 @@ DESCRIPTION:
and symbol information.

OPTIONS:
--from value Path to SCIP index file (default: index.scip)
--to value Path to output directory for snapshot files (default: scip-snapshot)
--comment-syntax value Comment syntax to use for snapshot files (default: "//")
--from value Path to SCIP index file (default: "index.scip")
--help, -h show help (default: false)
--project-root value Override project root in the SCIP file. For example, this can be helpful when the SCIP index was created inside a Docker image or created on another computer
--strict If true, fail fast on errors (default: true)
--to value Path to output directory for snapshot files (default: "scip-snapshot")
Comment on lines -99 to +116
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Why is this PR changing these lines? I thought the earlier PR that verified the documentation should've fixed this... 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests only verify that the global CLI help text is valid, not for any of the subcommands :(

It won't be much of an issue to add extra checks in a separate PR.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remove the unrelated changes from this PR? I can submit a PR tomorrow making the test more robust and fix this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remove the unrelated changes from this PR?

IMO, this is not a codebase with ridiculous velocity where unrelated changes are a problem - ongoing small improvements that aren't at odds with main purpose of the PR shouldn't be penalised by extra effort of reverting and resubmitting.

There are many small things that can be improved for which there is no plan and no dedicated effort - with a small number of contributors we should aim to fix things as we go.

You are free to follow up with a test for this (or I can do this) but updating and fixing small things in the docs should be a welcome addition to any PR.

Copy link
Contributor

@varungandhi-src varungandhi-src May 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First of all, my comment was not a blocking one.

ongoing small improvements that aren't at odds with main purpose of the PR shouldn't be penalised by extra effort of reverting and resubmitting.

I'm not trying to "penalise" something here... Ideally, these would not be part of the same PR (or commit) anyways. Normal commit hygiene IMO dictates that you'd commit related stuff in a single commit and move unrelated commit into separate PRs before submitting PRs. Even it got bundled into the same PR, if it were in different commits, it'd be easy to revert and push.

That's regardless of codebase velocity etc. My point isn't about velocity, it's about completeness. With drive-by improvements that get mixed in with other PRs, it's less clear what still needs fixing vs what doesn't. E.g. here, if I hadn't flagged this, then the point about the test missing might not have gone unnoticed.

That said, I don't think it's a big deal to leave it in.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a process worth discussing separately :) meanwhile, I added an issue so we don't forget: #152

```

## `scip stats`
Expand Down