"internal/vscode:/vscode.git/clone" did not exist on "e65e639971c3fd2e41c8971bdbad3e12907959b0"
Commit dc8b36de authored by 李宇怀's avatar 李宇怀
Browse files

完成TASK B 及部分TASK A

parent f13ebe0e
package model
type Foo struct {
ID int64 `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
Name string `json:"name" gorm:"type:varchar(255);not null"`
Age int64 `json:"age" gorm:"type:int"`
}
package model
import "time"
const LinkTable = "Links"
type Link struct {
ID uint `json:"id"` // 链接ID
Title string `json:"title"` // 链接标题
URL string `json:"url"` // 链接URL
OwnerID uint `json:"owner_id"` // 拥有者ID
CreatedAt time.Time `json:"created_at"` // 创建时间
UpdatedAt time.Time `json:"updated_at"` // 更新时间
}
package model
const UserTable = "Users"
type User struct {
ID uint `json:"id"` // 用户ID​
Email string `json:"email"` // 用户邮箱​
Name string `json:"name"` // 用户名​
Password string `json:"password"` // 用户密码​
// edge​
Links []Link `json:"-" gorm:"foreignKey:OwnerID;references:ID"`
}
package main
import (
"go-svc-tpl/cmd"
)
func main() {
cmd.Execute()
}
package logger
import (
"fmt"
"github.com/sirupsen/logrus"
"path/filepath"
"time"
)
var (
color_NORMAL = "\033[0m"
color_GRAY = "\033[1;30m"
color_RED = "\033[1;31m"
color_GREEN = "\033[1;32m"
color_YELLOW = "\033[1;33m"
color_BLUE = "\033[1;34m"
color_MAGENTA = "\033[1;35m"
color_CYAN = "\033[1;36m"
color_WHITE = "\033[1;37m"
)
type LogFormatter struct{}
func (slf *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
var logColor = color_NORMAL
// colorful log
switch entry.Level {
case logrus.DebugLevel:
logColor = color_BLUE
case logrus.InfoLevel:
logColor = color_GREEN
case logrus.WarnLevel:
logColor = color_YELLOW
case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
logColor = color_RED
default:
}
timestamp := time.Now().Local().Format("06/01/02 15:04:05")
// log format:
// ----------------------------------------
// [level] timestamp (file:line): field1=value1 field2=value2 ...
// message
// ----------------------------------------
prefix := fmt.Sprintf("%s[%s] %s (%s:%d):%s ", logColor, entry.Level,
timestamp,
filepath.Base(entry.Caller.File),
entry.Caller.Line,
color_NORMAL,
)
fields := ""
for k, v := range entry.Data {
fields += fmt.Sprintf(" %s%s%s=%v", color_CYAN, k, color_NORMAL, v)
}
msg := fmt.Sprintf("%s%s\n%s\n", prefix, fields, entry.Message)
return []byte(msg), nil
}
func init() {
// open file location reporter
logrus.SetReportCaller(true)
logrus.SetFormatter(&LogFormatter{})
}
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
# Stacktrace [![Circle CI](https://img.shields.io/circleci/project/palantir/stacktrace/master.svg?label=circleci)](https://circleci.com/gh/palantir/stacktrace) [![Travis CI](https://img.shields.io/travis/palantir/stacktrace/master.svg?label=travis)](https://travis-ci.org/palantir/stacktrace)
Look at Palantir, such a Java shop. I can't believe they want stack traces in
their Go code.
### Why would anyone want stack traces in Go code?
This is difficult to debug:
```
Inverse tachyon pulse failed
```
This gives the full story and is easier to debug:
```
Failed to register for villain discovery
--- at github.com/palantir/shield/agent/discovery.go:265 (ShieldAgent.reallyRegister) ---
--- at github.com/palantir/shield/connector/impl.go:89 (Connector.Register) ---
Caused by: Failed to load S.H.I.E.L.D. config from /opt/shield/conf/shield.yaml
--- at github.com/palantir/shield/connector/config.go:44 (withShieldConfig) ---
Caused by: There isn't enough time (4 picoseconds required)
--- at github.com/palantir/shield/axiom/pseudo/resource.go:46 (PseudoResource.Adjust) ---
--- at github.com/palantir/shield/axiom/pseudo/growth.go:110 (reciprocatingPseudo.growDown) ---
--- at github.com/palantir/shield/axiom/pseudo/growth.go:121 (reciprocatingPseudo.verify) ---
Caused by: Inverse tachyon pulse failed
--- at github.com/palantir/shield/metaphysic/tachyon.go:72 (TryPulse) ---
```
Note that stack traces are *not designed to be user-visible*. We have found them
to be valuable in log files of server applications. Nobody wants to see these in
CLI output or a web interface or a return value from library code.
## Intent
The intent is *not* that we capture the exact state of the stack when an error
happens, including every function call. For a library that does that, see
[github.com/go-errors/errors](https://github.com/go-errors/errors). The intent
here is to attach relevant contextual information (messages, variables) at
strategic places along the call stack, keeping stack traces compact and
maximally useful.
## Example Usage
<!-- pre instead of code block to support bold text inside -->
<pre>
func WriteAll(baseDir string, entities []Entity) error {
err := os.MkdirAll(baseDir, 0755)
if err != nil {
return <b>stacktrace.Propagate(err, "Failed to create base directory")</b>
}
for _, ent := range entities {
path := filepath.Join(baseDir, fileNameForEntity(ent))
err = Write(path, ent)
if err != nil {
return <b>stacktrace.Propagate(err, "Failed to write %v to %s", ent, path)</b>
}
}
return nil
}
</pre>
## Functions
#### stacktrace.Propagate(cause error, msg string, vals ...interface{}) error
Propagate wraps an error to include line number information. This is going to be
your most common stacktrace call.
As in all of these functions, the `msg` and `vals` work like `fmt.Errorf`.
The message passed to Propagate should describe the action that failed,
resulting in `cause`. The canonical call looks like this:
<pre>
result, err := process(arg)
if err != nil {
return nil, <b>stacktrace.Propagate(err, "Failed to process %v", arg)</b>
}
</pre>
To write the message, ask yourself "what does this call do?" What does
`process(arg)` do? It processes ${arg}, so the message is that we failed to
process ${arg}.
Pay attention that the message is not redundant with the one in `err`. In the
`WriteAll` example above, any error from `os.MkdirAll` will already contain the
path it failed to create, so it would be redundant to include it again in our
message. However, the error from `os.MkdirAll` will not identify that path as
corresponding to the "base directory" so we propagate with that information.
If it is not possible to add any useful contextual information beyond what is
already included in an error, `msg` can be an empty string:
<pre>
func Something() error {
mutex.Lock()
defer mutex.Unlock()
err := reallySomething()
return <b>stacktrace.Propagate(err, "")</b>
}
</pre>
The purpose of `""` as opposed to a separate function is to make you feel a
little guilty every time you do this.
This example also illustrates the behavior of Propagate when `cause` is nil
&ndash; it returns nil as well. There is no need to check `if err != nil`.
#### stacktrace.NewError(msg string, vals ...interface{}) error
NewError is a drop-in replacement for `fmt.Errorf` that includes line number
information. The canonical call looks like this:
<pre>
if !IsOkay(arg) {
return <b>stacktrace.NewError("Expected %v to be okay", arg)</b>
}
</pre>
### Error Codes
Occasionally it can be useful to propagate an error code while unwinding the
stack. For example, a RESTful API may use the error code to set the HTTP status
code.
The type `stacktrace.ErrorCode` is a typedef for uint16. You name the set of
error codes relevant to your application.
```
const (
EcodeManifestNotFound = stacktrace.ErrorCode(iota)
EcodeBadInput
EcodeTimeout
)
```
The special value `stacktrace.NoCode` is equal to `math.MaxUint16`, so avoid
using that. NoCode is the error code of errors with no code explicitly attached.
An ordinary `stacktrace.Propagate` preserves the error code of an error.
#### stacktrace.PropagateWithCode(cause error, code ErrorCode, msg string, vals ...interface{}) error
#### stacktrace.NewErrorWithCode(code ErrorCode, msg string, vals ...interface{}) error
PropagateWithCode and NewErrorWithCode are analogous to Propagate and NewError
but also attach an error code.
<pre>
_, err := os.Stat(manifestPath)
if os.IsNotExist(err) {
return <b>stacktrace.PropagateWithCode(err, EcodeManifestNotFound, "")</b>
}
</pre>
#### stacktrace.NewMessageWithCode(code ErrorCode, msg string, vals ...interface{}) error
The error code mechanism can be useful by itself even where stack traces with
line numbers are not required. NewMessageWithCode returns an error that prints
just like `fmt.Errorf` with no line number, but including a code.
<pre>
ttl := req.URL.Query().Get("ttl")
if ttl == "" {
return 0, <b>stacktrace.NewMessageWithCode(EcodeBadInput, "Missing ttl query parameter")</b>
}
</pre>
#### stacktrace.GetCode(err error) ErrorCode
GetCode extracts the error code from an error.
<pre>
for i := 0; i < attempts; i++ {
err := Do()
if <b>stacktrace.GetCode(err)</b> != EcodeTimeout {
return err
}
// try a few more times
}
return stacktrace.NewError("timed out after %d attempts", attempts)
</pre>
GetCode returns the special value `stacktrace.NoCode` if `err` is nil or if
there is no error code attached to `err`.
## License
Stacktrace is released by Palantir Technologies, Inc. under the Apache 2.0
License. See the included [LICENSE](LICENSE) file for details.
## Contributing
We welcome contributions of backward-compatible changes to this library.
- Write your code
- Add tests for new functionality
- Run `go test` and verify that the tests pass
- Fill out the [Individual](https://github.com/palantir/stacktrace/blob/master/Palantir_Individual_Contributor_License_Agreement.pdf?raw=true) or [Corporate](https://github.com/palantir/stacktrace/blob/master/Palantir_Corporate_Contributor_License_Agreement.pdf?raw=true) Contributor License Agreement and send it to [opensource@palantir.com](mailto:opensource@palantir.com)
- Submit a pull request
package stacktrace
import (
"errors"
)
/*
RootCause unwraps the original error that caused the current one.
_, err := f()
if perr, ok := stacktrace.RootCause(err).(*ParsingError); ok {
showError(perr.Line, perr.Column, perr.Text)
}
*/
func RootCause(err error) error {
for {
st, ok := err.(*stacktrace)
if !ok {
return err
}
if st.cause == nil {
return errors.New(st.message)
}
err = st.cause
}
}
// Current returns the top level error.
func Current(err error) error {
for {
st, ok := err.(*stacktrace)
if !ok {
return err
}
return create(nil, st.code, st.message)
}
}
package stacktrace_test
import (
"errors"
"go-svc-tpl/utils/stacktrace"
"testing"
"github.com/stretchr/testify/assert"
)
type customError string
func (e customError) Error() string { return string(e) }
func TestRootCause(t *testing.T) {
for _, test := range []struct {
err error
rootCause error
}{
{
err: nil,
rootCause: nil,
},
{
err: errors.New("msg"),
rootCause: errors.New("msg"),
},
{
err: stacktrace.NewError("msg"),
rootCause: errors.New("msg"),
},
{
err: stacktrace.Propagate(stacktrace.NewError("msg1"), "msg2"),
rootCause: errors.New("msg1"),
},
{
err: customError("msg"),
rootCause: customError("msg"),
},
{
err: stacktrace.Propagate(customError("msg1"), "msg2"),
rootCause: customError("msg1"),
},
} {
assert.Equal(t, test.rootCause, stacktrace.RootCause(test.err))
}
}
package cleanpath
import (
"os"
"path/filepath"
"sort"
"strings"
)
/*
RemoveGoPath makes a path relative to one of the src directories in the $GOPATH
environment variable. If $GOPATH is empty or the input path is not contained
within any of the src directories in $GOPATH, the original path is returned. If
the input path is contained within multiple of the src directories in $GOPATH,
it is made relative to the longest one of them.
*/
func RemoveGoPath(path string) string {
dirs := filepath.SplitList(os.Getenv("GOPATH"))
// Sort in decreasing order by length so the longest matching prefix is removed
sort.Stable(longestFirst(dirs))
for _, dir := range dirs {
srcdir := filepath.Join(dir, "src")
rel, err := filepath.Rel(srcdir, path)
// filepath.Rel can traverse parent directories, don't want those
if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return rel
}
}
return path
}
type longestFirst []string
func (strs longestFirst) Len() int { return len(strs) }
func (strs longestFirst) Less(i, j int) bool { return len(strs[i]) > len(strs[j]) }
func (strs longestFirst) Swap(i, j int) { strs[i], strs[j] = strs[j], strs[i] }
package cleanpath_test
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/palantir/stacktrace/cleanpath"
)
func TestRemoveGoPath(t *testing.T) {
for _, testcase := range []struct {
gopath []string
path string
expected string
}{
{
// empty gopath
gopath: []string{},
path: "/some/dir/src/pkg/prog.go",
expected: "/some/dir/src/pkg/prog.go",
},
{
// single matching dir in gopath
gopath: []string{"/some/dir"},
path: "/some/dir/src/pkg/prog.go",
expected: "pkg/prog.go",
},
{
// nonmatching dir in gopath
gopath: []string{"/other/dir"},
path: "/some/dir/src/pkg/prog.go",
expected: "/some/dir/src/pkg/prog.go",
},
{
// multiple matching dirs in gopath, shorter first
gopath: []string{"/some", "/some/src/dir"},
path: "/some/src/dir/src/pkg/prog.go",
expected: "pkg/prog.go",
},
{
// multiple matching dirs in gopath, longer first
gopath: []string{"/some/src/dir", "/some"},
path: "/some/src/dir/src/pkg/prog.go",
expected: "pkg/prog.go",
},
} {
gopath := strings.Join(testcase.gopath, string(filepath.ListSeparator))
err := os.Setenv("GOPATH", gopath)
assert.NoError(t, err, "error setting gopath")
cleaned := cleanpath.RemoveGoPath(testcase.path)
assert.Equal(t, testcase.expected, cleaned, "testcase: %+v", testcase)
}
}
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace_test
import (
"go-svc-tpl/utils/stacktrace"
)
const (
EcodeInvalidVillain = stacktrace.ErrorCode(iota)
EcodeNoSuchPseudo
EcodeNotFastEnough
EcodeTimeIsIllusion
EcodeNotImplemented
)
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace provides functions for wrapping an error to include line
number and/or error code information.
A stacktrace produced by this package looks like this:
Failed to register for villain discovery
--- at github.com/palantir/shield/agent/discovery.go:265 (ShieldAgent.reallyRegister) ---
--- at github.com/palantir/shield/connector/impl.go:89 (Connector.Register) ---
Caused by: Failed to load S.H.I.E.L.D. config from /opt/shield/conf/shield.yaml
--- at github.com/palantir/shield/connector/config.go:44 (withShieldConfig) ---
Caused by: There isn't enough time (4 picoseconds required)
--- at github.com/palantir/shield/axiom/pseudo/resource.go:46 (PseudoResource.Adjust) ---
--- at github.com/palantir/shield/axiom/pseudo/growth.go:110 (reciprocatingPseudo.growDown) ---
--- at github.com/palantir/shield/axiom/pseudo/growth.go:121 (reciprocatingPseudo.verify) ---
Caused by: Inverse tachyon pulse failed
--- at github.com/palantir/shield/metaphysic/tachyon.go:72 (TryPulse) ---
Note that stack traces are not designed to be user-visible. They can be valuable
in a log file of a server application, but nobody wants to see one of them in
CLI output or a web interface or a return value from library code.
*/
package stacktrace
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace
import (
"fmt"
"strings"
)
/*
DefaultFormat defines the behavior of err.Error() when called on a stacktrace,
as well as the default behavior of the "%v", "%s" and "%q" formatting
specifiers. By default, all of these produce a full stacktrace including line
number information. To have them produce a condensed single-line output, set
this value to stacktrace.FormatBrief.
The formatting specifier "%+s" can be used to force a full stacktrace regardless
of the value of DefaultFormat. Similarly, the formatting specifier "%#s" can be
used to force a brief output.
*/
var DefaultFormat = FormatFull
// Format is the type of the two possible values of stacktrace.DefaultFormat.
type Format int
const (
// FormatFull means format as a full stacktrace including line number information.
FormatFull Format = iota
// FormatBrief means Format on a single line without line number information.
FormatBrief
)
var _ fmt.Formatter = (*stacktrace)(nil)
func (st *stacktrace) Format(f fmt.State, c rune) {
var text string
if f.Flag('+') && !f.Flag('#') && c == 's' { // "%+s"
text = formatFull(st)
} else if f.Flag('#') && !f.Flag('+') && c == 's' { // "%#s"
text = formatBrief(st)
} else {
text = map[Format]func(*stacktrace) string{
FormatFull: formatFull,
FormatBrief: formatBrief,
}[DefaultFormat](st)
}
formatString := "%"
// keep the flags recognized by fmt package
for _, flag := range "-+# 0" {
if f.Flag(int(flag)) {
formatString += string(flag)
}
}
if width, has := f.Width(); has {
formatString += fmt.Sprint(width)
}
if precision, has := f.Precision(); has {
formatString += "."
formatString += fmt.Sprint(precision)
}
formatString += string(c)
fmt.Fprintf(f, formatString, text)
}
func formatFull(st *stacktrace) string {
var str string
newline := func() {
if str != "" && !strings.HasSuffix(str, "\n") {
str += "\n"
}
}
for curr, ok := st, true; ok; curr, ok = curr.cause.(*stacktrace) {
str += curr.message
if curr.file != "" {
newline()
if curr.function == "" {
str += fmt.Sprintf(" --- at %v:%v ---", curr.file, curr.line)
} else {
str += fmt.Sprintf(" --- at %v:%v (%v) ---", curr.file, curr.line, curr.function)
}
}
if curr.cause != nil {
newline()
if cause, ok := curr.cause.(*stacktrace); !ok {
str += "Caused by: "
str += curr.cause.Error()
} else if cause.message != "" {
str += "Caused by: "
}
}
}
return str
}
func formatBrief(st *stacktrace) string {
var str string
concat := func(msg string) {
if str != "" && msg != "" {
str += ": "
}
str += msg
}
curr := st
for {
concat(curr.message)
if cause, ok := curr.cause.(*stacktrace); ok {
curr = cause
} else {
break
}
}
if curr.cause != nil {
concat(curr.cause.Error())
}
return str
}
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace_test
import (
"errors"
"fmt"
"go-svc-tpl/utils/stacktrace"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFormat(t *testing.T) {
plainErr := errors.New("plain")
stacktraceErr := stacktrace.Propagate(plainErr, "decorated")
digits := regexp.MustCompile(`\d`)
for _, test := range []struct {
format stacktrace.Format
specifier string
expectedPlain string
expectedStacktrace string
}{
{
format: stacktrace.FormatFull,
specifier: "%v",
expectedPlain: "plain",
expectedStacktrace: "decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain",
},
{
format: stacktrace.FormatFull,
specifier: "%q",
expectedPlain: "\"plain\"",
expectedStacktrace: "\"decorated\\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\\nCaused by: plain\"",
},
{
format: stacktrace.FormatFull,
specifier: "%105s",
expectedPlain: " plain",
expectedStacktrace: " decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain",
},
{
format: stacktrace.FormatFull,
specifier: "%#s",
expectedPlain: "plain",
expectedStacktrace: "decorated: plain",
},
{
format: stacktrace.FormatBrief,
specifier: "%v",
expectedPlain: "plain",
expectedStacktrace: "decorated: plain",
},
{
format: stacktrace.FormatBrief,
specifier: "%q",
expectedPlain: "\"plain\"",
expectedStacktrace: "\"decorated: plain\"",
},
{
format: stacktrace.FormatBrief,
specifier: "%20s",
expectedPlain: " plain",
expectedStacktrace: " decorated: plain",
},
{
format: stacktrace.FormatBrief,
specifier: "%+s",
expectedPlain: "plain",
expectedStacktrace: "decorated\n --- at github.com/palantir/stacktrace/format_test.go:## (TestFormat) ---\nCaused by: plain",
},
} {
stacktrace.DefaultFormat = test.format
actualPlain := fmt.Sprintf(test.specifier, plainErr)
assert.Equal(t, test.expectedPlain, actualPlain)
actualStacktrace := fmt.Sprintf(test.specifier, stacktraceErr)
actualStacktrace = digits.ReplaceAllString(actualStacktrace, "#")
assert.Equal(t, test.expectedStacktrace, actualStacktrace)
}
}
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace_test
import "go-svc-tpl/utils/stacktrace"
type PublicObj struct{}
type privateObj struct{}
type ptrObj struct{}
func startDoing() error {
return stacktrace.NewError("%s %s %s %s", "failed", "to", "start", "doing")
}
func (PublicObj) DoPublic(err error) error {
return stacktrace.Propagate(err, "")
}
func (PublicObj) doPrivate(err error) error {
return stacktrace.Propagate(err, "")
}
func (privateObj) DoPublic(err error) error {
return stacktrace.Propagate(err, "")
}
func (privateObj) doPrivate(err error) error {
return stacktrace.Propagate(err, "")
}
func (*ptrObj) doPtr(err error) error {
return stacktrace.Propagate(err, "pointedly")
}
func doClosure(err error) error {
return func() error {
return stacktrace.Propagate(err, "so closed")
}()
}
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace
import (
"fmt"
"go-svc-tpl/utils/stacktrace/cleanpath"
"math"
"runtime"
"strings"
)
/*
CleanPath function is applied to file paths before adding them to a stacktrace.
By default, it makes the path relative to the $GOPATH environment variable.
To remove some additional prefix like "github.com" from file paths in
stacktraces, use something like:
stacktrace.CleanPath = func(path string) string {
path = cleanpath.RemoveGoPath(path)
path = strings.TrimPrefix(path, "github.com/")
return path
}
*/
var CleanPath = cleanpath.RemoveGoPath
/*
NewError is a drop-in replacement for fmt.Errorf that includes line number
information. The canonical call looks like this:
if !IsOkay(arg) {
return stacktrace.NewError("Expected %v to be okay", arg)
}
*/
func NewError(msg string, vals ...interface{}) error {
return create(nil, NoCode, msg, vals...)
}
/*
Propagate wraps an error to include line number information. The msg and vals
arguments work like the ones for fmt.Errorf.
The message passed to Propagate should describe the action that failed,
resulting in the cause. The canonical call looks like this:
result, err := process(arg)
if err != nil {
return nil, stacktrace.Propagate(err, "Failed to process %v", arg)
}
To write the message, ask yourself "what does this call do?" What does
process(arg) do? It processes ${arg}, so the message is that we failed to
process ${arg}.
Pay attention that the message is not redundant with the one in err. If it is
not possible to add any useful contextual information beyond what is already
included in an error, msg can be an empty string:
func Something() error {
mutex.Lock()
defer mutex.Unlock()
err := reallySomething()
return stacktrace.Propagate(err, "")
}
If cause is nil, Propagate returns nil. This allows elision of some "if err !=
nil" checks.
*/
func Propagate(cause error, msg string, vals ...interface{}) error {
if cause == nil {
// Allow calling Propagate without checking whether there is error
return nil
}
return create(cause, NoCode, msg, vals...)
}
/*
ErrorCode is a code that can be attached to an error as it is passed/propagated
up the stack.
There is no predefined set of error codes. You define the ones relevant to your
application:
const (
EcodeManifestNotFound = stacktrace.ErrorCode(iota)
EcodeBadInput
EcodeTimeout
)
The one predefined error code is NoCode, which has a value of math.MaxUint16.
Avoid using that value as an error code.
An ordinary stacktrace.Propagate call preserves the error code of an error.
*/
type ErrorCode uint16
/*
NoCode is the error code of errors with no code explicitly attached.
*/
const NoCode ErrorCode = math.MaxUint16
/*
NewErrorWithCode is similar to NewError but also attaches an error code.
*/
func NewErrorWithCode(code ErrorCode, msg string, vals ...interface{}) error {
return create(nil, code, msg, vals...)
}
/*
PropagateWithCode is similar to Propagate but also attaches an error code.
_, err := os.Stat(manifestPath)
if os.IsNotExist(err) {
return stacktrace.PropagateWithCode(err, EcodeManifestNotFound, "")
}
*/
func PropagateWithCode(cause error, code ErrorCode, msg string, vals ...interface{}) error {
if cause == nil {
// Allow calling PropagateWithCode without checking whether there is error
return nil
}
return create(cause, code, msg, vals...)
}
/*
NewMessageWithCode returns an error that prints just like fmt.Errorf with no
line number, but including a code. The error code mechanism can be useful by
itself even where stack traces with line numbers are not warranted.
ttl := req.URL.Query().Get("ttl")
if ttl == "" {
return 0, stacktrace.NewMessageWithCode(EcodeBadInput, "Missing ttl query parameter")
}
*/
func NewMessageWithCode(code ErrorCode, msg string, vals ...interface{}) error {
return &stacktrace{
message: fmt.Sprintf(msg, vals...),
code: code,
}
}
/*
GetCode extracts the error code from an error.
for i := 0; i < attempts; i++ {
err := Do()
if stacktrace.GetCode(err) != EcodeTimeout {
return err
}
// try a few more times
}
return stacktrace.NewError("timed out after %d attempts", attempts)
GetCode returns the special value stacktrace.NoCode if err is nil or if there is
no error code attached to err.
*/
func GetCode(err error) ErrorCode {
if err, ok := err.(*stacktrace); ok {
return err.code
}
return NoCode
}
type stacktrace struct {
message string
cause error
code ErrorCode
file string
function string
line int
}
func create(cause error, code ErrorCode, msg string, vals ...interface{}) error {
// If no error code specified, inherit error code from the cause.
if code == NoCode {
code = GetCode(cause)
}
err := &stacktrace{
message: fmt.Sprintf(msg, vals...),
cause: cause,
code: code,
}
// Caller of create is NewError or Propagate, so user's code is 2 up.
pc, file, line, ok := runtime.Caller(2)
if !ok {
return err
}
if CleanPath != nil {
file = CleanPath(file)
}
err.file, err.line = file, line
f := runtime.FuncForPC(pc)
if f == nil {
return err
}
err.function = shortFuncName(f)
return err
}
/* "FuncName" or "Receiver.MethodName" */
func shortFuncName(f *runtime.Func) string {
// f.Name() is like one of these:
// - "github.com/palantir/shield/package.FuncName"
// - "github.com/palantir/shield/package.Receiver.MethodName"
// - "github.com/palantir/shield/package.(*PtrReceiver).MethodName"
longName := f.Name()
withoutPath := longName[strings.LastIndex(longName, "/")+1:]
withoutPackage := withoutPath[strings.Index(withoutPath, ".")+1:]
shortName := withoutPackage
shortName = strings.Replace(shortName, "(", "", 1)
shortName = strings.Replace(shortName, "*", "", 1)
shortName = strings.Replace(shortName, ")", "", 1)
return shortName
}
func (st *stacktrace) Error() string {
return fmt.Sprint(st)
}
// ExitCode returns the exit code associated with the stacktrace error based on its error code. If the error code is
// NoCode, return 1 (default); otherwise, returns the value of the error code.
func (st *stacktrace) ExitCode() int {
if st.code == NoCode {
return 1
}
return int(st.code)
}
// Copyright 2016 Palantir Technologies
//
// 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 stacktrace_test
import (
"errors"
"fmt"
"go-svc-tpl/utils/stacktrace"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMessage(t *testing.T) {
err := startDoing()
err = PublicObj{}.DoPublic(err)
err = PublicObj{}.doPrivate(err)
err = privateObj{}.DoPublic(err)
err = privateObj{}.doPrivate(err)
err = (&ptrObj{}).doPtr(err)
err = doClosure(err)
expected := strings.Join([]string{
"so closed",
" --- at github.com/palantir/stacktrace/functions_for_test.go:51 (doClosure.func1) ---",
"Caused by: pointedly",
" --- at github.com/palantir/stacktrace/functions_for_test.go:46 (ptrObj.doPtr) ---",
" --- at github.com/palantir/stacktrace/functions_for_test.go:42 (privateObj.doPrivate) ---",
" --- at github.com/palantir/stacktrace/functions_for_test.go:38 (privateObj.DoPublic) ---",
" --- at github.com/palantir/stacktrace/functions_for_test.go:34 (PublicObj.doPrivate) ---",
" --- at github.com/palantir/stacktrace/functions_for_test.go:30 (PublicObj.DoPublic) ---",
"Caused by: failed to start doing",
" --- at github.com/palantir/stacktrace/functions_for_test.go:26 (startDoing) ---",
}, "\n")
stacktrace.DefaultFormat = stacktrace.FormatFull
assert.Equal(t, expected, err.Error())
assert.Equal(t, expected, fmt.Sprint(err))
}
func TestGetCode(t *testing.T) {
for _, test := range []struct {
originalError error
originalCode stacktrace.ErrorCode
}{
{
originalError: errors.New("err"),
originalCode: stacktrace.NoCode,
},
{
originalError: stacktrace.NewError("err"),
originalCode: stacktrace.NoCode,
},
{
originalError: stacktrace.NewErrorWithCode(EcodeInvalidVillain, "err"),
originalCode: EcodeInvalidVillain,
},
{
originalError: stacktrace.NewMessageWithCode(EcodeNoSuchPseudo, "err"),
originalCode: EcodeNoSuchPseudo,
},
} {
err := test.originalError
assert.Equal(t, test.originalCode, stacktrace.GetCode(err))
err = stacktrace.Propagate(err, "")
assert.Equal(t, test.originalCode, stacktrace.GetCode(err))
err = stacktrace.PropagateWithCode(err, EcodeNotFastEnough, "")
assert.Equal(t, EcodeNotFastEnough, stacktrace.GetCode(err))
err = stacktrace.PropagateWithCode(err, EcodeTimeIsIllusion, "")
assert.Equal(t, EcodeTimeIsIllusion, stacktrace.GetCode(err))
}
}
func TestPropagateNil(t *testing.T) {
var err error
err = stacktrace.Propagate(err, "")
assert.Nil(t, err)
err = stacktrace.PropagateWithCode(err, EcodeNotImplemented, "")
assert.Nil(t, err)
assert.Equal(t, stacktrace.NoCode, stacktrace.GetCode(err))
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment