<commit_before>/*
Package adminsock provides a Unix domain socket -- with builtin
request dispatch -- for administration of a daemon.

COMMAND DISPATCH

Consider this example, showing an instance of adminsock being setup as
an echo server.

    func hollaback(s []string) ([]byte, error){
        return []byte(strings.Join(s, " ")), nil
    }

    func main() {
        d := make(adminsock.Dispatch)
        d["echo"] = hollaback
        as, err := adminsock.New("mysockname", d, 0)
        // if err != nil, adminsock is up and listening
        ...
    }

A function is defined for each request which adminsock will handle
(here there is just the one, hollaback()).

These functions are added to an instance of adminsock.Dispatch, which
is passed to adminsock.New(). Functions added to the Dispatch map must
have the signature

    func ([]string) ([]byte, error)

The Dispatch map keys form the command set that the instance of
adminsock understands. They are matched against the first word of text
being read from the socket.

Given the above example, if "echo foo bar baz" was sent to the socket,
then hollaback() would be invoked with:

    []string{"foo", "bar", "baz"}

And it would return:

    []byte("foo bar baz"), nil

If error is nil, then the returned byteslice will be written to the
socket as a response. If error is non-nil, then a message about an
internal error having occurred is sent (no program state is exposed to
the client).

If the first word of a request does not match a key in the Dispatch
map, an unrecognized command error will be sent. This message will
contain a list of all known commands. It is left to the user to
provide more comprehensive help.

MONITORING

Servers are typically event-driven and adminsock is designed around
this assumption. Once instantiated, all that needs to be done is
monitoring the Msgr channel. Somewhere in your code, there should be
something like:

    select {
    case msg := <-as.Msgr:
        // Handle adminsock notifications here.
    case your_other_stuff:
        ...
    }

Msgr sends instances of Msg, each of which contains string (Msg.Txt)
and an error (Msg.Err).

If Msg.Err is nil, then the message is purely informational (client
connects, dispatched commands, unknown commands, etc.).

If Msg.Err is not nil, then the message is an actual error being
passed along. Most errors will also be inoccuous (clients dropping
connections, etc.), and adminsock should continue operating with no
intervention.

However, if Msg.Err is not nil and Msg.Txt is "ENOLISTENER", then a
local networking error has occurred and the adminsock's listener
socket has gone away. If this happens, your adminsock instance is no
longer viable; clean it up and spawn a new one. You should, at worst,
drop a few connection attempts.

Msgr is a buffered channel, capable of holding 32 Msgs. Most writes to
it, however, will silently fail instead of blocking (which would lead
to deadlock should a shutdown be called for). The one exception to
this is the ENOLISTENER message, which will block.

SHUTDOWN AND CLEANUP

To halt an adminsock instance, call

    as.Quit()

This will immediately stop the instance from accepting new
connections, and will then wait for all existing connections to
terminate.

Be aware that if the instance was created with very long connection
timeouts (or no timeout at all), then Quit() will block for an
indeterminate length of time.

Once Quit() returns, the instance will have no more execution threads
and will exist only as a reference to an Adminsock struct.

If you are recovering from a ENOLISTENER condition, it's safe at this
point to spawn a new instance:

    case msg := <- as.Msgr:
        if msg.Err != nil && msg.Txt == "ENOLISTENER" {
            as.Quit()
            as = adminsock.New(d, 0)
        }

*/
package adminsock
<commit_msg>doc wip<commit_after>/*
Package adminsock provides a Unix domain socket -- with builtin
request dispatch -- for administration of a daemon.

COMMAND DISPATCH

Consider this example, showing an instance of adminsock being setup as
an echo server.

    func hollaback(s []string) ([]byte, error){
        return []byte(strings.Join(s, " ")), nil
    }

    func main() {
        d := make(adminsock.Dispatch)
        d["echo"] = hollaback
        as, err := adminsock.New("mysockname", d, 0)
        // if err != nil, adminsock is up and listening
        ...
    }

A function is defined for each request which adminsock will handle
(here there is just the one, hollaback()).

These functions are added to an instance of adminsock.Dispatch, which
is passed to adminsock.New(). Functions added to the Dispatch map must
have the signature

    func ([]string) ([]byte, error)

The Dispatch map keys form the command set that the instance of
adminsock understands. They are matched against the first word of text
being read from the socket.

Given the above example, if "echo foo bar baz" was sent to the socket,
then hollaback() would be invoked with:

    []string{"foo", "bar", "baz"}

And it would return:

    []byte("foo bar baz"), nil

If error is nil, then the returned byteslice will be written to the
socket as a response. If error is non-nil, then a message about an
internal error having occurred is sent (no program state is exposed to
the client).

If the first word of a request does not match a key in the Dispatch
map, an unrecognized command error will be sent. This message will
contain a list of all known commands. It is left to the user to
provide more comprehensive help.

MONITORING

Servers are typically event-driven and adminsock is designed around
this assumption. Once instantiated, all that needs to be done is
monitoring the Msgr channel. Somewhere in your code, there should be
something like:

    select {
    case msg := <-as.Msgr:
        // Handle adminsock notifications here.
    case your_other_stuff:
        ...
    }

Msgr receives instances of Msg, each of which contains a connection
number, a request number, a status code, a textual description, and an
error.

The connection and request numbers (Msg.Conn, Msg.Req) are included
solely for your client tracking/logging use.

As with HTTP, the status code tells you both generally and
specifically what has occured.

    Code Text                                      Classification
    ---- ----------------------------------------- --------------
     100 client connected                          Informational
     101 dispatching '%v'                                "
     197 ending session                                  "
     198 client disconnected                             "
     199 terminating listener socket                     "
     200 reply sent                                Success
     400 bad command '%v'                          Client error
     500 request failed                            Server Error
     501 deadline set failed; disconnecting client       "
     599 read from listener socket failed                "

Adminsock does not throw away or hide information, so messages which
are not errors according to this table may have a Msg.Err value other
than nil. Client disconnects, for instance, pass along the socket read
error which triggered them. Always test the value of Msg.Err before
using it.

Msgr is a buffered channel, capable of holding 32 Msgs. If Msgr fills
up, new messages will be dropped on the floor to avoid blocking. The
one exception to this is a message with a code of 599, which indicates
that the listener socket itself has stopped working.

If a message with code 599 is received, immediately halt the adminsock
instance as described in the next section.

SHUTDOWN AND CLEANUP

To halt an adminsock instance, call

    as.Quit()

This will immediately stop the instance from accepting new
connections, and will then wait for all existing connections to
terminate.

Be aware that if the instance was created with very long connection
timeouts (or no timeout at all), then Quit() will block for an
indeterminate length of time.

Once Quit() returns, the instance will have no more execution threads
and will exist only as a reference to an Adminsock struct.

If you are recovering from a listener socket error (a message with
code 599 was received), it is now safe to spawn a new instance if you
wish to do so:

    case msg := <- as.Msgr:
        if msg.Code == 599 {
            as.Quit()
            as = adminsock.New(...)
        }

*/
package adminsock
<|endoftext|>


<commit_before>// Package pgx is a PostgreSQL database driver.
/*
pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar
to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use
github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for
details.

Establishing a Connection

The primary way of establishing a connection is with `pgx.Connect`.

    conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))

The database connection string can be in URL or DSN format. Both PostgreSQL settings and pgx settings can be specified
here. In addition, a config struct can be created by `ParseConfig` and modified before establishing the connection with
`ConnectConfig` to configure settings such as tracing that cannot be configured with a connection string.

Connection Pool

`*pgx.Conn` represents a single connection to the database and is not concurrency safe. Use sub-package pgxpool for a
concurrency safe connection pool.

Query Interface

pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and
ForEachRow that are a simpler and safer way of processing rows than manually calling rows.Next(), rows.Scan, and
rows.Err().

CollectRows can be used collect all returned rows into a slice.

    rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5)
    numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32])
    if err != nil {
      return err
    }
    // numbers => [1 2 3 4 5]

ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows
directly.

    var sum, n int32
    rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10)
    _, err := pgx.ForEachRow(rows, []any{&n}, func(pgx.QueryFuncRow) error {
      sum += n
      return nil
    })
    if err != nil {
      return err
    }

pgx also implements QueryRow in the same style as database/sql.

    var name string
    var weight int64
    err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
    if err != nil {
        return err
    }

Use Exec to execute a query that does not return a result set.

    commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42)
    if err != nil {
        return err
    }
    if commandTag.RowsAffected() != 1 {
        return errors.New("No row found to delete")
    }

PostgreSQL Data Types

The package pgtype provides extensive and customizable support for converting Go values to and from PostgreSQL values
including array and composite types. See that package's documentation for details.

Transactions

Transactions are started by calling Begin.

    tx, err := conn.Begin(context.Background())
    if err != nil {
        return err
    }
    // Rollback is safe to call even if the tx is already closed, so if
    // the tx commits successfully, this is a no-op
    defer tx.Rollback(context.Background())

    _, err = tx.Exec(context.Background(), "insert into foo(id) values (1)")
    if err != nil {
        return err
    }

    err = tx.Commit(context.Background())
    if err != nil {
        return err
    }

The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions.
These are internally implemented with savepoints.

Use BeginTx to control the transaction mode.

BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the
transaction depending on the return value of the function. These can be simpler and less error prone to use.

    err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error {
        _, err := tx.Exec(context.Background(), "insert into foo(id) values (1)")
        return err
    })
    if err != nil {
        return err
    }

Prepared Statements

Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx
includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are
automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig
for information on how to customize or disable the statement cache.

Copy Protocol

Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a
CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface.
Or implement CopyFromSource to avoid buffering the entire data set in memory.

    rows := [][]any{
        {"John", "Smith", int32(36)},
        {"Jane", "Doe", int32(29)},
    }

    copyCount, err := conn.CopyFrom(
        context.Background(),
        pgx.Identifier{"people"},
        []string{"first_name", "last_name", "age"},
        pgx.CopyFromRows(rows),
    )

When you already have a typed array using CopyFromSlice can be more convenient.

    rows := []User{
        {"John", "Smith", 36},
        {"Jane", "Doe", 29},
    }

    copyCount, err := conn.CopyFrom(
        context.Background(),
        pgx.Identifier{"people"},
        []string{"first_name", "last_name", "age"},
        pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
            return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil
        }),
    )

CopyFrom can be faster than an insert with as few as 5 rows.

Listen and Notify

pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a
notification is received or the context is canceled.

    _, err := conn.Exec(context.Background(), "listen channelname")
    if err != nil {
        return nil
    }

    if notification, err := conn.WaitForNotification(context.Background()); err != nil {
        // do something with notification
    }

Tracing and Logging

pgx supports tracing by setting ConnConfig.Tracer.

In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer.

Lower Level PostgreSQL Functionality

pgx is implemented on top of github.com/jackc/pgconn a lower level PostgreSQL driver. The Conn.PgConn() method can be
used to access this lower layer.

PgBouncer

By default pgx automatically uses prepared statements. Prepared statements are incompaptible with PgBouncer. This can be
disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode.
*/
package pgx
<commit_msg>More doc tweaks<commit_after>// Package pgx is a PostgreSQL database driver.
/*
pgx provides a native PostgreSQL driver and can act as a database/sql driver. The native PostgreSQL interface is similar
to the database/sql interface while providing better speed and access to PostgreSQL specific features. Use
github.com/jackc/pgx/v5/stdlib to use pgx as a database/sql compatible driver. See that package's documentation for
details.

Establishing a Connection

The primary way of establishing a connection is with `pgx.Connect`.

    conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL"))

The database connection string can be in URL or DSN format. Both PostgreSQL settings and pgx settings can be specified
here. In addition, a config struct can be created by `ParseConfig` and modified before establishing the connection with
`ConnectConfig` to configure settings such as tracing that cannot be configured with a connection string.

Connection Pool

`*pgx.Conn` represents a single connection to the database and is not concurrency safe. Use package
github.com/jackc/pgx/v5/pgxpool for a concurrency safe connection pool.

Query Interface

pgx implements Query in the familiar database/sql style. However, pgx provides generic functions such as CollectRows and
ForEachRow that are a simpler and safer way of processing rows than manually calling rows.Next(), rows.Scan, and
rows.Err().

CollectRows can be used collect all returned rows into a slice.

    rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5)
    numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32])
    if err != nil {
      return err
    }
    // numbers => [1 2 3 4 5]

ForEachRow can be used to execute a callback function for every row. This is often easier than iterating over rows
directly.

    var sum, n int32
    rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10)
    _, err := pgx.ForEachRow(rows, []any{&n}, func(pgx.QueryFuncRow) error {
      sum += n
      return nil
    })
    if err != nil {
      return err
    }

pgx also implements QueryRow in the same style as database/sql.

    var name string
    var weight int64
    err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight)
    if err != nil {
        return err
    }

Use Exec to execute a query that does not return a result set.

    commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42)
    if err != nil {
        return err
    }
    if commandTag.RowsAffected() != 1 {
        return errors.New("No row found to delete")
    }

PostgreSQL Data Types

The package pgtype provides extensive and customizable support for converting Go values to and from PostgreSQL values
including array and composite types. See that package's documentation for details.

Transactions

Transactions are started by calling Begin.

    tx, err := conn.Begin(context.Background())
    if err != nil {
        return err
    }
    // Rollback is safe to call even if the tx is already closed, so if
    // the tx commits successfully, this is a no-op
    defer tx.Rollback(context.Background())

    _, err = tx.Exec(context.Background(), "insert into foo(id) values (1)")
    if err != nil {
        return err
    }

    err = tx.Commit(context.Background())
    if err != nil {
        return err
    }

The Tx returned from Begin also implements the Begin method. This can be used to implement pseudo nested transactions.
These are internally implemented with savepoints.

Use BeginTx to control the transaction mode.

BeginFunc and BeginTxFunc are functions that begin a transaction, execute a function, and commit or rollback the
transaction depending on the return value of the function. These can be simpler and less error prone to use.

    err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error {
        _, err := tx.Exec(context.Background(), "insert into foo(id) values (1)")
        return err
    })
    if err != nil {
        return err
    }

Prepared Statements

Prepared statements can be manually created with the Prepare method. However, this is rarely necessary because pgx
includes an automatic statement cache by default. Queries run through the normal Query, QueryRow, and Exec functions are
automatically prepared on first execution and the prepared statement is reused on subsequent executions. See ParseConfig
for information on how to customize or disable the statement cache.

Copy Protocol

Use CopyFrom to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. CopyFrom accepts a
CopyFromSource interface. If the data is already in a [][]any use CopyFromRows to wrap it in a CopyFromSource interface.
Or implement CopyFromSource to avoid buffering the entire data set in memory.

    rows := [][]any{
        {"John", "Smith", int32(36)},
        {"Jane", "Doe", int32(29)},
    }

    copyCount, err := conn.CopyFrom(
        context.Background(),
        pgx.Identifier{"people"},
        []string{"first_name", "last_name", "age"},
        pgx.CopyFromRows(rows),
    )

When you already have a typed array using CopyFromSlice can be more convenient.

    rows := []User{
        {"John", "Smith", 36},
        {"Jane", "Doe", 29},
    }

    copyCount, err := conn.CopyFrom(
        context.Background(),
        pgx.Identifier{"people"},
        []string{"first_name", "last_name", "age"},
        pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
            return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil
        }),
    )

CopyFrom can be faster than an insert with as few as 5 rows.

Listen and Notify

pgx can listen to the PostgreSQL notification system with the `Conn.WaitForNotification` method. It blocks until a
notification is received or the context is canceled.

    _, err := conn.Exec(context.Background(), "listen channelname")
    if err != nil {
        return nil
    }

    if notification, err := conn.WaitForNotification(context.Background()); err != nil {
        // do something with notification
    }

Tracing and Logging

pgx supports tracing by setting ConnConfig.Tracer.

In addition, the tracelog package provides the TraceLog type which lets a traditional logger act as a Tracer.

For debug tracing of the actual PostgreSQL wire protocol messages see github.com/jackc/pgx/v5/pgproto3.

Lower Level PostgreSQL Functionality

github.com/jackc/pgx/v5/pgconn contains a lower level PostgreSQL driver roughly at the level of libpq. pgx.Conn in
implemented on top of pgconn. The Conn.PgConn() method can be used to access this lower layer.

PgBouncer

By default pgx automatically uses prepared statements. Prepared statements are incompaptible with PgBouncer. This can be
disabled by setting a different QueryExecMode in ConnConfig.DefaultQueryExecMode.
*/
package pgx
<|endoftext|>


<commit_before>// Copyright 2015 Ola Holmström. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package melody implements a framework for dealing with WebSockets.
//
// Example
//
// A broadcasting echo server:
//
//  func main() {
//  	r := gin.Default()
//  	m := melody.New()
//  	r.GET("/ws", func(c *gin.Context) {
//  		m.HandleRequest(c.Writer, c.Request)
//  	})
//  	m.HandleMessage(func(s *melody.Session, msg []byte) {
//  		m.Broadcast(msg)
//  	})
//  	r.Run(":5000")
//  }

package melody
<commit_msg>fix doc.go<commit_after>// Copyright 2015 Ola Holmström. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package melody implements a framework for dealing with WebSockets.
//
// Example
//
// A broadcasting echo server:
//
//  func main() {
//  	r := gin.Default()
//  	m := melody.New()
//  	r.GET("/ws", func(c *gin.Context) {
//  		m.HandleRequest(c.Writer, c.Request)
//  	})
//  	m.HandleMessage(func(s *melody.Session, msg []byte) {
//  		m.Broadcast(msg)
//  	})
//  	r.Run(":5000")
//  }
package melody
<|endoftext|>


<commit_before>// Package q provides quick and dirty debugging output for tired programmers.
// Just type Q(foo)
// It's the fastest way to print a variable. Typing Q(foo) is easier than
// fmt.Printf("%#v whatever"). The output is easy on the eyes, with
// colorization, pretty-printing, and nice formatting. The output goes to
// the $TMPDIR/q log file, away from the noisy output of your program. Try it
// and give up using fmt.Printf() for good!
//
// For best results, import it like this:
// import . "github.com/y0ssar1an/q"

package q
<commit_msg>Make it look better in godoc<commit_after>/*
Package q provides quick and dirty debugging output for tired programmers.

q.Q() is a fast way to pretty-print variables. It's easier than typing
fmt.Printf("%#v", whatever). The output will be colorized and nicely formatted.
The output goes to $TMPDIR/q, away from the noise of stdout.

q exports a single Q() function. This is how you use it:
    import "github.com/y0ssar1an/q"
    ...
    q.Q(a, b, c)
*/
package q
<|endoftext|>


<commit_before>/*

Package strinterp provides a demonstration of morally correct string
interpolation.

This package was created in support of a blog post. It's the result of
about 20 hours of screwing around. I meant to keep it shorter, but
I started to have too much fun.

"Morally" correct means that I intend this to demonstrate a point about
API and language design, and that I don't necessarily intend this to
have any other utility.

However, as I developed my ideas this turned into a potentially
legitimately useful library, because instead of expressing all
the interpolations in terms of strings, they are all expressed in
terms of io.Writers. Since this library also permits inputting
the strings to be interpolated in the form of io.Readers, this means
that this entire library is fully capable of string interpolation in
the middle of streams, not just strings. Or, if you prefer, this is
a *stream* interpolator.

This documentation focuses on usage; for the reasoning behind the
design, consult the blog post.

Using String Interpolators

To use this package, create an interpolator object:

    i := strinterp.NewInterpolator()

You can then use it to interpolate strings. The simplest case is
concatenation:

    concated, err := i.InterpStr("concated: %RAW;%RAW;", str1, str2)

See the blog post for a discussion of why this is deliberately a bit
heavyweight and *designed* to call attention to the use of "RAW".

The "format string", the first element of the call, has the following
syntax:

    * Begins with %, ends with unescaped ;
    * Begins with the formatter/encoder name
    * Which may be followed by a colon, then args for that formatter
    * Which may then be followed by a pipe, and further specifications
      of encoders with optional arguments

You may backslash-escape any of the pipe, colon, or semicolon to pass them
through as arguments to the formatter/encoder, or backslash itself to pass
it through. To emit a raw %, use "%%;".

Here is an example of a format string that uses all these features:

    result, err := i.InterpStr("copy and paste: %json:nohtml|base64:url;", obj)

This will result in the standard encoding/json encoding being used on the
obj, then it will be converted to base64 using the encoding/base64
URLEncoding specification. You can continue piping to further encoders
indefinitely.

There are two different kinds of interpolators you can write, formatters
and encoders.

Formatters

A "formatter" is a routine that takes a Go value of some sort and
converts it to some bytes to be written out via a provided io.Writer.
A formatter has the function signature defined by the Formatter type,
which is:

    func (w io.Writer, arg interface{}, params []byte) error

When called, the function should first examine the parameters. If it
doesn't like the parameters, it should return ErrUnknownArguments,
properly filled out. (Note: It is important to be strict on the
parameters; if they don't make perfect sense, this is your only chance
to warn a user about that.) It should then take the arg and write it
out to the io.Writer in whatever manner makes sense, then return either
the error obtained during writing or nil if it was fully successful.

See the Formatter documentation below for more gritty details.

A formatter can only appear in the first position of a format
specification.

Encoders

An "encoder" is a routine that receives incoming io.Writer requests,
modifies them in a suitable manner, and passes them down to the next
io.Writer in the chain. In other words it takes []byte and generates
further []byte from them.

See the Encoder documentation below for more gritty details. See
examples.go for examples that the library ships with.

Configuring Your Interpolators

To configure your interpolator, you will need to add additional
formatters and encoders to the interpolator so it is aware of them.
NewInterpolator will return a bare *Interpolator with only the "RAW"
encoder. A DefaultInterpolator is also provided that comes preconfigured
for some HTML- and JSON-type-tasks. Consulting the "examples.go" file
in the godoc file listing below will highlight these formatters
and interpolators for your cribbing convenience.

Use the AddFormatter and AddEncoder functions to add these to your
interpolator to configure it.

(Since I find people often get a sort of mental block around this,
remember that, for instance, even though I provide you a default JSON
streamer based on the standard encoding/json library, if you have
something else you prefer, you can always specify a *different*
json formatter for your own usage.)

Once configured, for maximum utility I recommend putting string
interpolation into your environment object. See
http://www.jerf.org/iri/post/2929 .

Security Note

This is true of all string interpolators, but even more so of
strinterp. You MUST NOT feed user input as the interpolation source
string. In fact I'd suggest that one could make a good case that the first
parameter to strinterp should always be a constant string in the source
code base, and if I were going to write a local validation routine to plug
into go vet or something I'd probably add that as a rule.

Again, let me emphasize, this is NOT special to strinterp. You shouldn't
let users feed into the first parameter of fmt.Sprintf, or any other such
string, in any language for that matter. It's possible some are "safe" to
do that in, but given the wide range of havoc done over the years by
letting users control interpolation strings, I would just recommend against
it unconditionally.

Care should also be taken in the construction of filters. If they get much
"smarter" than a for loop iterating over bytes/runes and doing "something" with
them, you're starting to ask for trouble if user input passes through
them. Generally the entire point of strinterp is to handle potentially
untrusted input in a safe manner, so if you start "interpreting" user input
you could be creating openings for attackers.

*/
package strinterp
<commit_msg>Hopefully final changes to the docs.<commit_after>/*

Package strinterp provides a demonstration of morally correct string
interpolation.

This package was created in support of a blog post. It's the result of
about 20 hours of screwing around. I meant to keep it shorter, but
I started to have too much fun.

"Morally" correct means that I intend this to demonstrate a point about
API and language design, and that any actual utility is a bit
coincidental.

That said, as this developed it became potentially more useful than
I had initially intended, because instead of expressing all
the interpolations in terms of strings, they are all expressed in
terms of io.Writers. Since this library also permits inputting
the strings to be interpolated in the form of io.Readers, this means
that this entire library is fully capable of string interpolation in
the middle of streams, not just strings. Or, if you prefer, this is
a *stream* interpolator. The "str" in "strinterp" is pleasingly
ambiguous.

This documentation focuses on usage; for the reasoning behind the
design, consult the blog post.

Using String Interpolators

To use this package, create an interpolator object:

    i := strinterp.NewInterpolator()

You can then use it to interpolate strings. The simplest case is
concatenation:

    concated, err := i.InterpStr("concatenated: %RAW;%RAW;", str1, str2)

See the blog post for a discussion of why this is deliberately a bit
heavyweight and *designed* to call attention to the use of "RAW", rather
than making such usage a simple and quiet default behavior.

The "format string", the first element of the call, has the following
syntax:

    * Begins with %, ends with unescaped ;
    * Begins with the formatter/encoder name
    * Which may be followed by a colon, then args for that formatter
    * Which may then be followed by a pipe, and further specifications
      of encoders with optional arguments

You may backslash-escape any of the pipe, colon, or semicolon to pass them
through as arguments to the formatter/encoder, or backslash itself to pass
it through. (The formatter/encoder will of course receive the decoded
bytes without the escaping backslash.) To emit a raw %, use "%%;".

Here is an example of a format string that uses all these features:

    result, err := i.InterpStr("copy and paste: %json|base64:url;", obj)

This will result in the standard encoding/json encoding being used on the
obj, then it will be converted to base64, which will use the encoding/base64
URLEncoding due to the "url" argument being passed. You can continue
piping to further encoders indefinitely.

There are two different kinds of interpolators you can write, formatters
and encoders.

Formatters

A "formatter" is a routine that takes a Go value of some sort and
converts it to some bytes to be written out via a provided io.Writer.
A formatter has the function signature defined by the Formatter type,
which is:

    func (w io.Writer, arg interface{}, params []byte) error

When called, the function should first examine the parameters. If it
doesn't like the parameters, it should return ErrUnknownArguments,
properly filled out. (Note: It is important to be strict on the
parameters; if they don't make perfect sense, this is your only chance
to warn a user about that.) It should then take the arg and write it
out to the io.Writer in whatever manner makes sense, then return either
the error obtained during writing or nil if it was fully successful.

You want to write a Formatter when you are trying to convert something
that isn't already a string, []byte, or io.Reader into output.
Therefore it only makes sense in the first element of a formatter's
pipeline (the "json" in the previous example), because only a
formatter can handle arbitrary objects.

See the Formatter documentation below for more gritty details.

Encoders

An "encoder" is a routine that receives incoming io.Writer requests,
modifies them in a suitable manner, and passes them down to the next
io.Writer in the chain. In other words it takes []byte and generates
further []byte from them.

You want to write an Encoder when either you want to transform input
going through it (like escaping), or when you know the only valid
input coming in will be in the form of a string, []byte, or io.Reader,
which strinterp will automatically handle feeding down the encoder
pipeline.

See the Encoder documentation below for more gritty details.

Configuring Your Interpolators

To configure your interpolator, you will need to add additional
formatters and encoders to the interpolator so it is aware of them.
NewInterpolator will return a bare *Interpolator with only the "RAW"
encoder. A DefaultInterpolator is also provided that comes preconfigured
for some HTML- and JSON-type-tasks. Consulting the "examples.go" file
in the godoc file listing below will highlight these formatters
and interpolators for your cribbing convenience.

Use the AddFormatter and AddEncoder functions to add these to your
interpolator to configure it.

(Since I find people often get a sort of mental block around this,
remember that, for instance, even though I provide you a default JSON
streamer based on the standard encoding/json library, if you have
something else you prefer, you can always specify a *different*
json formatter for your own usage.)

Once configured, for maximum utility I recommend putting string
interpolation into your environment object. See
http://www.jerf.org/iri/post/2929 .

Direct Encoder Usage

It is also possible to directly use the Encoders, as their type signature
tends to imply (note how you don't have to pass them any *Interpolator
or any other context). Ideally you instantiate a WriterStack around your
target io.Writer and .Push encoders on top of that, as WriterStack handles
some corner cases around Encoders that want to be "Close"d, then call
.Finish() on the WriterStack when done, which DOES NOT close the
underlying io.Writer. This is probably the maximally-performing way to
do this sort of encoding in a stream.

Security Note

This is true of all string interpolators, but even more so of
strinterp since it can be hooked up to arbitrary formatters and
encoders. You MUST NOT feed user input as the interpolation source
string. In fact I'd suggest that one could make a good case that the first
parameter to strinterp should always be a constant string in the source
code base, and if I were going to write a local validation routine to plug
into go vet or something I'd probably add that as a rule.

Again, let me emphasize, this is NOT special to strinterp. You shouldn't
let users feed into the first parameter of fmt.Sprintf, or any other such
string, in any language for that matter. It's possible some are "safe" to
do that in, but given the wide range of havoc done over the years by
letting users control interpolation strings, I would just recommend against
it unconditionally. Even when "safe" it probably isn't what you mean.

Care should also be taken in the construction of filters. If they get much
"smarter" than a for loop iterating over bytes/runes and doing "something" with
them, you're starting to ask for trouble if user input passes through
them. Generally the entire point of strinterp is to handle potentially
untrusted input in a safe manner, so if you start "interpreting" user input
you could be creating openings for attackers.

Contributing

I'm interested in pull requests for more Formatters and Encoders for the
"default Interpolator", though ideally only for things in the standard
library.

*/
package strinterp
<|endoftext|>


<commit_before>// Copyright (c) 2017 Marc René Arns. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

/*
  Package midi provides interfaces for reading and writing of MIDI messages.

  Since they are handled slightly different, this packages introduces the terminology of
  "live" MIDI reading/writing for dealing with MIDI messages as "over the wire" (in realtime)
  as opposed to smf MIDI reading/writing to Standard MIDI Files (SMF).

  However both variants can be used with io.Writer and io.Reader and can thus be "streamed".

  This package provides a Reader and Writer interface that is common to live and SMF MIDI handling.
  This should allow to easily develop transformations (e.g. quantization,
  filtering) that may be used in both cases.

  One package providing a unified access in both cases is the handler package for reading MIDI data.

    github.com/gomidi/midi/handler    (reading MIDI messages live or from SMF files)

  The core implementations can be found here:

    github.com/gomidi/midi/midireader (live reading)
    github.com/gomidi/midi/midiwriter (live writing)
    github.com/gomidi/midi/smf/smfreader   (SMF reading)
    github.com/gomidi/midi/smf/smfwriter   (SMF writing)
    github.com/gomidi/midi/smf/smfmodify   (SMF modification)

  The MIDI messages themselves that can be written or analyzed can be found here:

    github.com/gomidi/midi/midimessage/channel    (Channel Messages)
    github.com/gomidi/midi/midimessage/cc         (Control Change Messages)
    github.com/gomidi/midi/midimessage/meta       (Meta Messages)
    github.com/gomidi/midi/midimessage/realtime   (System Realtime Messages)
    github.com/gomidi/midi/midimessage/syscommon  (System Common messages)
    github.com/gomidi/midi/midimessage/sysex      (System Exclusive messages)

  Please keep in mind that that not all kinds of MIDI messages can be used in both scenarios.

  System Realtime and System Common Messages are restricted to "over the wire",
  while Meta Messages are restricted to SMF files. However System Realtime and System Common Messages
  can be saved inside a SMF file which the help of SysEx escaping (F7).

*/
package midi
<commit_msg>fix docs<commit_after>// Copyright (c) 2017 Marc René Arns. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

/*
  Package midi provides interfaces for reading and writing of MIDI messages.

  Since they are handled slightly different, this packages introduces the terminology of
  "live" MIDI reading/writing for dealing with MIDI messages as "over the wire" (in realtime)
  as opposed to smf MIDI reading/writing to Standard MIDI Files (SMF).

  However both variants can be used with io.Writer and io.Reader and can thus be "streamed".

  This package provides a Reader and Writer interface that is common to live and SMF MIDI handling.
  This should allow to easily develop transformations (e.g. quantization,
  filtering) that may be used in both cases.

  One package providing a unified access in both cases is the handler package for reading MIDI data.

    github.com/gomidi/midi/midihandler    (reading MIDI messages live or from SMF files)

  The core implementations can be found here:

    github.com/gomidi/midi/midireader (live reading)
    github.com/gomidi/midi/midiwriter (live writing)
    github.com/gomidi/midi/smf/smfreader   (SMF reading)
    github.com/gomidi/midi/smf/smfwriter   (SMF writing)
    github.com/gomidi/midi/smf/smfmodify   (SMF modification)

  The MIDI messages themselves that can be written or analyzed can be found here:

    github.com/gomidi/midi/midimessage/channel    (Channel Messages)
    github.com/gomidi/midi/midimessage/cc         (Control Change Messages)
    github.com/gomidi/midi/midimessage/meta       (Meta Messages)
    github.com/gomidi/midi/midimessage/realtime   (System Realtime Messages)
    github.com/gomidi/midi/midimessage/syscommon  (System Common messages)
    github.com/gomidi/midi/midimessage/sysex      (System Exclusive messages)

  Please keep in mind that that not all kinds of MIDI messages can be used in both scenarios.

  System Realtime and System Common Messages are restricted to "over the wire",
  while Meta Messages are restricted to SMF files. However System Realtime and System Common Messages
  can be saved inside a SMF file which the help of SysEx escaping (F7).

*/
package midi
<|endoftext|>


<commit_before>/*
Package gobotto offers a simple library for fetching, parsing and dealing with `robots.txt` files.

Gobotto has the following methods:

	* gobotto.RobotsURL(URL string)
	* gobotto.Fetch(URL string)
	* gobotto.Parse(robotsContents string)
	* gobotto.IsAllowed(userAgent string, route string, rules RobotsRules)
*/
package gobotto
<commit_msg>Documented go.doc file aggregating the other subpackages<commit_after>/*
  Copyright? Are you kidding? No rights reserved.
  Use of this source code is totally free, do whatever you want with it.
  I'm just giving something back to the internet, which has helped me with so many things in life I can't even count.
  Thanks internet, you are by far mankind's greatest invention!
*/

/*
  Package gobotto offers a simple library for fetching, parsing and checking permissions against `robots.txt` files.

  Gobotto has the following methods:

   gobotto.RobotsURL(URL string)

   gobotto.Fetch(URL string)

   gobotto.Parse(robotsContents string)

   gobotto.IsAllowed(userAgent string, route string, rules RobotsRules)
*/
package gobotto

import (
	// models module
	_ "github.com/lucasfcosta/gobotto/models"
	// robotsurl module
	_ "github.com/lucasfcosta/gobotto/robotsurl"
	// fetch module
	_ "github.com/lucasfcosta/gobotto/fetch"
	// parse module
	_ "github.com/lucasfcosta/gobotto/parse"
	// isallowed module
	_ "github.com/lucasfcosta/gobotto/isallowed"
)
<|endoftext|>


<commit_before>/*
 * This file is part of the libvirt-go-xml project
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * Copyright (C) 2017 Red Hat, Inc.
 *
 */

// Package libvirt-go-xml defines structs for parsing libvirt XML schemas
//
// The libvirt API uses XML schemas/documents to describe the configuration
// of many of its managed objects. Thus when using the libvirt-go package,
// it is often neccessary to either parse or format XML documents. This
// package defines a set of Go structs which have been annotated for use
// with the encoding/xml API to manage libvirt XML documents.
//
// Example creating a domain XML document from configuration:
//
//  import (
//   "github.com/libvirt/libvirt-go-xml"
//  )
//
//  domcfg := &libvirtxml.Domain{Type: "kvm", Name: "demo",
//                               UUID: "8f99e332-06c4-463a-9099-330fb244e1b3",
//                               ....}
//  xmldoc, err := domcfg.Marshal()
//
// Example parsing a domainXML document, in combination with libvirt-go
//
//  import (
//    "github.com/libvirt/libvirt-go"
//    "github.com/libvirt/libvirt-go-xml"
//    "fmt"
//  )
//
//  conn, err := libvirt.NewConnect("qemu:///system")
//  dom, err := conn.LookupDomainByName("demo")
//  xmldoc, err := dom.GetXMLDesc(0)
//
//  domcfg := &libvirtxml.Domain{}
//  err := domcfg.Unmarshal(xmldoc)
//
//  fmt.Printf("Virt type %s", domcfg.Type)
//
package libvirtxml
<commit_msg>doc: Variable is already defined<commit_after>/*
 * This file is part of the libvirt-go-xml project
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * Copyright (C) 2017 Red Hat, Inc.
 *
 */

// Package libvirt-go-xml defines structs for parsing libvirt XML schemas
//
// The libvirt API uses XML schemas/documents to describe the configuration
// of many of its managed objects. Thus when using the libvirt-go package,
// it is often neccessary to either parse or format XML documents. This
// package defines a set of Go structs which have been annotated for use
// with the encoding/xml API to manage libvirt XML documents.
//
// Example creating a domain XML document from configuration:
//
//  import (
//   "github.com/libvirt/libvirt-go-xml"
//  )
//
//  domcfg := &libvirtxml.Domain{Type: "kvm", Name: "demo",
//                               UUID: "8f99e332-06c4-463a-9099-330fb244e1b3",
//                               ....}
//  xmldoc, err := domcfg.Marshal()
//
// Example parsing a domainXML document, in combination with libvirt-go
//
//  import (
//    "github.com/libvirt/libvirt-go"
//    "github.com/libvirt/libvirt-go-xml"
//    "fmt"
//  )
//
//  conn, err := libvirt.NewConnect("qemu:///system")
//  dom, err := conn.LookupDomainByName("demo")
//  xmldoc, err := dom.GetXMLDesc(0)
//
//  domcfg := &libvirtxml.Domain{}
//  err = domcfg.Unmarshal(xmldoc)
//
//  fmt.Printf("Virt type %s", domcfg.Type)
//
package libvirtxml
<|endoftext|>


