GithubHelp home page GithubHelp logo

isabella232 / litter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from yext/litter

0.0 0.0 0.0 52 KB

Litter is a pretty printer library for Go data structures to aid in debugging and testing.

License: MIT License

Go 100.00%

litter's Introduction

!Build Status

Litter

Litter is a pretty printer library for Go data structures to aid in debugging and testing.


litter is provided by


Sanity: The Headless CMS Construction Kit

It's named for the fact that it outputs literals, which you litter your output with. As a side benefit, all Litter output is compilable Go. You can use Litter to emit data during debug, and it's also really nice for "snapshot data" in unit tests, since it produces consistent, sorted output.

Litter was inspired by Spew, but focuses on terseness and readability.

Basic example

This:

type Person struct {
  Name   string
  Age    int
  Parent *Person
}

litter.Dump(Person{
  Name:   "Bob",
  Age:    20,
  Parent: &Person{
    Name: "Jane",
    Age:  50,
  },
})

will output:

Person{
  Name: "Bob",
  Age: 20,
  Parent: &Person{
    Name: "Jane",
    Age: 50,
  },
}

Use in tests

Litter is a great alternative to JSON or YAML for providing "snapshots" or example data. For example:

func TestSearch(t *testing.T) {
  result := DoSearch()

  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile("testdata.txt")
  if err != nil {
    // First run, write test data since it doesn't exist
		if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write("testdata.txt", actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf("Expected %s, got %s", expected, actual)
  }
}

The first run will use Litter to write the data to testdata.txt. On subsequent runs, the test will compare the data. Since Litter always provides a consistent view of a value, you can compare the strings directly.

Circular references

Litter detects circular references or aliasing, and will replace additional references to the same object with aliases. For example:

type Circular struct {
  Self *Circular
}

selfref := Circular{}
selfref.Self = &selfref

litter.Dump(selfref)

will output:

Circular { // p0
  Self: p0,
}

Installation

$ go get -u github.com/sanity-io/litter

Quick start

Add this import line to the file you're working in:

import "github.com/sanity-io/litter"

To dump a variable with full newlines, indentation, type, and aliasing information, use Dump or Sdump:

litter.Dump(myVar1)
str := litter.Sdump(myVar1)

litter.Dump(value, ...)

Dumps the data structure to STDOUT.

litter.Sdump(value, ...)

Returns the dump as a string

Configuration

You can configure litter globally by modifying the default litter.Config

// Strip all package names from types
litter.Config.StripPackageNames = true

// Hide private struct fields from dumped structs
litter.Config.HidePrivateFields = true

// Hide fields matched with given regexp if it is not nil. It is set up to hide fields generate with protoc-gen-go
litter.Config.FieldExclusions = regexp.MustCompile(`^(XXX_.*)$`)

// Sets a "home" package. The package name will be stripped from all its types
litter.Config.HomePackage = "mypackage"

// Sets separator used when multiple arguments are passed to Dump() or Sdump().
litter.Config.Separator = "\n"

// Use compact output: strip newlines and other unnecessary whitespace
litter.Config.Compact = true

litter.Options

Allows you to configure a local configuration of litter to allow for proper compartmentalization of state at the expense of some comfort:

  sq := litter.Options {
    HidePrivateFields: true,
    HomePackage: "thispack",
    Separator: " ",
  }

  sq.Dump("dumped", "with", "local", "settings")

Custom dumpers

Implement the interface Dumper on your types to take control of how your type is dumped.

type Dumper interface {
  LitterDump(w io.Writer)
}

Just write your custom dump to the provided stream, using multiple lines divided by "\n" if you need. Litter might indent your output according to context, and optionally decorate your first line with a pointer comment where appropriate.

A couple of examples from the test suite:

type CustomMultiLineDumper struct {}

func (cmld *CustomMultiLineDumper) LitterDump(w io.Writer) {
  w.Write([]byte("{\n  multi\n  line\n}"))
}

type CustomSingleLineDumper int

func (csld CustomSingleLineDumper) LitterDump(w io.Writer) {
  w.Write([]byte("<custom>"))
}

litter's People

Contributors

simen avatar atombender avatar erikgrinaker avatar rexxars avatar pshah28 avatar bradleyjkemp avatar sirkon avatar nochso avatar tmvrus avatar truefurby avatar opensourcesteve avatar dupoxy avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.