rewrite

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2026 License: BSD-3-Clause Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rewrite

Go source-rewriting tools. gofmt taken it's logical conclusion.

  • Package documentation

  • gobackquote unifies string literals by converting them to backquoted strings where possible.

  • mininline inlines single-use or trivial functions automatically.

  • gotopsort sorts function and type declarations reverse-topologically (i.e, a function comes before all the functions that depend on it).

  • testsplit splits out tests into separate files by test type (example, fuzz, benchmark, 'regular').

  • rmdfmt formats Markdown files and the fenced code blocks inside it.

About .uf

The .uf (universal flag) files used to define the APIs may be unusual to you, but are hopefully self-explanatory. See that project for more details.

installation:

globally, from source

This will install the rewrite tools globally on your system.

git clone https://gitlab.com/efronlicht/rewrite.git
cd rewrite
for cmd in mininline gobackquote gotopsort testsplit rmdfmt; do
  go install -o 'somewhere/in/your/$PATH$'"/$cmd" ./cmd/$cmd
done
as a go tool
#!/usr/bin/env bash
for cmd in mininline gobackquote gotopsort testsplit rmdfmt; do
  go get -tool "gitlab.com/efronlicht/rewrite/cmd/$cmd@latest"
done

Quick Start:

List the diffs that gotopsort would make without actually applying them:

gotopsort -d ./...

rmdfmt needs the formatter for each language selected by -lang. Go blocks use gofumpt through the Go rmdfmt needs the formatter for each language selected by -lang. Go blocks use gofumpt through the Go package API; SQL blocks use Deno's unstable SQL formatter; other languages use these executables: luafmt, mdfmt, odinfmt, ruff, rustfmt, shfmt, uf, and zig. Run rmdfmt/install_formatters.sh to install the supported tools on a Homebrew and Rust setup. The command does not install missing tools while formatting.

Rewrite all the source code in the current directory using every tool and its subpackages, recursively (like gofmt):

#!/usr/bin/env bash
for cmd in mininline gobackquote gotopsort testsplit rmdfmt; do
  "$cmd" -w ./...
done

Documentation

Overview

Package rewrite contains shared mechanics for source-rewriting commands.

Index

Examples

Constants

This section is empty.

Variables

View Source
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

func DisplayPath(cwd, path string) string

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

func ListChanged(w io.Writer, cwd string, changes map[string]Change) error

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

func ListDirs(ctx context.Context, cwd string, env []string, pattern string) ([]string, error)

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

func RelativeListError(cwd, path string, err error) error

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

func WriteChange(path string, change Change) error

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 Change

type Change struct {
	Before       []byte
	After        []byte
	BeforeExists bool
}

Change contains the source bytes before and after a rewrite.

type Mode

type Mode uint8

Mode controls the output selected by a rewrite command.

const (
	ModePrint Mode = 'p'
	ModeDiff  Mode = 'd'
	ModeList  Mode = 'l'
	ModeWrite Mode = 'w'
)

func ParseMode

func ParseMode(write, list, diff bool) (Mode, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL