Documentation
¶
Overview ¶
Package rewrite contains shared mechanics for source-rewriting commands.
Index ¶
- Variables
- func DisplayPath(cwd, path string) string
- func ListChanged(w io.Writer, cwd string, changes map[string]Change) error
- func ListDirs(ctx context.Context, cwd string, env []string, pattern string) ([]string, error)
- func RelativeListError(cwd, path string, err error) error
- func WriteChange(path string, change Change) error
- func WriteUnifiedDiff(w io.Writer, before, after []byte, fromFile, toFile string, context int) error
- type Change
- type Mode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrMultipleModes = errors.New("use only one of -w, -l, or -d")
ErrMultipleModes reports that mutually exclusive rewrite modes (two or more of `-w`, `-l`, `-d`) were combined.
Functions ¶
func DisplayPath ¶
DisplayPath returns the shorter of filepath.Rel(cwd, path) and the cleaned absolute path, both slash-separated.,
DisplayPath("/workspace", "/workspace/cmd/../main.go") == "main.go"
Example ¶
ExampleDisplayPath makes an absolute path readable from a working directory. Parent segments are cleaned before the path is made relative.
package main
import (
"fmt"
"gitlab.com/efronlicht/rewrite"
)
func main() {
fmt.Println(rewrite.DisplayPath("/workspace", "/workspace/cmd/../main.go")) // we can eliminate the unnecessary ../ segment
fmt.Println(rewrite.DisplayPath("/a/b/c/d", "/b/e")) // the absolute path is shorter
}
Output: ./main.go /b/e
func ListChanged ¶
ListChanged writes changed paths in sorted path order.
ListChanged(w, "/workspace", map[string]Change{
"/workspace/b.go": {Before: []byte("old"), After: []byte("new")},
"/workspace/a.go": {Before: []byte("old"), After: []byte("new")},
})
// writes "a.go\nb.go\n"
Example ¶
ExampleListChanged prints changed files in path order. Unchanged files are skipped, and the remaining paths are sorted.
package main
import (
"bytes"
"fmt"
"gitlab.com/efronlicht/rewrite"
)
func main() {
changes := map[string]rewrite.Change{
"/workspace/a.go": {Before: []byte("old"), After: []byte("a")},
"/workspace/c.go": {Before: []byte("old"), After: []byte("old")}, // unchanged: should be ignored
"/workspace/b.go": {Before: []byte("old"), After: []byte("b")},
}
var output bytes.Buffer
if err := rewrite.ListChanged(&output, "/workspace", changes); err != nil {
panic(err)
}
fmt.Print(output.String())
}
Output: ./a.go ./b.go
func ListDirs ¶
ListDirs expands a Go package pattern into sorted, unique directories.
ListDirs(ctx, moduleDir, os.Environ(), ".") // returns one directory for a module containing only main.go.
Example ¶
ExampleListDirs finds Go package directories below a module. A module containing one Go file produces one package directory.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"gitlab.com/efronlicht/rewrite"
)
func main() {
directory, err := os.MkdirTemp("", "rewrite-example-")
if err != nil {
panic(err)
}
defer os.RemoveAll(directory)
if err := os.WriteFile(filepath.Join(directory, "go.mod"), []byte("module example.com/rewrite\n\ngo 1.23\n"), 0o644); err != nil {
panic(err)
}
if err := os.WriteFile(filepath.Join(directory, "main.go"), []byte("package main\n"), 0o644); err != nil {
panic(err)
}
directories, err := rewrite.ListDirs(context.Background(), directory, os.Environ(), ".")
if err != nil {
panic(err)
}
fmt.Println("package directories:", len(directories))
}
Output: package directories: 1
func RelativeListError ¶
RelativeListError rewrites an error's path for list-mode output.
RelativeListError("/workspace", "/workspace/pkg/file.go",
errors.New("/workspace/pkg/file.go: /workspace/pkg/file.go: parse error"))
// returns an error with message "pkg/file.go: parse error"
Example ¶
ExampleRelativeListError cleans duplicate absolute paths from a list error and converts them to relative paths as with DisplayPath.
package main
import (
"errors"
"fmt"
"gitlab.com/efronlicht/rewrite"
)
func main() {
const workdir = "/workspace"
const file = "/workspace/pkg/file.go"
fmt.Println(rewrite.RelativeListError(workdir, file, errors.New("/workspace/pkg/file.go: /workspace/pkg/file.go: parse error"))) // duplicate absolute path: we'd like this to collapse to the relative path
}
Output: pkg/file.go: parse error
func WriteChange ¶
WriteChange writes a changed file while preserving its existing permissions.
WriteChange("source.go", Change{After: []byte("package example\n")})
// source.go now contains "package example\n".
Example ¶
ExampleWriteChange writes a new file through the change API. A change without existing content creates the target file.
package main
import (
"fmt"
"os"
"path/filepath"
"gitlab.com/efronlicht/rewrite"
)
func main() {
directory, err := os.MkdirTemp("", "rewrite-example-")
if err != nil {
panic(err)
}
defer os.RemoveAll(directory)
path := filepath.Join(directory, "source.go")
if err := rewrite.WriteChange(path, rewrite.Change{After: []byte("package example\n")}); err != nil {
panic(err)
}
source, err := os.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Print(string(source))
}
Output: package example
func WriteUnifiedDiff ¶
func WriteUnifiedDiff(w io.Writer, before, after []byte, fromFile, toFile string, context int) error
WriteUnifiedDiff writes a unified diff with explicit file labels.
WriteUnifiedDiff(w, []byte("old\n"), []byte("new\n"), "a.go", "b.go", 3)
// writes headers for a.go and b.go and the changed lines -old and +new.
Example ¶
ExampleWriteUnifiedDiff prints a unified diff between two file versions. The hunk shows the old and new lines under the supplied file labels.
package main
import (
"bytes"
"fmt"
"gitlab.com/efronlicht/rewrite"
)
func main() {
var output bytes.Buffer
if err := rewrite.WriteUnifiedDiff(&output, []byte("old\n"), []byte("new\n"), "a.go", "b.go", 3); err != nil {
panic(err)
}
fmt.Print(output.String())
}
Output: --- a.go +++ b.go @@ -1,2 +1,2 @@ -old +new
Types ¶
type Mode ¶
type Mode uint8
Mode controls the output selected by a rewrite command.
func ParseMode ¶
ParseMode selects the command mode from its output flags.
mode, err := ParseMode(false, true, false) // mode == ModeList and err == nil
Example ¶
ExampleParseMode selects list mode without changing source files. Exactly one output flag selects the mode; here, -l corresponds to list mode.
package main
import (
"fmt"
"gitlab.com/efronlicht/rewrite"
)
func main() {
mode, err := rewrite.ParseMode(false, true, false)
if err != nil {
panic(err)
}
fmt.Printf("mode: %c\n", mode)
}
Output: mode: l
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
gobackquote
command
Command gobackquote rewrites eligible Go strings as backquoted literals.
|
Command gobackquote rewrites eligible Go strings as backquoted literals. |
|
gotopsort
command
Command gotopsort orders Go declarations by dependencies.
|
Command gotopsort orders Go declarations by dependencies. |
|
idsplit
command
Command idsplit moves selected Go declarations into a destination file.
|
Command idsplit moves selected Go declarations into a destination file. |
|
mininline
command
Command mininline applies safe Go function inlining rewrites.
|
Command mininline applies safe Go function inlining rewrites. |
|
rmdfmt
command
|
|
|
testsplit
command
Command testsplit splits generated tests into independent test files.
|
Command testsplit splits generated tests into independent test files. |
|
Package gobackquote rewrites eligible Go strings as backquoted literals.
|
Package gobackquote rewrites eligible Go strings as backquoted literals. |
|
Package gotopsort orders Go declarations by dependencies.
|
Package gotopsort orders Go declarations by dependencies. |
|
Package idsplit moves selected Go declarations and their private helper functions.
|
Package idsplit moves selected Go declarations and their private helper functions. |
|
internal
|
|
|
Package mininline implements the rewrite engine for safe Go function inlining.
|
Package mininline implements the rewrite engine for safe Go function inlining. |
|
Package parseerror defines errors with byte-accurate source locations.
|
Package parseerror defines errors with byte-accurate source locations. |
|
Package rmdfmt does recursive markdown formatting.
|
Package rmdfmt does recursive markdown formatting. |
|
Package testsplit splits generated tests into independent test files.
|
Package testsplit splits generated tests into independent test files. |