formatter

package
v0.0.0-...-0031c6d Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2018 License: GPL-3.0 Imports: 9 Imported by: 0

README

= Formatters Package
Alessandro Sanino <a.sanino@arduino.cc>
:source-highlighter: pygments
:pygments-style: manni

Formatters is a package which contains a useful and customizable set of formatters for your application.

. Formatter - A generic `interface` to format data.
. TextFormatter - Formats and Prints `interface{}` to Text String - Binded to `String()` method.
. JSONFormatter - Formats and Prints `interface{}` to JSON String - Binded to `json.Marshal()` method.

== Usage 
[source, go]
----
type TestType struct {
   field1 string `json:"field1,omitempty"` //same json tag as required by json.Marshal
   field2 int    `json:"field2"`           //same json tag as required by json.Marshal
}

var a Formatter = TextFormatter{}
var b JSONFormatter = JSONFormatter{} 

var test TestType{
    field1 : "test",
    field2 : 42,
}

var testString = a.Format(test) 
fmt.Println(testString) // Prints test.String()
a.Print(test) // Does the same.

testString = b.Format(test) 
fmt.Println(testString) // Prints { field1 : "test", field2 : "42" }
b.Print(test) // Does the same
----

=== The default formatter
There is a global formatter which can be used across other packages. You can set it with the `formatter.setFormatter(Formatter)` function.
[source, go]
----

type TestType struct {
   field1 string `json:"field1,omitempty"` //same json tag as required by json.Marshal
   field2 int    `json:"field2"`           //same json tag as required by json.Marshal
}

var test TestType{
    field1 : "test",
    field2 : 42,
}

formatter.setFormatter("text")
formatter.Print(test) // Prints string representation of the test struct, using String().
formatter.setFormatter("json")
formatter.Print(test) // Prints test struct as a JSON object.
----

== Custom Formatters
It is possible to add custom formatters with the `formatter.AddCustomFormatter(format, Formatter)` function.

Let's assume we want to add a YamlFormatter which parses to Yaml Objects.
[source, go]
----
// Solution 1 : YamlFormatter is a struct.
type YamlFormatter struct{}

func (yf YamlFormatter) Format(msg interface{}) (string, error) {
    // do something and return values.
}

//...
formatter.AddCustomFormatter("yaml", YamlFormatter{})
//...

// Solution 2 : YamlFormatter is a int8 or other primitive type, useful for formatters which does not need fields.
type YamlFormatter int8

func (yf YamlFormatter) Format(msg interface{}) (string, error) {
    // do something and return values.
}

//...
formatter.AddCustomFormatter("yaml", YamlFormatter(3)) // every int8 is valid, this is a cast.
----

== Printing Errors
Just use `formatter.PrintErrorMessage(string)` or `formatter.PrintError(error)` function.
[source, go]
----
var errormessage string = "Some error occurred"
formatter.PrintErrorMessage(errormessage) // Prints the error formatted properly.

err := functionWhichMayReturnAnError()
if err != nil {
    formatter.PrintError(err)
}
----

== Debug with JSON values
`JSONFormatter` by default does not print what it cannot parse (everything which is not a map or a struct).
If you are in a debugging session you will print an error message instead.
Sessions are opened by `formatterInstance.StartDebug()` and closed by `formatterInstance.EndDebug()`

[source, go]
----
formatter = JSONFormatter{}
formatter.StartDebug()
formatter.Print("Invalid String")
//Outputs "\"Invalid String\" is a non supported data, please use map or struct"
formatter.EndDebug()
----

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DownloadProgressBar

func DownloadProgressBar(d *downloader.Downloader, prefix string)

DownloadProgressBar prints a progress bar from a running download Request

func Format

func Format(msg interface{}) (string, error)

Format formats a message formatted using a Formatter specified by SetFormatter(...) function.

func IsCurrentFormat

func IsCurrentFormat(formatName string) bool

IsCurrentFormat returns if the specified format is the one currently set.