<commit_before>/*
Package core provides a pure handlers (or middlewares) stack so you can perform actions downstream, then filter and manipulate the response upstream.

The handlers stack

A handler is a function that receives a context.
It can be registered with Use and has the possibility to break the stream or to continue with the next handler in the stack.

Example of a logger followed by the response writing:

	// Log
	core.Use(func(c *core.Context) {
		start := time.Now()                                                           // Before the response.
		c.Next()                                                                      // Execute next handler in the stack.
		log.Printf(" %s  %s  %s", c.Request.Method, c.Request.URL, time.Since(start)) // After the response.
	})

	// Response
	core.Use(func(c *core.Context) {
		fmt.Fprint(c.ResponseWriter, "Hello, World!")
	})

	// Run server
	core.Run()

When using Run, your app is reachable at http://localhost:8080 by default.

If you need more flexibility, you can make a new handlers stack, which is fully compatible with the net/http.Handler interface:

	hs := core.NewHandlersStack()

	hs.Use(func(c *core.Context) {
		fmt.Fprint(c.ResponseWriter, "Hello, World!")
	})

	http.ListenAndServe(":8080", hs)

Here is the visualization of the serving flow when using log, secure and compress handlers:

	request open
	  |- log start
	  |--- secure start
	  |----- compress start
	  |------- response write
	  |----- compress end
	  |--- secure end
	  |- log end
	request close

Flags

These flags are preset:

	-address
		The address to listen and serving on.
		Value is saved in Address.
	-production
		Run the server in production environment.
		Some third-party handlers may have different behaviors depending on the environment.
		Value is saved in Production.

It's up to you to call
	flag.Parse()
in your main function if you want to use them.

Panic recovering

When using Run, your server always recovers from panics, logs the error with stack, and sends a 500 Internal Server Error.
If you want to use a custom handler on panic, give one to HandlePanic.

Handlers and helpers

No handlers or helpers are bundled in the core: it does one thing and does it well.
That's why you need to import all and only the handlers or helpers you need:

	compress
		Clever response compressing
		https://godoc.org/github.com/volatile/compress
	cors
		Cross-Origin Resource Sharing support
		https://godoc.org/github.com/volatile/cors
	i18n
		Simple internationalization
		https://godoc.org/github.com/volatile/i18n
	log
		Requests logging
		https://godoc.org/github.com/volatile/log
	response
		Readable response helper
		https://godoc.org/github.com/volatile/response
	route
		Flexible routing helper
		https://godoc.org/github.com/volatile/route
	secure
		Quick security wins
		https://godoc.org/github.com/volatile/secure
	static
		Simple assets serving
		https://godoc.org/github.com/volatile/static
*/
package core
<commit_msg>Update doc<commit_after>/*
Package core provides a pure handlers (or middlewares) stack so you can perform actions downstream, then filter and manipulate the response upstream.

The handlers stack

A handler is a function that receives a context.
It can be registered with Use and has the possibility to break the stream or to continue with the next handler in the stack.

Example of a logger followed by the response writing:

	// Log
	core.Use(func(c *core.Context) {
		start := time.Now()                                                           // Before the response.
		c.Next()                                                                      // Execute the next handler in the stack (in this case, the response).
		log.Printf(" %s  %s  %s", c.Request.Method, c.Request.URL, time.Since(start)) // After the response.
	})

	// Response
	core.Use(func(c *core.Context) {
		fmt.Fprint(c.ResponseWriter, "Hello, World!")
	})

	// Run server
	core.Run()

When using Run, your app is reachable at http://localhost:8080 by default.

If you need more flexibility, you can make a new handlers stack, which is fully compatible with the net/http.Handler interface:

	hs := core.NewHandlersStack()

	hs.Use(func(c *core.Context) {
		fmt.Fprint(c.ResponseWriter, "Hello, World!")
	})

	http.ListenAndServe(":8080", hs)

Here is the visualization of the serving flow when using log, secure and compress handlers:

	request open
	  |- log start
	  |--- secure start
	  |----- compress start
	  |------- response write
	  |----- compress end
	  |--- secure end
	  |- log end
	request close

Flags

These flags are preset:

	-address
		The address to listen and serving on.
		Value is saved in Address.
	-production
		Run the server in production environment.
		Some third-party handlers may have different behaviors depending on the environment.
		Value is saved in Production.

It's up to you to call
	flag.Parse()
in your main function if you want to use them.

Panic recovering

When using Run, your server always recovers from panics, logs the error with stack, and sends a 500 Internal Server Error.
If you want to use a custom handler on panic, give one to HandlePanic.

Handlers and helpers

No handlers or helpers are bundled in the core: it does one thing and does it well.
That's why you need to import all and only the handlers or helpers you need:

	compress
		Clever response compressing
		https://godoc.org/github.com/volatile/compress
	cors
		Cross-Origin Resource Sharing support
		https://godoc.org/github.com/volatile/cors
	i18n
		Simple internationalization
		https://godoc.org/github.com/volatile/i18n
	log
		Requests logging
		https://godoc.org/github.com/volatile/log
	response
		Readable response helper
		https://godoc.org/github.com/volatile/response
	route
		Flexible routing helper
		https://godoc.org/github.com/volatile/route
	secure
		Quick security wins
		https://godoc.org/github.com/volatile/secure
	static
		Simple assets serving
		https://godoc.org/github.com/volatile/static
*/
package core
<|endoftext|>


<commit_before>// Copyright 2015 Peter Goetz
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pegomock

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/petergtz/pegomock/internal/verify"
)

var GlobalFailHandler FailHandler

func RegisterMockFailHandler(handler FailHandler) {
	GlobalFailHandler = handler
}
func RegisterMockTestingT(t *testing.T) {
	RegisterMockFailHandler(BuildTestingTGomegaFailHandler(t))
}

var lastInvocation *invocation
var globalArgMatchers Matchers

func RegisterMatcher(matcher Matcher) {
	globalArgMatchers.append(matcher)
}

type invocation struct {
	genericMock *GenericMock
	MethodName  string
	Params      []Param
	ReturnTypes []reflect.Type
}

type GenericMock struct {
	mockedMethods map[string]*mockedMethod
}

func (genericMock *GenericMock) Invoke(methodName string, params []Param, returnTypes []reflect.Type) ReturnValues {
	lastInvocation = &invocation{
		genericMock: genericMock,
		MethodName:  methodName,
		Params:      params,
		ReturnTypes: returnTypes,
	}
	return genericMock.getOrCreateMockedMethod(methodName).Invoke(params)
}

func (genericMock *GenericMock) stub(methodName string, paramMatchers []Matcher, returnValues ReturnValues) {
	genericMock.stubWithCallback(methodName, paramMatchers, func([]Param) ReturnValues { return returnValues })
}

func (genericMock *GenericMock) stubWithCallback(methodName string, paramMatchers []Matcher, callback func([]Param) ReturnValues) {
	genericMock.getOrCreateMockedMethod(methodName).stub(paramMatchers, callback)
}

func (genericMock *GenericMock) getOrCreateMockedMethod(methodName string) *mockedMethod {
	if _, ok := genericMock.mockedMethods[methodName]; !ok {
		genericMock.mockedMethods[methodName] = &mockedMethod{name: methodName}
	}
	return genericMock.mockedMethods[methodName]
}

func (genericMock *GenericMock) reset(methodName string, paramMatchers []Matcher) {
	genericMock.getOrCreateMockedMethod(methodName).reset(paramMatchers)
}

func (genericMock *GenericMock) Verify(
	inOrderContext *InOrderContext,
	invocationCountMatcher Matcher,
	methodName string,
	params []Param) []MethodInvocation {
	if GlobalFailHandler == nil {
		panic("No GlobalFailHandler set. Please use either RegisterMockFailHandler or RegisterMockTestingT to set a fail handler.")
	}
	defer func() { globalArgMatchers = nil }() // We don't want a panic somewhere during verification screw our global argMatchers

	if len(globalArgMatchers) != 0 {
		verifyArgMatcherUse(globalArgMatchers, params)
	}

	methodInvocations := genericMock.methodInvocations(methodName, params, globalArgMatchers)
	if inOrderContext != nil {
		for _, methodInvocation := range methodInvocations {
			if methodInvocation.orderingInvocationNumber <= inOrderContext.invocationCounter {
				GlobalFailHandler(fmt.Sprintf("Expected function call \"%v\" with params %v before function call \"%v\" with params %v",
					methodName, params, inOrderContext.lastInvokedMethodName, inOrderContext.lastInvokedMethodParams))
			}
			inOrderContext.invocationCounter = methodInvocation.orderingInvocationNumber
			inOrderContext.lastInvokedMethodName = methodName
			inOrderContext.lastInvokedMethodParams = params
		}
	}
	if !invocationCountMatcher.Matches(len(methodInvocations)) {
		if len(globalArgMatchers) == 0 {
			GlobalFailHandler(fmt.Sprintf(
				"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
				methodName, params, invocationCountMatcher.FailureMessage()))
		} else {
			GlobalFailHandler(fmt.Sprintf(
				"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
				methodName, globalArgMatchers, invocationCountMatcher.FailureMessage()))
		}
	}
	return methodInvocations
}

func (genericMock *GenericMock) GetInvocationParams(methodInvocations []MethodInvocation) [][]Param {
	if len(methodInvocations) == 0 {
		return nil
	}
	result := make([][]Param, len(methodInvocations[len(methodInvocations)-1].params))
	for i, invocation := range methodInvocations {
		for u, param := range invocation.params {
			if result[u] == nil {
				result[u] = make([]Param, len(methodInvocations))
			}
			result[u][i] = param
		}
	}
	return result
}

func (genericMock *GenericMock) methodInvocations(methodName string, params []Param, matchers []Matcher) []MethodInvocation {
	var invocations []MethodInvocation
	if _, exists := genericMock.mockedMethods[methodName]; exists {
		for _, invocation := range genericMock.mockedMethods[methodName].invocations {
			if (len(matchers) != 0 && Matchers(matchers).Matches(invocation.params)) ||
				(reflect.DeepEqual(params, invocation.params) ||
					(len(params) == 0 && len(invocation.params) == 0)) {
				invocations = append(invocations, invocation)
			}
		}
	}
	return invocations
}

