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

Update README #25

Merged
merged 1 commit into from
Jan 29, 2025
Merged
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
237 changes: 149 additions & 88 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,124 +1,178 @@
# knife [![PkgGoDev](https://pkg.go.dev/badge/github.com/gostaticanalysis/knife)](https://pkg.go.dev/github.com/gostaticanalysis/knife)

`knife` lists type information of the named packages, one per line.
`knife` has `-f` option likes `go list` command.
**knife** is a CLI tool for inspecting Go packages, focusing on listing type and object information.
It provides a `-f` option similar to `go list`, allowing you to customize output via Go templates.

## Install
Additionally, this repository offers several **separate** CLI tools that work similarly:

```sh
$ go install github.com/gostaticanalysis/knife/cmd/knife@latest
```

## How to use
- **knife**: The main CLI (comprehensive tool for listing and inspecting Go package objects)
- **cutter**: A lightweight tool focusing on listing type information
- **typels**: Lists types in a package
- **objls**: Lists objects in a package
- **hagane**: A template-based code generator

### Options
---

See [Options](./_docs/options.md)
## Table of Contents

### Functions
1. [Installation](#installation)
2. [Usage](#usage)
1. [Common Options](#common-options)
2. [Functions for Templates](#functions-for-templates)
3. [Example Commands](#example-commands)
3. [Related Tools](#related-tools)
1. [cutter](#cutter)
2. [typels](#typels)
3. [objls](#objls)
4. [hagane](#hagane)
4. [License](#license)
5. [Author](#author)

See [Functions for a template](./_docs/funcs.md)
---

### Types
## Installation

A package is represented as [`knife.Package`](https://pkg.go.dev/github.com/gostaticanalysis/knife/#Package).
Most knife's types are struct and which hold data as fields because it is easy to use in a template.

### List `fmt` package's functions which name begins `Print`
### knife

```sh
$ knife -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
Print
Printf
Println
go install github.com/gostaticanalysis/knife/cmd/knife@latest
```

### List `fmt` package's exported types
### cutter

```sh
$ knife -f "{{range exported .Types}}{{.Name}}{{br}}{{end}}" fmt
Formatter
GoStringer
ScanState
Scanner
State
Stringer
go install github.com/gostaticanalysis/knife/cmd/cutter@latest
```

### List `net/http` package's functions which first parameter is context.Context
### typels

```sh
$ knife -f '{{range exported .Funcs}}{{.Name}} \
{{with .Signature.Params}}{{index . 0}}{{end}}{{br}}{{end}}' "net/http" | grep context.Context
NewRequestWithContext var ctx context.Context
go install github.com/gostaticanalysis/knife/cmd/typels@latest
```

### List net/http types which implements error interface
### objls

```sh
$ knife -f '{{range exported .Vars}}{{if implements . (typeof "error")}}{{.Name}}{{br}}{{end}}{{end}}' "net/http"
ErrAbortHandler
ErrBodyNotAllowed
ErrBodyReadAfterClose
ErrContentLength
ErrHandlerTimeout
ErrHeaderTooLong
ErrHijacked
ErrLineTooLong
ErrMissingBoundary
ErrMissingContentLength
ErrMissingFile
ErrNoCookie
ErrNoLocation
ErrNotMultipart
ErrNotSupported
ErrServerClosed
ErrShortBody
ErrSkipAltProtocol
ErrUnexpectedTrailer
ErrUseLastResponse
ErrWriteAfterFlush
go install github.com/gostaticanalysis/knife/cmd/objls@latest
```

### List position of fields which type is context.Context
### hagane

```sh
$ knife -f '{{range .Types}}{{$t := .}}{{with struct .}}{{range .Fields}}{{if identical . (typeof "context.Context")}}{{$t.Name}} - {{pos .}}{{br}}{{end}}{{end}}{{end}}{{end}}' "net/http"
Request - /usr/local/go/src/net/http/request.go:319:2
http2ServeConnOpts - /usr/local/go/src/net/http/h2_bundle.go:3878:2
http2serverConn - /usr/local/go/src/net/http/h2_bundle.go:4065:2
http2stream - /usr/local/go/src/net/http/h2_bundle.go:4146:2
initALPNRequest - /usr/local/go/src/net/http/server.go:3393:2
timeoutHandler - /usr/local/go/src/net/http/server.go:3241:2
wantConn - /usr/local/go/src/net/http/transport.go:1162:2
go install github.com/gostaticanalysis/knife/cmd/hagane@latest
```

### List type information of an AST node which is selected by a XPath expression
---

## Usage

### Common Options

`knife` works similarly to `go list`: You can specify a Go template using the `-f` option to customize the output.
For example:

```sh
$ knife -f '{{range .}}{{.Name}}:{{with .Scope}}{{.Names}}{{end}}{{br}}{{end}}' -xpath '//*[@type="FuncDecl"]/Name[starts-with(@Name, "Print")]' fmt
Printf:[a err format n]
Print:[a err n]
Println:[a err n]
knife -f "{{.}}" fmt
```

## cutter: lightweight version of knife for type information only
For more details, see [Options](./_docs/options.md).

### Functions for Templates

Within the template specified by the `-f` flag, you can use various helper functions alongside the standard Go `text/template` package. For instance:

- `exported`: Filters for exported items only
- `identical`: Checks if two types are identical
- `implements`: Checks if a type implements a given interface
- `typeof`: Returns the type by name
- `pos`: Retrieves the position (file and line) of a definition
- `br`: Inserts a line break in the output

See the full list of available functions in [Functions for a template](./_docs/funcs.md).

### Example Commands

Below are some common examples:

1. **List functions in the `fmt` package whose names begin with `Print`:**

```sh
knife -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
Print
Printf
Println
```

cutter is a lightweight version of knife.
2. **List exported types in the `fmt` package:**

```sh
knife -f "{{range exported .Types}}{{.Name}}{{br}}{{end}}" fmt
Formatter
GoStringer
ScanState
Scanner
State
Stringer
```

3. **List functions in `net/http` whose first parameter is `context.Context`:**

```sh
knife -f '{{range exported .Funcs}}{{.Name}} {{with .Signature.Params}}{{index . 0}}{{end}}{{br}}{{end}}' net/http | grep context.Context
NewRequestWithContext var ctx context.Context
```

4. **List variables in `net/http` that implement the `error` interface:**

```sh
knife -f '{{range exported .Vars}}{{if implements . (typeof "error")}}{{.Name}}{{br}}{{end}}{{end}}' net/http
ErrAbortHandler
ErrBodyNotAllowed
ErrBodyReadAfterClose
...
ErrWriteAfterFlush
```

5. **List the position of fields whose type is `context.Context`:**

```sh
knife -f '{{range .Types}}{{$t := .}}{{with struct .}}{{range .Fields}}{{if identical . (typeof "context.Context")}}{{$t.Name}} - {{pos .}}{{br}}{{end}}{{end}}{{end}}{{end}}' net/http
Request - /usr/local/go/src/net/http/request.go:319:2
http2ServeConnOpts - /usr/local/go/src/net/http/h2_bundle.go:3878:2
...
```

6. **Use an XPath expression to list AST node types (e.g., `FuncDecl` names starting with `Print`):**

```sh
knife -f '{{range .}}{{.Name}}:{{with .Scope}}{{.Names}}{{end}}{{br}}{{end}}' -xpath '//*[@type="FuncDecl"]/Name[starts-with(@Name, "Print")]' fmt
Printf:[a err format n]
Print:[a err n]
Println:[a err n]
```

---

## Related Tools

### cutter

`cutter` is a simplified version of `knife` that focuses on listing types.
Usage is almost identical to `knife`:

```sh
$ cutter -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
cutter -f "{{range exported .Funcs}}{{.Name}}{{br}}{{end}}" fmt | grep Print
Print
Printf
Println
```

## typels: print a list of types
### typels

typels prints list of types.
`typels` lists types in a package:

```sh
$ typels -f interface io | grep Writer
typels -f interface io | grep Writer
io.ByteWriter
io.ReadWriter
io.WriterAt
Expand All @@ -127,31 +181,38 @@ io.StringWriter
io.Writer
```

## objls: print a list of objects
### objls

objls prints list of objects.
`objls` lists objects in a package:

```sh
$ objls -f const net/http | grep Status | head -5
objls -f const net/http | grep Status | head -5
net/http.StatusBadGateway
net/http.StatusMovedPermanently
net/http.StatusNotFound
net/http.StatusCreated
net/http.StatusForbidden
```

### hagane

## hagane: template base code generator

hagane is a template base code generator.
`hagane` is a template-based code generator that can produce Go code based on a specified template and source file(s):

```sh
$ hagane -template template.go.tmpl -o sample_mock.go -data '{"type":"DB"}' sample.go
hagane -template template.go.tmpl -o sample_mock.go -data '{"type":"DB"}' sample.go
```

* `-o`: output file path (default stdout)
* `-f`: template format (default "{{.}}")
* `-template`: template file (data use `-f` option)
* `-data`: extra data as JSON format
- `-o`: Output file path (defaults to stdout)
- `-f`: Template format (defaults to `{{.}}`)
- `-template`: Template file (used if `-f` is not set)
- `-data`: Extra data (JSON) passed into the template

For a complete example, see [this hagane sample](./_examples/hagane/).

---

## License

This project is licensed under the [MIT License](./LICENSE).

See [the example](./_examples/hagane/).
Contributions are always welcome! Feel free to open issues or PRs for bugs and enhancements.
Loading