func IsSupported

func IsSupported(formatName string) bool

IsSupported returns whether the format specified is supported or not by the current set of formatters.

func Print

func Print(msg interface{}) error

Print prints a message formatted using a Formatter specified by SetFormatter(...) function.

Example
package main

import (
	"fmt"

	"github.com/arduino/arduino-cli/common/formatter"
)

type ExType struct {
	Field1 string `json:"field1"`
	Field2 int    `json:"field2"`
	Field3 struct {
		Inner1 string  `json:"inner1"`
		Inner2 float32 `json:"inner2"`
	} `json:"field3"`
}

func (et ExType) String() string {
	return fmt.Sprintln("Field1:", et.Field1) +
		fmt.Sprintln("Field2:", et.Field2) +
		fmt.Sprintln("Field3.Inner1:", et.Field3.Inner1) +
		fmt.Sprintln("Field3.Inner2:", et.Field3.Inner2)
}

func main() {
	var example ExType

	example.Field1 = "test"
	example.Field2 = 10
	example.Field3.Inner1 = "inner test"
	example.Field3.Inner2 = 10.432412

	formatter.SetFormatter("json")
	formatter.Print(example)
	formatter.SetFormatter("text")
	formatter.Print(example)
}
Output:

{"field1":"test","field2":10,"field3":{"inner1":"inner test","inner2":10.432412}}
Field1: test
Field2: 10
Field3.Inner1: inner test
Field3.Inner2: 10.432412
Example (Alternative)
formatter.SetFormatter("text")
formatter.Print(TestStruct{5})
formatter.Print("a string")

formatter.SetFormatter("json")
formatter.Print(TestStruct{10})
formatter.Print("a string")
Output:

VALUE = 5
a string
{"value":10}

func PrintError

func PrintError(err error, msg string)

PrintError formats and prints info about an error.

Err is the error to print full info while msg is the user friendly message to print.

Example
SetFormatter("text")
PrintErrorMessage("error message")
PrintError(fmt.Errorf("inner error message"), "outer error message")
SetFormatter("json")
PrintErrorMessage("error message")
PrintError(fmt.Errorf("inner error message"), "outer error message")
Output:

error message
Error: inner error message
outer error message
{"Message":"error message","Cause":""}
{"Message":"outer error message","Cause":"inner error message"}

func PrintErrorMessage

func PrintErrorMessage(msg string)

PrintErrorMessage formats and prints info about an error message.

func PrintResult

func PrintResult(res interface{})

PrintResult prints a value as a result from an operation.

func SetFormatter

func SetFormatter(formatName string) error

SetFormatter sets the defaults format to the one specified, if valid. Otherwise it returns an error.

Example
package main

import (
	"fmt"

	"github.com/arduino/arduino-cli/common/formatter"
)

type TestStruct struct {
	Value int `json:"value"`
}

func (ts TestStruct) String() string {
	return fmt.Sprint("VALUE = ", ts.Value)
}

func main() {
	formatter.SetFormatter("text")
	fmt.Println(formatter.Format(TestStruct{5}))
	formatter.SetFormatter("json")
	fmt.Println(formatter.Format(TestStruct{10}))
	fmt.Println(formatter.Format(5))

}
Output:

VALUE = 5 <nil>
{"value":10} <nil>
 int ignored

func SetLogger

func SetLogger(log *logrus.Logger)

SetLogger sets the logger for printed errors.

Types

type ErrorMessage

type ErrorMessage struct {
	Message  string
	CausedBy error
}

ErrorMessage represents an Error with an attached message.

func (ErrorMessage) MarshalJSON

func (err ErrorMessage) MarshalJSON() ([]byte, error)

MarshalJSON allows to marshal this object as a JSON object.

func (ErrorMessage) String

func (err ErrorMessage) String() string

String returns a string representation of the Error.

type Formatter