type mockedMethod struct {
	name        string
	invocations []MethodInvocation
	stubbings   Stubbings
}

func (method *mockedMethod) Invoke(params []Param) ReturnValues {
	method.invocations = append(method.invocations, MethodInvocation{params, globalInvocationCounter.nextNumber()})
	stubbing := method.stubbings.find(params)
	if stubbing == nil {
		return ReturnValues{}
	}
	return stubbing.Invoke(params)
}

func (method *mockedMethod) stub(paramMatchers Matchers, callback func([]Param) ReturnValues) {
	stubbing := method.stubbings.findByMatchers(paramMatchers)
	if stubbing == nil {
		stubbing = &Stubbing{paramMatchers: paramMatchers}
		method.stubbings = append(method.stubbings, stubbing)
	}
	stubbing.callbackSequence = append(stubbing.callbackSequence, callback)
}

func (method *mockedMethod) removeLastInvocation() {
	method.invocations = method.invocations[:len(method.invocations)-1]
}

func (method *mockedMethod) reset(paramMatchers Matchers) {
	method.stubbings.removeByMatchers(paramMatchers)
}

type Counter struct {
	count int
}

func (counter *Counter) nextNumber() (nextNumber int) {
	nextNumber = counter.count
	counter.count++
	return
}

var globalInvocationCounter Counter

type MethodInvocation struct {
	params                   []Param
	orderingInvocationNumber int
}

type Stubbings []*Stubbing

func (stubbings Stubbings) find(params []Param) *Stubbing {
	for i := len(stubbings) - 1; i >= 0; i-- {
		if stubbings[i].paramMatchers.Matches(params) {
			return stubbings[i]
		}
	}
	return nil
}

func (stubbings Stubbings) findByMatchers(paramMatchers Matchers) *Stubbing {
	for _, stubbing := range stubbings {
		if matchersEqual(stubbing.paramMatchers, paramMatchers) {
			return stubbing
		}
	}
	return nil
}

func (stubbings *Stubbings) removeByMatchers(paramMatchers Matchers) {
	for i, stubbing := range *stubbings {
		if matchersEqual(stubbing.paramMatchers, paramMatchers) {
			*stubbings = append((*stubbings)[:i], (*stubbings)[i+1:]...)
		}
	}
}

func matchersEqual(a, b Matchers) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if !reflect.DeepEqual(a[i], b[i]) {
			return false
		}
	}
	return true
}

type Stubbing struct {
	paramMatchers    Matchers
	callbackSequence []func([]Param) ReturnValues
	sequencePointer  int
}

func (stubbing *Stubbing) Invoke(params []Param) ReturnValues {
	defer func() {
		if stubbing.sequencePointer < len(stubbing.callbackSequence)-1 {
			stubbing.sequencePointer++
		}
	}()
	return stubbing.callbackSequence[stubbing.sequencePointer](params)
}

type Matchers []Matcher

func (matchers Matchers) Matches(params []Param) bool {
	if len(matchers) != len(params) { // Technically, this is not an error. Variadic arguments can cause this
		return false
	}
	for i := range params {
		if !matchers[i].Matches(params[i]) {
			return false
		}
	}
	return true
}

func (matchers *Matchers) append(matcher Matcher) {
	*matchers = append(*matchers, matcher)
}

type ongoingStubbing struct {
	genericMock   *GenericMock
	MethodName    string
	ParamMatchers []Matcher
	returnTypes   []reflect.Type
}

func When(invocation ...interface{}) *ongoingStubbing {
	callIfIsFunc(invocation)
	verify.Argument(lastInvocation != nil,
		"When() requires an argument which has to be 'a method call on a mock'.")
	defer func() {
		lastInvocation = nil
		globalArgMatchers = nil
	}()
	lastInvocation.genericMock.mockedMethods[lastInvocation.MethodName].removeLastInvocation()

	paramMatchers := paramMatchersFromArgMatchersOrParams(globalArgMatchers, lastInvocation.Params)
	lastInvocation.genericMock.reset(lastInvocation.MethodName, paramMatchers)
	return &ongoingStubbing{
		genericMock:   lastInvocation.genericMock,
		MethodName:    lastInvocation.MethodName,
		ParamMatchers: paramMatchers,
		returnTypes:   lastInvocation.ReturnTypes,
	}
}

func callIfIsFunc(invocation []interface{}) {
	if len(invocation) == 1 {
		actualType := actualTypeOf(invocation[0])
		if actualType != nil && actualType.Kind() == reflect.Func && !reflect.ValueOf(invocation[0]).IsNil() {
			if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
				panic("When using 'When' with function that does not return a value, " +
					"it expects a function with no arguments and no return value.")
			}
			reflect.ValueOf(invocation[0]).Call([]reflect.Value{})
		}
	}
}

// Deals with nils without panicking
func actualTypeOf(iface interface{}) reflect.Type {
	defer func() { recover() }()
	return reflect.TypeOf(iface)
}

func paramMatchersFromArgMatchersOrParams(argMatchers []Matcher, params []Param) []Matcher {
	if len(argMatchers) != 0 {
		verifyArgMatcherUse(argMatchers, params)
		return argMatchers
	}
	return transformParamsIntoEqMatchers(params)
}

func verifyArgMatcherUse(argMatchers []Matcher, params []Param) {
	verify.Argument(len(argMatchers) == len(params),
		"Invalid use of matchers!\n\n %v matchers expected, %v recorded.\n\n"+
			"This error may occur if matchers are combined with raw values:\n"+
			"    //incorrect:\n"+
			"    someFunc(AnyInt(), \"raw String\")\n"+
			"When using matchers, all arguments have to be provided by matchers.\n"+
			"For example:\n"+
			"    //correct:\n"+
			"    someFunc(AnyInt(), EqString(\"String by matcher\"))",
		len(params), len(argMatchers),
	)
}

func transformParamsIntoEqMatchers(params []Param) []Matcher {
	paramMatchers := make([]Matcher, len(params))
	for i, param := range params {
		paramMatchers[i] = &EqMatcher{Value: param}
	}
	return paramMatchers
}

var genericMocks = make(map[Mock]*GenericMock)

func GetGenericMockFrom(mock Mock) *GenericMock {
	if genericMocks[mock] == nil {
		genericMocks[mock] = &GenericMock{mockedMethods: make(map[string]*mockedMethod)}
	}
	return genericMocks[mock]
}

func (stubbing *ongoingStubbing) ThenReturn(values ...ReturnValue) *ongoingStubbing {
	checkAssignabilityOf(values, stubbing.returnTypes)
	stubbing.genericMock.stub(stubbing.MethodName, stubbing.ParamMatchers, values)
	return stubbing
}

func checkAssignabilityOf(stubbedReturnValues []ReturnValue, expectedReturnTypes []reflect.Type) {
	verify.Argument(len(stubbedReturnValues) == len(expectedReturnTypes),
		"Different number of return values")
	for i := range stubbedReturnValues {
		if stubbedReturnValues[i] == nil {
			switch expectedReturnTypes[i].Kind() {
			case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint,
				reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32,
				reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.Array, reflect.String,
				reflect.Struct:
				panic("Return value 'nil' not assignable to return type " + expectedReturnTypes[i].Kind().String())
			}
		} else {
			verify.Argument(reflect.TypeOf(stubbedReturnValues[i]).AssignableTo(expectedReturnTypes[i]),
				"Return value of type %T not assignable to return type %v", stubbedReturnValues[i], expectedReturnTypes[i])
		}
	}
}

func (stubbing *ongoingStubbing) ThenPanic(v interface{}) *ongoingStubbing {
	stubbing.genericMock.stubWithCallback(
		stubbing.MethodName,
		stubbing.ParamMatchers,
		func([]Param) ReturnValues { panic(v) })
	return stubbing
}

func (stubbing *ongoingStubbing) Then(callback func([]Param) ReturnValues) *ongoingStubbing {
	stubbing.genericMock.stubWithCallback(
		stubbing.MethodName,
		stubbing.ParamMatchers,
		callback)
	return stubbing
}

type InOrderContext struct {
	invocationCounter       int
	lastInvokedMethodName   string
	lastInvokedMethodParams []Param
}

type Stubber struct {
	returnValue interface{}
}

func DoPanic(value interface{}) *Stubber {
	return &Stubber{returnValue: value}
}

func (stubber *Stubber) When(mock interface{}) {

}

// Matcher ... it is guaranteed that FailureMessage will always be called after Matches
// so an implementation can save state
type Matcher interface {
	Matches(param Param) bool
	FailureMessage() string
	fmt.Stringer
}
<commit_msg>Remove obsolete Stubber stubs<commit_after>// Copyright 2015 Peter Goetz
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pegomock

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/petergtz/pegomock/internal/verify"
)

var GlobalFailHandler FailHandler

func RegisterMockFailHandler(handler FailHandler) {
	GlobalFailHandler = handler
}
func RegisterMockTestingT(t *testing.T) {
	RegisterMockFailHandler(BuildTestingTGomegaFailHandler(t))
}

var lastInvocation *invocation
var globalArgMatchers Matchers

func RegisterMatcher(matcher Matcher) {
	globalArgMatchers.append(matcher)
}

type invocation struct {
	genericMock *GenericMock
	MethodName  string
	Params      []Param
	ReturnTypes []reflect.Type
}

type GenericMock struct {
	mockedMethods map[string]*mockedMethod
}

func (genericMock *GenericMock) Invoke(methodName string, params []Param, returnTypes []reflect.Type) ReturnValues {
	lastInvocation = &invocation{
		genericMock: genericMock,
		MethodName:  methodName,
		Params:      params,
		ReturnTypes: returnTypes,
	}
	return genericMock.getOrCreateMockedMethod(methodName).Invoke(params)
}

func (genericMock *GenericMock) stub(methodName string, paramMatchers []Matcher, returnValues ReturnValues) {
	genericMock.stubWithCallback(methodName, paramMatchers, func([]Param) ReturnValues { return returnValues })
}

func (genericMock *GenericMock) stubWithCallback(methodName string, paramMatchers []Matcher, callback func([]Param) ReturnValues) {
	genericMock.getOrCreateMockedMethod(methodName).stub(paramMatchers, callback)
}

func (genericMock *GenericMock) getOrCreateMockedMethod(methodName string) *mockedMethod {
	if _, ok := genericMock.mockedMethods[methodName]; !ok {
		genericMock.mockedMethods[methodName] = &mockedMethod{name: methodName}
	}
	return genericMock.mockedMethods[methodName]
}

func (genericMock *GenericMock) reset(methodName string, paramMatchers []Matcher) {
	genericMock.getOrCreateMockedMethod(methodName).reset(paramMatchers)
}

func (genericMock *GenericMock) Verify(
	inOrderContext *InOrderContext,
	invocationCountMatcher Matcher,
	methodName string,
	params []Param) []MethodInvocation {
	if GlobalFailHandler == nil {
		panic("No GlobalFailHandler set. Please use either RegisterMockFailHandler or RegisterMockTestingT to set a fail handler.")
	}
	defer func() { globalArgMatchers = nil }() // We don't want a panic somewhere during verification screw our global argMatchers

	if len(globalArgMatchers) != 0 {
		verifyArgMatcherUse(globalArgMatchers, params)
	}

	methodInvocations := genericMock.methodInvocations(methodName, params, globalArgMatchers)
	if inOrderContext != nil {
		for _, methodInvocation := range methodInvocations {
			if methodInvocation.orderingInvocationNumber <= inOrderContext.invocationCounter {
				GlobalFailHandler(fmt.Sprintf("Expected function call \"%v\" with params %v before function call \"%v\" with params %v",
					methodName, params, inOrderContext.lastInvokedMethodName, inOrderContext.lastInvokedMethodParams))
			}
			inOrderContext.invocationCounter = methodInvocation.orderingInvocationNumber
			inOrderContext.lastInvokedMethodName = methodName
			inOrderContext.lastInvokedMethodParams = params
		}
	}
	if !invocationCountMatcher.Matches(len(methodInvocations)) {
		if len(globalArgMatchers) == 0 {
			GlobalFailHandler(fmt.Sprintf(
				"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
				methodName, params, invocationCountMatcher.FailureMessage()))
		} else {
			GlobalFailHandler(fmt.Sprintf(
				"Mock invocation count for method \"%s\" with params %v does not match expectation.\n\n\t%v",
				methodName, globalArgMatchers, invocationCountMatcher.FailureMessage()))
		}
	}
	return methodInvocations
}

func (genericMock *GenericMock) GetInvocationParams(methodInvocations []MethodInvocation) [][]Param {
	if len(methodInvocations) == 0 {
		return nil
	}
	result := make([][]Param, len(methodInvocations[len(methodInvocations)-1].params))
	for i, invocation := range methodInvocations {
		for u, param := range invocation.params {
			if result[u] == nil {
				result[u] = make([]Param, len(methodInvocations))
			}
			result[u][i] = param
		}
	}
	return result
}

func (genericMock *GenericMock) methodInvocations(methodName string, params []Param, matchers []Matcher) []MethodInvocation {
	var invocations []MethodInvocation
	if _, exists := genericMock.mockedMethods[methodName]; exists {
		for _, invocation := range genericMock.mockedMethods[methodName].invocations {
			if (len(matchers) != 0 && Matchers(matchers).Matches(invocation.params)) ||
				(reflect.DeepEqual(params, invocation.params) ||
					(len(params) == 0 && len(invocation.params) == 0)) {
				invocations = append(invocations, invocation)
			}
		}
	}
	return invocations
}

type mockedMethod struct {
	name        string
	invocations []MethodInvocation
	stubbings   Stubbings
}

func (method *mockedMethod) Invoke(params []Param) ReturnValues {
	method.invocations = append(method.invocations, MethodInvocation{params, globalInvocationCounter.nextNumber()})
	stubbing := method.stubbings.find(params)
	if stubbing == nil {
		return ReturnValues{}
	}
	return stubbing.Invoke(params)
}

func (method *mockedMethod) stub(paramMatchers Matchers, callback func([]Param) ReturnValues) {
	stubbing := method.stubbings.findByMatchers(paramMatchers)
	if stubbing == nil {
		stubbing = &Stubbing{paramMatchers: paramMatchers}
		method.stubbings = append(method.stubbings, stubbing)
	}
	stubbing.callbackSequence = append(stubbing.callbackSequence, callback)
}

func (method *mockedMethod) removeLastInvocation() {
	method.invocations = method.invocations[:len(method.invocations)-1]
}

func (method *mockedMethod) reset(paramMatchers Matchers) {
	method.stubbings.removeByMatchers(paramMatchers)
}

type Counter struct {
	count int
}

func (counter *Counter) nextNumber() (nextNumber int) {
	nextNumber = counter.count
	counter.count++
	return
}

var globalInvocationCounter Counter

type MethodInvocation struct {
	params                   []Param
	orderingInvocationNumber int
}

type Stubbings []*Stubbing

func (stubbings Stubbings) find(params []Param) *Stubbing {
	for i := len(stubbings) - 1; i >= 0; i-- {
		if stubbings[i].paramMatchers.Matches(params) {
			return stubbings[i]
		}
	}
	return nil
}

func (stubbings Stubbings) findByMatchers(paramMatchers Matchers) *Stubbing {
	for _, stubbing := range stubbings {
		if matchersEqual(stubbing.paramMatchers, paramMatchers) {
			return stubbing
		}
	}
	return nil
}

func (stubbings *Stubbings) removeByMatchers(paramMatchers Matchers) {
	for i, stubbing := range *stubbings {
		if matchersEqual(stubbing.paramMatchers, paramMatchers) {
			*stubbings = append((*stubbings)[:i], (*stubbings)[i+1:]...)
		}
	}
}

func matchersEqual(a, b Matchers) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if !reflect.DeepEqual(a[i], b[i]) {
			return false
		}
	}
	return true
}

type Stubbing struct {
	paramMatchers    Matchers
	callbackSequence []func([]Param) ReturnValues
	sequencePointer  int
}

func (stubbing *Stubbing) Invoke(params []Param) ReturnValues {
	defer func() {
		if stubbing.sequencePointer < len(stubbing.callbackSequence)-1 {
			stubbing.sequencePointer++
		}
	}()
	return stubbing.callbackSequence[stubbing.sequencePointer](params)
}

type Matchers []Matcher

func (matchers Matchers) Matches(params []Param) bool {
	if len(matchers) != len(params) { // Technically, this is not an error. Variadic arguments can cause this
		return false
	}
	for i := range params {
		if !matchers[i].Matches(params[i]) {
			return false
		}
	}
	return true
}

func (matchers *Matchers) append(matcher Matcher) {
	*matchers = append(*matchers, matcher)
}

type ongoingStubbing struct {
	genericMock   *GenericMock
	MethodName    string
	ParamMatchers []Matcher
	returnTypes   []reflect.Type
}

func When(invocation ...interface{}) *ongoingStubbing {
	callIfIsFunc(invocation)
	verify.Argument(lastInvocation != nil,
		"When() requires an argument which has to be 'a method call on a mock'.")
	defer func() {
		lastInvocation = nil
		globalArgMatchers = nil
	}()
	lastInvocation.genericMock.mockedMethods[lastInvocation.MethodName].removeLastInvocation()

	paramMatchers := paramMatchersFromArgMatchersOrParams(globalArgMatchers, lastInvocation.Params)
	lastInvocation.genericMock.reset(lastInvocation.MethodName, paramMatchers)
	return &ongoingStubbing{
		genericMock:   lastInvocation.genericMock,
		MethodName:    lastInvocation.MethodName,
		ParamMatchers: paramMatchers,
		returnTypes:   lastInvocation.ReturnTypes,
	}
}

func callIfIsFunc(invocation []interface{}) {
	if len(invocation) == 1 {
		actualType := actualTypeOf(invocation[0])
		if actualType != nil && actualType.Kind() == reflect.Func && !reflect.ValueOf(invocation[0]).IsNil() {
			if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) {
				panic("When using 'When' with function that does not return a value, " +
					"it expects a function with no arguments and no return value.")
			}
			reflect.ValueOf(invocation[0]).Call([]reflect.Value{})
		}
	}
}

// Deals with nils without panicking
func actualTypeOf(iface interface{}) reflect.Type {
	defer func() { recover() }()
	return reflect.TypeOf(iface)
}

func paramMatchersFromArgMatchersOrParams(argMatchers []Matcher, params []Param) []Matcher {
	if len(argMatchers) != 0 {
		verifyArgMatcherUse(argMatchers, params)
		return argMatchers
	}
	return transformParamsIntoEqMatchers(params)
}

func verifyArgMatcherUse(argMatchers []Matcher, params []Param) {
	verify.Argument(len(argMatchers) == len(params),
		"Invalid use of matchers!\n\n %v matchers expected, %v recorded.\n\n"+
			"This error may occur if matchers are combined with raw values:\n"+
			"    //incorrect:\n"+
			"    someFunc(AnyInt(), \"raw String\")\n"+
			"When using matchers, all arguments have to be provided by matchers.\n"+
			"For example:\n"+
			"    //correct:\n"+
			"    someFunc(AnyInt(), EqString(\"String by matcher\"))",
		len(params), len(argMatchers),
	)
}