type Formatter interface {
	// Format formats a parameter if possible, otherwise it returns an error.
	Format(interface{}) (string, error)

	// DownloadProgressBar outputs a progress bar if possible. Waits until the download ends.
	DownloadProgressBar(d *downloader.Downloader, prefix string)
}

Formatter interface represents a generic formatter. It allows to print and format Messages.

func AddCustomFormatter

func AddCustomFormatter(formatName string, form Formatter) Formatter

AddCustomFormatter adds a custom formatter to the list of available formatters of this package.

If a key is already present, it is replaced and old Value is returned.

If format was not already added as supported, the custom formatter is simply added, and oldValue returns nil.

type JSONFormatter

type JSONFormatter struct {
	Debug bool // if false, errors are not shown. Unparsable inputs are skipped. Otherwise an error message is shown.
}

JSONFormatter is a Formatter that output JSON objects. Intermediate results or interactive messages are ignored.

func (*JSONFormatter) DownloadProgressBar

func (jf *JSONFormatter) DownloadProgressBar(d *downloader.Downloader, prefix string)

DownloadProgressBar implements Formatter interface

func (*JSONFormatter) Format

func (jf *JSONFormatter) Format(msg interface{}) (string, error)

Format implements Formatter interface

Example
package main

import (
	"fmt"

	"github.com/arduino/arduino-cli/common/formatter"
)

func main() {
	var example struct {
		Field1 string `json:"field1"`
		Field2 int    `json:"field2"`
		Field3 struct {
			Inner1 string  `json:"inner1"`
			Inner2 float32 `json:"inner2"`
		} `json:"field3"`
	}

	example.Field1 = "test"
	example.Field2 = 10
	example.Field3.Inner1 = "inner test"
	example.Field3.Inner2 = 10.432412

	var jf formatter.JSONFormatter
	fmt.Println(jf.Format(example))

	var example2 = 3.14
	fmt.Println(jf.Format(example2))

	var example3 float32 = 3.14
	fmt.Println(jf.Format(example3))

}
Output:

{"field1":"test","field2":10,"field3":{"inner1":"inner test","inner2":10.432412}} <nil>
 float64 ignored
 float32 ignored
Example (Debug)
package main

import (
	"fmt"

	"github.com/arduino/arduino-cli/common/formatter"
)

type TestStruct struct {
	Value int `json:"value"`
}

func (ts TestStruct) String() string {
	return fmt.Sprint("VALUE = ", ts.Value)
}

func main() {
	valid := TestStruct{20}
	invalid := "invalid"
	jf := formatter.JSONFormatter{
		Debug: false,
	}
	// using struct
	fmt.Println(jf.Format(valid))

	// using string (invalid sine it's not a struct or a map)
	fmt.Println(jf.Format(invalid))

	jf.Debug = true
	fmt.Println(jf.Format(valid))
	fmt.Println(jf.Format(invalid))

	// using map
	newValue := make(map[string]int)
	newValue["value2"] = 10

	fmt.Println(jf.Format(newValue))

}
Output:

{"value":20} <nil>
 string ignored
{"value":20} <nil>
 string ignored
{"value2":10} <nil>

type Message

type Message struct {
	Header string      `json:"header,omitempty"` // What is written before parsing Data.
	Data   interface{} `json:"data,omitempty"`   // The Data of the message, this should be the most important data to convert.
	Footer string      `json:"footer,omitempty"` // What is written after parsing Data.
}

Message represents a formattable message.

func (*Message) String

func (m *Message) String() string

String returns a string representation of the object.

type PrintFunc

type PrintFunc func(Formatter, interface{}) error

PrintFunc represents a function used to print formatted data.

type TextFormatter

type TextFormatter struct{}

TextFormatter represents a Formatter for a text console

func (*TextFormatter) DownloadProgressBar

func (tp *TextFormatter) DownloadProgressBar(d *downloader.Downloader, prefix string)

DownloadProgressBar implements Formatter interface

func (*TextFormatter) Format

func (tp *TextFormatter) Format(msg interface{}) (string, error)

Format implements Formatter interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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