func transformParamsIntoEqMatchers(params []Param) []Matcher {
	paramMatchers := make([]Matcher, len(params))
	for i, param := range params {
		paramMatchers[i] = &EqMatcher{Value: param}
	}
	return paramMatchers
}

var genericMocks = make(map[Mock]*GenericMock)

func GetGenericMockFrom(mock Mock) *GenericMock {
	if genericMocks[mock] == nil {
		genericMocks[mock] = &GenericMock{mockedMethods: make(map[string]*mockedMethod)}
	}
	return genericMocks[mock]
}

func (stubbing *ongoingStubbing) ThenReturn(values ...ReturnValue) *ongoingStubbing {
	checkAssignabilityOf(values, stubbing.returnTypes)
	stubbing.genericMock.stub(stubbing.MethodName, stubbing.ParamMatchers, values)
	return stubbing
}

func checkAssignabilityOf(stubbedReturnValues []ReturnValue, expectedReturnTypes []reflect.Type) {
	verify.Argument(len(stubbedReturnValues) == len(expectedReturnTypes),
		"Different number of return values")
	for i := range stubbedReturnValues {
		if stubbedReturnValues[i] == nil {
			switch expectedReturnTypes[i].Kind() {
			case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint,
				reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32,
				reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.Array, reflect.String,
				reflect.Struct:
				panic("Return value 'nil' not assignable to return type " + expectedReturnTypes[i].Kind().String())
			}
		} else {
			verify.Argument(reflect.TypeOf(stubbedReturnValues[i]).AssignableTo(expectedReturnTypes[i]),
				"Return value of type %T not assignable to return type %v", stubbedReturnValues[i], expectedReturnTypes[i])
		}
	}
}

func (stubbing *ongoingStubbing) ThenPanic(v interface{}) *ongoingStubbing {
	stubbing.genericMock.stubWithCallback(
		stubbing.MethodName,
		stubbing.ParamMatchers,
		func([]Param) ReturnValues { panic(v) })
	return stubbing
}

func (stubbing *ongoingStubbing) Then(callback func([]Param) ReturnValues) *ongoingStubbing {
	stubbing.genericMock.stubWithCallback(
		stubbing.MethodName,
		stubbing.ParamMatchers,
		callback)
	return stubbing
}

type InOrderContext struct {
	invocationCounter       int
	lastInvokedMethodName   string
	lastInvokedMethodParams []Param
}

// Matcher ... it is guaranteed that FailureMessage will always be called after Matches
// so an implementation can save state
type Matcher interface {
	Matches(param Param) bool
	FailureMessage() string
	fmt.Stringer
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"compress/zlib"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
)

type Env map[string]string

func EnvToShell(env Env, shell Shell) string {
	str := ""
	for key, value := range env {
		// FIXME: This is not exacly as the ruby nil
		if value == "" {
			if key == "PS1" {
				// unsetting PS1 doesn't restore the default in OSX's bash
			} else {
				str += shell.Unset(key)
			}
		} else {
			str += shell.Export(key, value)
		}
	}
	return str
}

func EnvDiff(env1 map[string]string, env2 map[string]string) Env {
	envDiff := make(Env)

	for key, _ := range env1 {
		if env2[key] != env1[key] && !ignoredKey(key) {
			envDiff[key] = env2[key]
		}
	}

	// FIXME: I'm sure there is a smarter way to do that
	for key, _ := range env2 {
		if env2[key] != env1[key] && !ignoredKey(key) {
			envDiff[key] = env2[key]
		}
	}

	return envDiff
}

// A list of keys we don't want to deal with
var IGNORED_KEYS = map[string]bool{
	"_":      true,
	"PWD":    true,
	"OLDPWD": true,
	"SHLVL":  true,
	"SHELL":  true,
}

func ignoredKey(key string) bool {
	if len(key) > 6 && key[:7] == "DIRENV_" {
		return true
	}

	_, found := IGNORED_KEYS[key]
	return found
}

// NOTE:  We don't support having two variables with the same name.
//        I've never seen it used in the wild but accoding to POSIX
//        it's allowed.
func GetEnv() Env {
	env := make(Env)

	for _, kv := range os.Environ() {
		kv2 := strings.SplitN(kv, "=", 2)

		key := kv2[0]
		value := kv2[1]

		env[key] = value
	}

	return env
}

func (env Env) Filtered() Env {
	newEnv := make(Env)

	for key, value := range env {
		if !ignoredKey(key) {
			newEnv[key] = value
		}
	}

	return newEnv
}

func (env Env) ToGoEnv() []string {
	goEnv := make([]string, len(env))
	index := 0
	for key, value := range env {
		goEnv[index] = strings.Join([]string{key, value}, "=")
		index += 1
	}
	return goEnv
}

func ParseEnv(base64env string) (Env, error) {
	base64env = strings.TrimSpace(base64env)

	zlibData, err := base64.URLEncoding.DecodeString(base64env)
	if err != nil {
		return nil, fmt.Errorf("base64 decoding: %v", err)
	}

	zlibReader := bytes.NewReader(zlibData)
	w, err := zlib.NewReader(zlibReader)
	if err != nil {
		return nil, fmt.Errorf("zlib opening: %v", err)
	}

	envData := bytes.NewBuffer([]byte{})
	_, err = io.Copy(envData, w)
	if err != nil {
		return nil, fmt.Errorf("zlib decoding: %v", err)
	}
	w.Close()

	env := make(Env)
	err = json.Unmarshal(envData.Bytes(), &env)
	if err != nil {
		return nil, fmt.Errorf("json parsing: %v", err)
	}

	return env, nil
}

func (env Env) Serialize() string {
	// We can safely ignore the err because it's only thrown
	// for unsupported datatype. We know that a map[string]string
	// is supported.
	jsonData, err := json.Marshal(env)
	if err != nil {
		panic(err)
	}

	zlibData := bytes.NewBuffer([]byte{})
	w := zlib.NewWriter(zlibData)
	w.Write(jsonData)
	w.Close()

	base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes())

	return base64Data
}
<commit_msg>Style, thx @pwaller<commit_after>package main

import (
	"bytes"
	"compress/zlib"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
)

type Env map[string]string

func EnvToShell(env Env, shell Shell) string {
	str := ""
	for key, value := range env {
		// FIXME: This is not exacly as the ruby nil
		if value == "" {
			if key == "PS1" {
				// unsetting PS1 doesn't restore the default in OSX's bash
			} else {
				str += shell.Unset(key)
			}
		} else {
			str += shell.Export(key, value)
		}
	}
	return str
}

func EnvDiff(env1 map[string]string, env2 map[string]string) Env {
	envDiff := make(Env)

	for key, _ := range env1 {
		if env2[key] != env1[key] && !ignoredKey(key) {
			envDiff[key] = env2[key]
		}
	}

	// FIXME: I'm sure there is a smarter way to do that
	for key, _ := range env2 {
		if env2[key] != env1[key] && !ignoredKey(key) {
			envDiff[key] = env2[key]
		}
	}

	return envDiff
}

// A list of keys we don't want to deal with
var IGNORED_KEYS = map[string]bool{
	"_":      true,
	"PWD":    true,
	"OLDPWD": true,
	"SHLVL":  true,
	"SHELL":  true,
}

func ignoredKey(key string) bool {
	if strings.HasPrefix(key, "DIRENV_") {
		return true
	}

	_, found := IGNORED_KEYS[key]
	return found
}

// NOTE:  We don't support having two variables with the same name.
//        I've never seen it used in the wild but accoding to POSIX
//        it's allowed.
func GetEnv() Env {
	env := make(Env)

	for _, kv := range os.Environ() {
		kv2 := strings.SplitN(kv, "=", 2)

		key := kv2[0]
		value := kv2[1]

		env[key] = value
	}

	return env
}

func (env Env) Filtered() Env {
	newEnv := make(Env)

	for key, value := range env {
		if !ignoredKey(key) {
			newEnv[key] = value
		}
	}

	return newEnv
}

func (env Env) ToGoEnv() []string {
	goEnv := make([]string, len(env))
	index := 0
	for key, value := range env {
		goEnv[index] = strings.Join([]string{key, value}, "=")
		index += 1
	}
	return goEnv
}

func ParseEnv(base64env string) (Env, error) {
	base64env = strings.TrimSpace(base64env)

	zlibData, err := base64.URLEncoding.DecodeString(base64env)
	if err != nil {
		return nil, fmt.Errorf("base64 decoding: %v", err)
	}

	zlibReader := bytes.NewReader(zlibData)
	w, err := zlib.NewReader(zlibReader)
	if err != nil {
		return nil, fmt.Errorf("zlib opening: %v", err)
	}

	envData := bytes.NewBuffer([]byte{})
	_, err = io.Copy(envData, w)
	if err != nil {
		return nil, fmt.Errorf("zlib decoding: %v", err)
	}
	w.Close()

	env := make(Env)
	err = json.Unmarshal(envData.Bytes(), &env)
	if err != nil {
		return nil, fmt.Errorf("json parsing: %v", err)
	}

	return env, nil
}

func (env Env) Serialize() string {
	// We can safely ignore the err because it's only thrown
	// for unsupported datatype. We know that a map[string]string
	// is supported.
	jsonData, err := json.Marshal(env)
	if err != nil {
		panic(err)
	}

	zlibData := bytes.NewBuffer([]byte{})
	w := zlib.NewWriter(zlibData)
	w.Write(jsonData)
	w.Close()

	base64Data := base64.URLEncoding.EncodeToString(zlibData.Bytes())

	return base64Data
}
<|endoftext|>