diff --git a/acl/acl.go b/acl/acl.go index 59a9b3c6f23..41160dfd1e7 100644 --- a/acl/acl.go +++ b/acl/acl.go @@ -8,12 +8,12 @@ package acl import ( "context" "encoding/json" + "errors" "fmt" "strings" "time" "github.com/golang/glog" - "github.com/pkg/errors" "github.com/spf13/viper" "github.com/dgraph-io/dgo/v240" @@ -26,7 +26,7 @@ func getUserAndGroup(conf *viper.Viper) (userId string, groupId string, err erro groupId = conf.GetString("group") if (len(userId) == 0 && len(groupId) == 0) || (len(userId) != 0 && len(groupId) != 0) { - return "", "", errors.Errorf("one of the --user or --group must be specified, but not both") + return "", "", errors.New("one of the --user or --group must be specified, but not both") } return userId, groupId, nil } @@ -47,10 +47,10 @@ func checkForbiddenOpts(conf *viper.Viper, forbiddenOpts []string) error { case bool: isSet = conf.GetBool(opt) default: - return errors.Errorf("unexpected option type for %s", opt) + return fmt.Errorf("unexpected option type for %s", opt) } if isSet { - return errors.Errorf("the option --%s should not be set", opt) + return fmt.Errorf("the option --%s should not be set", opt) } } @@ -77,7 +77,7 @@ func add(conf *viper.Viper) error { func userAdd(conf *viper.Viper, userid string, password string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() @@ -100,10 +100,10 @@ func userAdd(conf *viper.Viper, userid string, password string) error { user, err := queryUser(ctx, txn, userid) if err != nil { - return errors.Wrapf(err, "while querying user") + return fmt.Errorf("while querying user: %w", err) } if user != nil { - return errors.Errorf("unable to create user because of conflict: %v", userid) + return fmt.Errorf("unable to create user because of conflict: %v", userid) } createUserNQuads := CreateUserNQuads(userid, password) @@ -114,7 +114,7 @@ func userAdd(conf *viper.Viper, userid string, password string) error { } if _, err := txn.Mutate(ctx, mu); err != nil { - return errors.Wrapf(err, "unable to create user") + return fmt.Errorf("unable to create user: %w", err) } fmt.Printf("Created new user with id %v\n", userid) @@ -124,7 +124,7 @@ func userAdd(conf *viper.Viper, userid string, password string) error { func groupAdd(conf *viper.Viper, groupId string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() @@ -139,10 +139,10 @@ func groupAdd(conf *viper.Viper, groupId string) error { group, err := queryGroup(ctx, txn, groupId) if err != nil { - return errors.Wrapf(err, "while querying group") + return fmt.Errorf("while querying group: %w", err) } if group != nil { - return errors.Errorf("group %q already exists", groupId) + return fmt.Errorf("group %q already exists", groupId) } createGroupNQuads := CreateGroupNQuads(groupId) @@ -152,7 +152,7 @@ func groupAdd(conf *viper.Viper, groupId string) error { Set: createGroupNQuads, } if _, err = txn.Mutate(ctx, mu); err != nil { - return errors.Wrapf(err, "unable to create group") + return fmt.Errorf("unable to create group: %w", err) } fmt.Printf("Created new group with id %v\n", groupId) @@ -191,7 +191,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, queryFn func(context.Context, *dgo.Txn, string) (AclEntity, error)) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() @@ -209,7 +209,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, return err } if len(entity.GetUid()) == 0 { - return errors.Errorf("unable to delete %q since it does not exist", + return fmt.Errorf("unable to delete %q since it does not exist", userOrGroupId) } @@ -226,7 +226,7 @@ func userOrGroupDel(conf *viper.Viper, userOrGroupId string, } if _, err = txn.Mutate(ctx, mu); err != nil { - return errors.Wrapf(err, "unable to delete %q", userOrGroupId) + return fmt.Errorf("unable to delete %q: %w", userOrGroupId, err) } fmt.Printf("Successfully deleted %q\n", userOrGroupId) @@ -249,8 +249,7 @@ func mod(conf *viper.Viper) error { groupList := conf.GetString("group_list") if (newPassword && groupList != defaultGroupList) || (!newPassword && groupList == defaultGroupList) { - return errors.Errorf( - "one of --new_password or --group_list must be provided, but not both") + return errors.New("one of --new_password or --group_list must be provided, but not both") } if newPassword { @@ -272,7 +271,7 @@ func changePassword(conf *viper.Viper, userId string) error { // 1. get the dgo client with appropriate access JWT dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get dgo client") + return fmt.Errorf("unable to get dgo client: %w", err) } defer cancel() @@ -294,10 +293,10 @@ func changePassword(conf *viper.Viper, userId string) error { // 3. query the user's current uid user, err := queryUser(ctx, txn, userId) if err != nil { - return errors.Wrapf(err, "while querying user") + return fmt.Errorf("while querying user: %w", err) } if user == nil { - return errors.Errorf("user %q does not exist", userId) + return fmt.Errorf("user %q does not exist", userId) } // 4. mutate the user's password @@ -312,7 +311,7 @@ func changePassword(conf *viper.Viper, userId string) error { Set: chPdNQuads, } if _, err := txn.Mutate(ctx, mu); err != nil { - return errors.Wrapf(err, "unable to change password for user %v", userId) + return fmt.Errorf("unable to change password for user %v: %w", userId, err) } fmt.Printf("Successfully changed password for %v\n", userId) return nil @@ -321,7 +320,7 @@ func changePassword(conf *viper.Viper, userId string) error { func userMod(conf *viper.Viper, userId string, groups string) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() @@ -336,10 +335,10 @@ func userMod(conf *viper.Viper, userId string, groups string) error { user, err := queryUser(ctx, txn, userId) if err != nil { - return errors.Wrapf(err, "while querying user") + return fmt.Errorf("while querying user: %w", err) } if user == nil { - return errors.Errorf("user %q does not exist", userId) + return fmt.Errorf("user %q does not exist", userId) } targetGroupsMap := make(map[string]struct{}) @@ -384,7 +383,7 @@ func userMod(conf *viper.Viper, userId string, groups string) error { } if _, err := txn.Mutate(ctx, mu); err != nil { - return errors.Wrapf(err, "while mutating the group") + return fmt.Errorf("while mutating the group: %w", err) } fmt.Printf("Successfully modified groups for user %v.\n", userId) fmt.Println("The latest info is:") @@ -407,17 +406,17 @@ func chMod(conf *viper.Viper) error { perm := conf.GetInt("perm") switch { case len(groupName) == 0: - return errors.Errorf("the group must not be empty") + return errors.New("the group must not be empty") case len(predicate) == 0: - return errors.Errorf("no predicates specified") + return errors.New("no predicates specified") case perm > 7: - return errors.Errorf("the perm value must be less than or equal to 7, "+ + return fmt.Errorf("the perm value must be less than or equal to 7, "+ "the provided value is %d", perm) } dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() @@ -502,10 +501,10 @@ func chMod(conf *viper.Viper) error { uidCount, ok := jsonResp["groupUIDCount"][0]["count"] if !ok { - return errors.New("Malformed output of groupUIDCount") + return errors.New("malformed output of groupUIDCount") } else if uidCount == 0 { // We already have a check for multiple groups with same name at dgraph/acl/utils.go:142 - return errors.Errorf("Group <%s> doesn't exist", groupName) + return fmt.Errorf("group <%s> doesn't exist", groupName) } return nil } @@ -528,7 +527,7 @@ func queryUser(ctx context.Context, txn *dgo.Txn, userid string) (user *User, er queryResp, err := txn.QueryWithVars(ctx, query, queryVars) if err != nil { - return nil, errors.Wrapf(err, "hile query user with id %s", userid) + return nil, fmt.Errorf("while query user with id %s: %w", userid, err) } user, err = UnmarshalUser(queryResp, "user") if err != nil { @@ -544,7 +543,7 @@ func getUserModNQuad(ctx context.Context, txn *dgo.Txn, userId string, return nil, err } if group == nil { - return nil, errors.Errorf("group %q does not exist", groupId) + return nil, fmt.Errorf("group %q does not exist", groupId) } createUserGroupNQuads := &api.NQuad{ @@ -590,7 +589,7 @@ func queryAndPrintUser(ctx context.Context, txn *dgo.Txn, userId string) error { return err } if user == nil { - return errors.Errorf("The user %q does not exist.\n", userId) + return fmt.Errorf("the user %q does not exist", userId) } fmt.Printf("User : %s\n", userId) @@ -608,7 +607,7 @@ func queryAndPrintGroup(ctx context.Context, txn *dgo.Txn, groupId string) error return err } if group == nil { - return errors.Errorf("The group %s doesn't exist", groupId) + return fmt.Errorf("the group %s doesn't exist", groupId) } fmt.Printf("Group: %s\n", groupId) @@ -636,7 +635,7 @@ func info(conf *viper.Viper) error { dc, cancel, err := getClientWithAdminCtx(conf) if err != nil { - return errors.Wrapf(err, "unable to get admin context") + return fmt.Errorf("unable to get admin context: %w", err) } defer cancel() diff --git a/acl/acl_test.go b/acl/acl_test.go index 275b8179501..9b9c742da52 100644 --- a/acl/acl_test.go +++ b/acl/acl_test.go @@ -11,12 +11,12 @@ package acl import ( "context" "encoding/json" + "errors" "fmt" "strconv" "testing" "time" - "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/dgraph-io/dgo/v240" diff --git a/acl/utils.go b/acl/utils.go index 59e8dc6a77f..9513c7814a6 100644 --- a/acl/utils.go +++ b/acl/utils.go @@ -7,9 +7,9 @@ package acl import ( "encoding/json" + "fmt" "github.com/golang/glog" - "github.com/pkg/errors" "github.com/spf13/viper" "github.com/dgraph-io/dgo/v240" @@ -86,7 +86,7 @@ func UnmarshalUser(resp *api.Response, userKey string) (user *User, err error) { err = json.Unmarshal(resp.GetJson(), &m) if err != nil { - return nil, errors.Wrapf(err, "unable to unmarshal the query user response") + return nil, fmt.Errorf("unable to unmarshal the query user response: %w", err) } users := m[userKey] if len(users) == 0 { @@ -94,7 +94,7 @@ func UnmarshalUser(resp *api.Response, userKey string) (user *User, err error) { return nil, nil } if len(users) > 1 { - return nil, errors.Errorf("Found multiple users: %s", resp.GetJson()) + return nil, fmt.Errorf("found multiple users: %s", resp.GetJson()) } return &users[0], nil } @@ -136,7 +136,7 @@ func UnmarshalGroup(input []byte, groupKey string) (group *Group, err error) { return nil, nil } if len(groups) > 1 { - return nil, errors.Errorf("found multiple groups: %s", input) + return nil, fmt.Errorf("found multiple groups: %s", input) } return &groups[0], nil diff --git a/audit/run.go b/audit/run.go index c8c31bec353..2b9ae271003 100644 --- a/audit/run.go +++ b/audit/run.go @@ -9,12 +9,12 @@ import ( "crypto/aes" "crypto/cipher" "encoding/binary" + "errors" "fmt" "io" "os" "github.com/golang/glog" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -102,7 +102,7 @@ func run() error { } if err := decrypt(file, outfile, block, stat.Size()); err != nil { - return errors.Wrap(err, "could not decrypt audit log") + return fmt.Errorf("could not decrypt audit log: %w", err) } glog.Infof("decryption of audit file %s is done: decrypted file is %s", @@ -119,14 +119,14 @@ func decrypt(file io.ReaderAt, outfile io.Writer, block cipher.Block, sz int64) iv := make([]byte, aes.BlockSize) n, err := file.ReadAt(iv, iterator) // get first iv if err != nil { - return nil, 0, errors.Wrap(err, "unable to read IV") + return nil, 0, fmt.Errorf("unable to read IV: %w", err) } iterator = iterator + int64(n) + 4 // length of verification text encoded in uint32 ct := make([]byte, len(x.VerificationText)) n, err = file.ReadAt(ct, iterator) if err != nil { - return nil, 0, errors.Wrap(err, "unable to read verification text") + return nil, 0, fmt.Errorf("unable to read verification text: %w", err) } iterator = iterator + int64(n) @@ -145,14 +145,14 @@ func decrypt(file io.ReaderAt, outfile io.Writer, block cipher.Block, sz int64) iv := make([]byte, aes.BlockSize) n, err := file.ReadAt(iv, iterator) if err != nil { - return nil, 0, errors.Wrap(err, "unable to read IV") + return nil, 0, fmt.Errorf("unable to read IV: %w", err) } iterator = iterator + int64(n) ct := make([]byte, len(x.VerificationTextDeprecated)) n, err = file.ReadAt(ct, iterator) if err != nil { - return nil, 0, errors.Wrap(err, "unable to read verification text") + return nil, 0, fmt.Errorf("unable to read verification text: %w", err) } iterator = iterator + int64(n) diff --git a/backup/run.go b/backup/run.go index eaa35025087..bc94a9a1908 100644 --- a/backup/run.go +++ b/backup/run.go @@ -8,6 +8,7 @@ package backup import ( "context" "encoding/json" + "errors" "fmt" "net/url" "os" @@ -15,7 +16,6 @@ import ( "time" "github.com/golang/glog" - "github.com/pkg/errors" "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -172,7 +172,7 @@ func runRestoreCmd() error { fmt.Println("Writing postings to:", opt.pdir) if opt.zero == "" && opt.forceZero { - return errors.Errorf("No Dgraph Zero address passed. Use the --force_zero option if you " + + return errors.New("No Dgraph Zero address passed. Use the --force_zero option if you " + "meant to do this") } @@ -191,7 +191,7 @@ func runRestoreCmd() error { zero, err := grpc.NewClient(opt.zero, callOpts...) if err != nil { - return errors.Wrapf(err, "Unable to connect to %s", opt.zero) + return fmt.Errorf("unable to connect to %s: %w", opt.zero, err) } zc = pb.NewZeroClient(zero) } @@ -206,7 +206,7 @@ func runRestoreCmd() error { return result.Err } if result.Version == 0 { - return errors.Errorf("failed to obtain a restore version") + return errors.New("failed to obtain a restore version") } fmt.Printf("Restore version: %d\n", result.Version) fmt.Printf("Restore max uid: %d\n", result.MaxLeaseUid) @@ -236,10 +236,10 @@ func runRestoreCmd() error { } if err := leaseID(result.MaxLeaseUid, pb.Num_UID); err != nil { - return errors.Wrapf(err, "cannot update max uid lease after restore.") + return fmt.Errorf("cannot update max uid lease after restore: %w", err) } if err := leaseID(result.MaxLeaseNsId, pb.Num_NS_ID); err != nil { - return errors.Wrapf(err, "cannot update max namespace lease after restore.") + return fmt.Errorf("cannot update max namespace lease after restore: %w", err) } } @@ -250,7 +250,7 @@ func runRestoreCmd() error { func runLsbackupCmd() error { manifests, err := worker.ListBackupManifests(opt.location, nil) if err != nil { - return errors.Wrapf(err, "while listing manifests") + return fmt.Errorf("while listing manifests: %w", err) } type backupEntry struct { @@ -353,11 +353,11 @@ func (bw *bufWriter) Write(buf *z.Buffer) error { err := buf.SliceIterate(func(s []byte) error { kv.Reset() if err := proto.Unmarshal(s, kv); err != nil { - return errors.Wrap(err, "processKvBuf failed to unmarshal kv") + return fmt.Errorf("processKvBuf failed to unmarshal kv: %w", err) } pk, err := x.Parse(kv.Key) if err != nil { - return errors.Wrap(err, "processKvBuf failed to parse key") + return fmt.Errorf("processKvBuf failed to parse key: %w", err) } if pk.Attr == "_predicate_" { return nil @@ -368,12 +368,12 @@ func (bw *bufWriter) Write(buf *z.Buffer) error { if pk.IsData() { pl := &pb.PostingList{} if err := proto.Unmarshal(kv.Value, pl); err != nil { - return errors.Wrap(err, "processKvBuf failed to Unmarshal pl") + return fmt.Errorf("processKvBuf failed to Unmarshal pl: %w", err) } l := posting.NewList(kv.Key, pl, kv.Version) kvList, err := worker.ToExportKvList(pk, l, bw.req) if err != nil { - return errors.Wrap(err, "processKvBuf failed to Export") + return fmt.Errorf("processKvBuf failed to export: %w", err) } if len(kvList.Kv) == 0 { return nil @@ -383,7 +383,7 @@ func (bw *bufWriter) Write(buf *z.Buffer) error { } return nil }) - return errors.Wrap(err, "bufWriter failed to write") + return fmt.Errorf("bufWriter failed to write: %w", err) } func runExportBackup() error { @@ -393,28 +393,28 @@ func runExportBackup() error { } opt.key = keys.EncKey if opt.format != "json" && opt.format != "rdf" { - return errors.Errorf("invalid format %s", opt.format) + return fmt.Errorf("invalid format %s", opt.format) } // Create exportDir and temporary folder to store the restored backup. exportDir, err := filepath.Abs(opt.destination) if err != nil { - return errors.Wrapf(err, "cannot convert path %s to absolute path", exportDir) + return fmt.Errorf("cannot convert path %s to absolute path: %w", exportDir, err) } if err := os.MkdirAll(exportDir, 0755); err != nil { - return errors.Wrapf(err, "cannot create dir %s", exportDir) + return fmt.Errorf("cannot create dir %s: %w", exportDir, err) } uri, err := url.Parse(opt.location) if err != nil { - return errors.Wrapf(err, "runExportBackup") + return fmt.Errorf("runExportBackup: %w", err) } handler, err := worker.NewUriHandler(uri, nil) if err != nil { - return errors.Wrapf(err, "runExportBackup") + return fmt.Errorf("runExportBackup: %w", err) } latestManifest, err := worker.GetLatestManifest(handler, uri) if err != nil { - return errors.Wrapf(err, "runExportBackup") + return fmt.Errorf("runExportBackup: %w", err) } mapDir, err := os.MkdirTemp(x.WorkerConfig.TmpDir, "restore-export") @@ -436,7 +436,7 @@ func runExportBackup() error { RestoreTs: 1, } if _, err := worker.RunMapper(req, mapDir); err != nil { - return errors.Wrap(err, "Failed to map the backups") + return fmt.Errorf("failed to map the backups: %w", err) } in := &pb.ExportRequest{ GroupId: gid, @@ -459,10 +459,10 @@ func runExportBackup() error { w := &bufWriter{req: in, writers: writers} if err := worker.RunReducer(w, mapDir); err != nil { - return errors.Wrap(err, "Failed to reduce the map") + return fmt.Errorf("failed to reduce the map: %w", err) } if files, err := exportStorage.FinishWriting(writers); err != nil { - return errors.Wrap(err, "Failed to finish write") + return fmt.Errorf("failed to finish write: %w", err) } else { glog.Infof("done exporting files: %v\n", files) } diff --git a/check_upgrade/check_upgrade.go b/check_upgrade/check_upgrade.go index f2139636231..739d45bf5a6 100644 --- a/check_upgrade/check_upgrade.go +++ b/check_upgrade/check_upgrade.go @@ -16,7 +16,6 @@ import ( "time" "github.com/golang-jwt/jwt/v5" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/hypermodeinc/dgraph/v24/dgraphapi" @@ -75,26 +74,26 @@ func parseJWTKey(alg jwt.SigningMethod, key x.Sensitive) (interface{}, interface case strings.HasPrefix(alg.Alg(), "ES"): pk, err := jwt.ParseECPrivateKeyFromPEM(key) if err != nil { - return nil, nil, errors.Wrapf(err, "error parsing ACL key as ECDSA private key") + return nil, nil, fmt.Errorf("error parsing ACL key as ECDSA private key: %w", err) } return pk, &pk.PublicKey, nil case strings.HasPrefix(alg.Alg(), "RS") || strings.HasPrefix(alg.Alg(), "PS"): pk, err := jwt.ParseRSAPrivateKeyFromPEM(key) if err != nil { - return nil, nil, errors.Wrapf(err, "error parsing ACL key as RSA private key") + return nil, nil, fmt.Errorf("error parsing ACL key as RSA private key: %w", err) } return pk, &pk.PublicKey, nil case alg.Alg() == "EdDSA": pk, err := jwt.ParseEdPrivateKeyFromPEM(key) if err != nil { - return nil, nil, errors.Wrapf(err, "error parsing ACL key as EdDSA private key") + return nil, nil, fmt.Errorf("error parsing ACL key as EdDSA private key: %w", err) } return pk.(crypto.Signer), pk.(ed25519.PrivateKey).Public(), nil default: - return nil, nil, errors.Errorf("unsupported signing algorithm: %v", alg.Alg()) + return nil, nil, fmt.Errorf("unsupported signing algorithm: %v", alg.Alg()) } } @@ -127,7 +126,7 @@ func getAccessJwt(userId string, group string, namespace uint64, aclSecretFile s jwtString, err := token.SignedString(x.MaybeKeyToBytes(privKey)) if err != nil { - return "", errors.Errorf("unable to encode jwt to string: %v", err) + return "", fmt.Errorf("unable to encode jwt to string: %w", err) } return jwtString, nil } @@ -135,7 +134,7 @@ func getAccessJwt(userId string, group string, namespace uint64, aclSecretFile s func setupClient(alphaHttp string) (*dgraphapi.HTTPClient, error) { httpClient, err := dgraphapi.GetHttpClient(alphaHttp, "") if err != nil { - return nil, errors.Wrapf(err, "while getting HTTP client") + return nil, fmt.Errorf("while getting HTTP client: %w", err) } return httpClient, nil } @@ -197,12 +196,12 @@ func queryDuplicateNodes(hc *dgraphapi.HTTPClient) ([3]map[string][]string, erro resp, err := hc.PostDqlQuery(query) if err != nil { - return [3]map[string][]string{}, errors.Wrapf(err, "while querying dgraph for duplicate nodes") + return [3]map[string][]string{}, fmt.Errorf("while querying dgraph for duplicate nodes: %w", err) } var result Response if err := json.Unmarshal(resp, &result); err != nil { - return [3]map[string][]string{}, errors.Wrapf(err, "while unmarshalling response: %v", string(resp)) + return [3]map[string][]string{}, fmt.Errorf("while unmarshalling response: %v: %w", string(resp), err) } return findDuplicateNodes(result.Data.Nodes), nil @@ -292,7 +291,7 @@ func queryUserGroup(hc *dgraphapi.HTTPClient, uid string) (aclNode, error) { } var result Response if err := json.Unmarshal(resp, &result); err != nil { - return aclNode{}, errors.Wrapf(err, "while unmarshalling response: %v", string(resp)) + return aclNode{}, fmt.Errorf("while unmarshalling response: %v: %w", string(resp), err) } if len(result.Data.Nodes) > 1 { @@ -506,12 +505,12 @@ func checkUpgrade() error { accessJwt, err = getAccessJwt(dgraphapi.DefaultUser, guardianGroup, 0, cmdInput.aclSecretKeyFilePath, cmdInput.jwtAlg) if err != nil { - return errors.Wrapf(err, "while getting access jwt token") + return fmt.Errorf("while getting access jwt token: %w", err) } } hc, err := setupClient(cmdInput.alphaHttp) if err != nil { - return errors.Wrapf(err, "while setting up clients") + return fmt.Errorf("while setting up clients: %w", err) } hc.AccessJwt = accessJwt @@ -520,7 +519,7 @@ func checkUpgrade() error { if cmdInput.namespace == 0 { namespaces, err = hc.ListNamespaces() if err != nil { - return errors.Wrapf(err, "while lisiting namespaces") + return fmt.Errorf("while lisiting namespaces: %w", err) } } else { namespaces = append(namespaces, cmdInput.namespace) @@ -531,11 +530,11 @@ func checkUpgrade() error { hc.AccessJwt, err = getAccessJwt(dgraphapi.DefaultUser, guardianGroup, ns, cmdInput.aclSecretKeyFilePath, cmdInput.jwtAlg) if err != nil { - return errors.Wrapf(err, "while getting access jwt token for namespace %v", ns) + return fmt.Errorf("while getting access jwt token for namespace %v: %w", ns, err) } } else { if err := hc.LoginIntoNamespace(cmdInput.dgUser, cmdInput.password, ns); err != nil { - return errors.Wrapf(err, "while logging into namespace %v", ns) + return fmt.Errorf("while logging into namespace %v: %w", ns, err) } } diff --git a/chunker/chunk.go b/chunker/chunk.go index 05684bd4eb2..a21cb744c53 100644 --- a/chunker/chunk.go +++ b/chunker/chunk.go @@ -10,6 +10,8 @@ import ( "bytes" "compress/gzip" encjson "encoding/json" + "errors" + "fmt" "io" "net/http" "os" @@ -17,8 +19,6 @@ import ( "strings" "unicode" - "github.com/pkg/errors" - "github.com/hypermodeinc/dgraph/v24/enc" "github.com/hypermodeinc/dgraph/v24/lex" "github.com/hypermodeinc/dgraph/v24/x" @@ -142,7 +142,7 @@ func (rc *rdfChunker) Parse(chunkBuf *bytes.Buffer) error { case err == ErrEmpty: continue // blank line or comment case err != nil: - return errors.Wrapf(err, "while parsing line %q", str) + return fmt.Errorf("while parsing line %q: %w", str, err) default: rc.nqs.Push(&nq) } @@ -168,7 +168,7 @@ func (jc *jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) { return nil, err } default: - return nil, errors.Errorf("file is not JSON") + return nil, errors.New("file is not JSON") } out := new(bytes.Buffer) @@ -192,7 +192,7 @@ func (jc *jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) { if err == io.EOF { // handles the EOF case, return the buffer which represents the top level map if jc.inList { - return nil, errors.Errorf("JSON file ends abruptly, expecting ]") + return nil, errors.New("JSON file ends abruptly, expecting ]") } if _, err := out.WriteRune(']'); err != nil { @@ -205,12 +205,12 @@ func (jc *jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) { if ch == ']' { if !jc.inList { - return nil, errors.Errorf("JSON map is followed by an extraneous ]") + return nil, errors.New("JSON map is followed by an extraneous ]") } // validate that there are no more non-space chars after the ] if slurpSpace(r) != io.EOF { - return nil, errors.New("Not all of JSON file consumed") + return nil, errors.New("not all of JSON file consumed") } if _, err := out.WriteRune(']'); err != nil { @@ -219,13 +219,13 @@ func (jc *jsonChunker) Chunk(r *bufio.Reader) (*bytes.Buffer, error) { return out, io.EOF } - // In the non termination cases, ensure at least one map has been consumed, and + // In the non-termination cases, ensure at least one map has been consumed, and // the only allowed char after the map is ",". if out.Len() == 1 { // 1 represents the [ inserted before the for loop - return nil, errors.Errorf("Illegal rune found \"%c\", expecting {", ch) + return nil, fmt.Errorf("illegal rune found \"%c\", expecting {", ch) } if ch != ',' { - return nil, errors.Errorf("JSON map is followed by illegal rune \"%c\"", ch) + return nil, fmt.Errorf("JSON map is followed by illegal rune \"%c\"", ch) } } if _, err := out.WriteRune(']'); err != nil { diff --git a/chunker/json_parser.go b/chunker/json_parser.go index 757ff85b86b..ee2c72dde38 100644 --- a/chunker/json_parser.go +++ b/chunker/json_parser.go @@ -8,6 +8,7 @@ package chunker import ( "bytes" "encoding/json" + "errors" "fmt" "math/rand" "strconv" @@ -15,7 +16,6 @@ import ( "sync/atomic" "unicode" - "github.com/pkg/errors" "github.com/twpayne/go-geom" "github.com/twpayne/go-geom/encoding/geojson" @@ -27,6 +27,8 @@ import ( "github.com/hypermodeinc/dgraph/v24/x" ) +var errEmptyUID = errors.New("UID must be present and non-zero while deleting edges") + func stripSpaces(str string) string { return strings.Map(func(r rune) rune { if unicode.IsSpace(r) { @@ -85,7 +87,7 @@ func handleBasicFacetsType(key string, facetVal interface{}) (*api.Facet, error) jsonValue = v valueType = api.Facet_BOOL default: - return nil, errors.Errorf("facet value can only be string/number/bool.") + return nil, errors.New("facet value can only be string/number/bool") } // Convert facet val interface{} to binary. @@ -128,7 +130,7 @@ func parseMapFacets(m map[string]interface{}, prefix string) ([]map[int]*api.Fac fm, ok := facetVal.(map[string]interface{}) if !ok { - return nil, errors.Errorf("facets format should be of type map for "+ + return nil, fmt.Errorf("facets format should be of type map for "+ "scalarlist predicates, found: %v for facet: %v", facetVal, fname) } @@ -137,11 +139,11 @@ func parseMapFacets(m map[string]interface{}, prefix string) ([]map[int]*api.Fac key := fname[len(prefix):] facet, err := handleBasicFacetsType(key, val) if err != nil { - return nil, errors.Wrapf(err, "facet: %s, index: %s", fname, sidx) + return nil, fmt.Errorf("facet: %s, index: %s: %w", fname, sidx, err) } idx, err := strconv.Atoi(sidx) if err != nil { - return nil, errors.Wrapf(err, "facet: %s, index: %s", fname, sidx) + return nil, fmt.Errorf("facet: %s, index: %s: %w", fname, sidx, err) } idxMap[idx] = facet } @@ -171,7 +173,7 @@ func parseScalarFacets(m map[string]interface{}, prefix string) ([]*api.Facet, e key := fname[len(prefix):] facet, err := handleBasicFacetsType(key, facetVal) if err != nil { - return nil, errors.Wrapf(err, "facet: %s", fname) + return nil, fmt.Errorf("facet: %s: %w", fname, err) } facetsForPred = append(facetsForPred, facet) } @@ -228,7 +230,7 @@ func handleBasicType(k string, v interface{}, op int, nq *api.NQuad) error { s := stripSpaces(v) if strings.HasPrefix(s, "uid(") || strings.HasPrefix(s, "val(") { if !strings.HasSuffix(s, ")") { - return errors.Errorf("While processing '%s', brackets are not closed properly", s) + return fmt.Errorf("while processing '%s', brackets are not closed properly", s) } nq.ObjectId = s return nil @@ -254,7 +256,7 @@ func handleBasicType(k string, v interface{}, op int, nq *api.NQuad) error { nq.ObjectValue = &api.Value{Val: &api.Value_BoolVal{BoolVal: v}} default: - return errors.Errorf("Unexpected type for val for attr: %s while converting to nquad", k) + return fmt.Errorf("unexpected type for val for attr: %s while converting to nquad", k) } return nil @@ -278,7 +280,7 @@ func handleGeoType(val map[string]interface{}, nq *api.NQuad) (bool, error) { if len(val) == 2 && hasType && hasCoordinates { b, err := json.Marshal(val) if err != nil { - return false, errors.Errorf("Error while trying to parse value: %+v as geo val", val) + return false, fmt.Errorf("error while trying to parse value: %+v as geo val", val) } ok, err := tryParseAsGeo(b, nq) if err != nil && ok { @@ -300,7 +302,7 @@ func tryParseAsGeo(b []byte, nq *api.NQuad) (bool, error) { geo, err := types.ObjectValue(types.GeoID, g) if err != nil { - return false, errors.Errorf("Couldn't convert value: %s to geo type", string(b)) + return false, fmt.Errorf("couldn't convert value: %s to geo type", string(b)) } nq.ObjectValue = geo @@ -441,8 +443,8 @@ func (buf *NQuadBuffer) mapToNquads(m map[string]interface{}, op int, parentPred if mr.uid == "" { if op == DeleteNquads { - // Delete operations with a non-nil value must have a uid specified. - return mr, errors.Errorf("UID must be present and non-zero while deleting edges.") + // Delete operations with a non-nil value must have an uid specified. + return mr, errEmptyUID } mr.uid = getNextBlank() } @@ -640,11 +642,11 @@ func (buf *NQuadBuffer) mapToNquads(m map[string]interface{}, op int, parentPred buf.Push(&nq) default: return mr, - errors.Errorf("Got unsupported type for list: %s", pred) + fmt.Errorf("got unsupported type for list: %s", pred) } } default: - return mr, errors.Errorf("Unexpected type for val for attr: %s while converting to nquad", pred) + return mr, fmt.Errorf("unexpected type for val for attr: %s while converting to nquad", pred) } } @@ -726,7 +728,7 @@ func (buf *NQuadBuffer) FastParseJSON(b []byte, op int) error { var o interface{} for _, o = range a { if _, ok := o.(map[string]interface{}); !ok { - return errors.Errorf("only array of map allowed at root") + return errors.New("only array of map allowed at root") } // pass to next parsing stage mr, err := buf.mapToNquads(o.(map[string]interface{}), op, "") @@ -738,7 +740,7 @@ func (buf *NQuadBuffer) FastParseJSON(b []byte, op int) error { } } default: - return errors.Errorf("initial element not found in json") + return errors.New("initial element not found in json") } return nil } @@ -767,7 +769,7 @@ func (buf *NQuadBuffer) ParseJSON(b []byte, op int) error { if len(list) > 0 { for _, obj := range list { if _, ok := obj.(map[string]interface{}); !ok { - return errors.Errorf("Only array of map allowed at root.") + return errors.New("only array of map allowed at root") } mr, err := buf.mapToNquads(obj.(map[string]interface{}), op, "") if err != nil { diff --git a/chunker/json_parser_test.go b/chunker/json_parser_test.go index 8fd7a77bcf8..dfc77b2fac9 100644 --- a/chunker/json_parser_test.go +++ b/chunker/json_parser_test.go @@ -971,11 +971,11 @@ func TestNquadsFromJsonError1(t *testing.T) { _, err = Parse(b, DeleteNquads) require.Error(t, err) - require.Contains(t, err.Error(), "UID must be present and non-zero while deleting edges.") + require.ErrorIs(t, err, errEmptyUID) _, err = FastParse(b, DeleteNquads) require.Error(t, err) - require.Contains(t, err.Error(), "UID must be present and non-zero while deleting edges.") + require.ErrorIs(t, err, errEmptyUID) } func TestNquadsFromJsonList(t *testing.T) { diff --git a/chunker/rdf_parser.go b/chunker/rdf_parser.go index 2e329ef0bb3..239b8d41d00 100644 --- a/chunker/rdf_parser.go +++ b/chunker/rdf_parser.go @@ -7,12 +7,12 @@ package chunker import ( "bytes" + "errors" + "fmt" "strconv" "strings" "unicode" - "github.com/pkg/errors" - "github.com/dgraph-io/dgo/v240/protos/api" "github.com/hypermodeinc/dgraph/v24/lex" "github.com/hypermodeinc/dgraph/v24/protos/pb" @@ -50,7 +50,7 @@ func ParseRDFs(b []byte) ([]*api.NQuad, *pb.Metadata, error) { var l lex.Lexer for _, line := range bytes.Split(b, []byte{'\n'}) { nq, err := ParseRDF(string(line), &l) - if err == ErrEmpty { + if errors.Is(err, ErrEmpty) { continue } if err != nil { @@ -126,7 +126,7 @@ L: var err error oval, err = strconv.Unquote(item.Val) if err != nil { - return rnq, errors.Wrapf(err, "while unquoting") + return rnq, fmt.Errorf("while unquoting: %w", err) } seenOval = true @@ -135,21 +135,21 @@ L: case itemObjectType: if rnq.Predicate == x.Star || rnq.Subject == x.Star { - return rnq, errors.Errorf("If predicate/subject is *, value should be * as well") + return rnq, errors.New("if predicate/subject is *, value should be * as well") } val := strings.TrimFunc(item.Val, isSpaceRune) // TODO: Check if this condition is required. if val == "*" { - return rnq, errors.Errorf("itemObject can't be *") + return rnq, errors.New("itemObject can't be *") } // Lets find out the storage type from the type map. t, ok := typeMap[val] if !ok { - return rnq, errors.Errorf("Unrecognized rdf type %s", val) + return rnq, fmt.Errorf("unrecognized rdf type %s", val) } if oval == "" && t != types.StringID { - return rnq, errors.Errorf("Invalid ObjectValue") + return rnq, errors.New("invalid ObjectValue") } src := types.ValueForType(types.StringID) src.Value = []byte(oval) @@ -172,13 +172,13 @@ L: case itemValidEnd: vend = true if !it.Next() { - return rnq, errors.Errorf("Invalid end of input. Input: [%s]", line) + return rnq, fmt.Errorf("invalid end of input. Input: [%s]", line) } // RDF spec says N-Quads should be terminated with a newline. Since we break the input // by newline already. We should get EOF or # after dot(.) item = it.Item() if !(item.Typ == lex.ItemEOF || item.Typ == itemComment) { - return rnq, errors.Errorf("Invalid end of input. Expected newline or # after ."+ + return rnq, fmt.Errorf("invalid end of input. Expected newline or # after ."+ " Input: [%s]", line) } break L @@ -187,20 +187,20 @@ L: s := strings.TrimFunc(item.Val, isSpaceRune) namespace, err := strconv.ParseUint(s, 0, 64) if err != nil { - return rnq, errors.Errorf("Invalid namespace ID. Input: [%s]", line) + return rnq, fmt.Errorf("invalid namespace ID. Input: [%s]", line) } rnq.Namespace = namespace case itemLeftRound: it.Prev() // backup '(' if err := parseFacetsRDF(it, &rnq); err != nil { - return rnq, errors.Wrap(err, "could not parse facet") + return rnq, fmt.Errorf("could not parse facet: %w", err) } } } if !vend { - return rnq, errors.Errorf("Invalid end of input. Input: [%s]", line) + return rnq, fmt.Errorf("invalid end of input. Input: [%s]", line) } if isCommentLine { return rnq, ErrEmpty @@ -211,13 +211,13 @@ L: rnq.ObjectValue = &api.Value{Val: &api.Value_DefaultVal{DefaultVal: oval}} } if len(rnq.Subject) == 0 || len(rnq.Predicate) == 0 { - return rnq, errors.Errorf("Empty required fields in NQuad. Input: [%s]", line) + return rnq, fmt.Errorf("empty required fields in NQuad. Input: [%s]", line) } if len(rnq.ObjectId) == 0 && rnq.ObjectValue == nil { - return rnq, errors.Errorf("No Object in NQuad. Input: [%s]", line) + return rnq, fmt.Errorf("no Object in NQuad. Input: [%s]", line) } if !sane(rnq.Subject) || !sane(rnq.Predicate) || !sane(rnq.ObjectId) { - return rnq, errors.Errorf("NQuad failed sanity check:%+v", rnq) + return rnq, fmt.Errorf("NQuad failed sanity check:%+v", rnq) } return rnq, nil @@ -231,21 +231,21 @@ func parseFunction(it *lex.ItemIterator) (string, error) { it.Next() if item = it.Item(); item.Typ != itemLeftRound { - return "", errors.Errorf("Expected '(', found: %s", item.Val) + return "", fmt.Errorf("expected '(', found: %s", item.Val) } it.Next() if item = it.Item(); item.Typ != itemVarName { - return "", errors.Errorf("Expected variable name, found: %s", item.Val) + return "", fmt.Errorf("expected variable name, found: %s", item.Val) } if strings.TrimSpace(item.Val) == "" { - return "", errors.Errorf("Empty variable name in function call") + return "", errors.New("empty variable name in function call") } s += "(" + item.Val + ")" it.Next() if item = it.Item(); item.Typ != itemRightRound { - return "", errors.Errorf("Expected ')', found: %s", item.Val) + return "", fmt.Errorf("expected ')', found: %s", item.Val) } return s, nil @@ -253,34 +253,34 @@ func parseFunction(it *lex.ItemIterator) (string, error) { func parseFacetsRDF(it *lex.ItemIterator, rnq *api.NQuad) error { if !it.Next() { - return errors.Errorf("Unexpected end of facets.") + return errors.New("unexpected end of facets") } item := it.Item() if item.Typ != itemLeftRound { - return errors.Errorf("Expected '(' but found %v at Facet.", item.Val) + return fmt.Errorf("expected '(' but found %v at facet", item.Val) } for it.Next() { // parse one key value pair // parse key item = it.Item() if item.Typ != itemText { - return errors.Errorf("Expected key but found %v.", item.Val) + return fmt.Errorf("expected key but found %v", item.Val) } facetKey := strings.TrimSpace(item.Val) if len(facetKey) == 0 { - return errors.Errorf("Empty facetKeys not allowed.") + return errors.New("empty facetKeys not allowed") } // parse = if !it.Next() { - return errors.Errorf("Unexpected end of facets.") + return errors.New("unexpected end of facets") } item = it.Item() if item.Typ != itemEqual { - return errors.Errorf("Expected = after facetKey. Found %v", item.Val) + return fmt.Errorf("expected = after facetKey. Found %v", item.Val) } // parse value or empty value if !it.Next() { - return errors.Errorf("Unexpected end of facets.") + return errors.New("unexpected end of facets") } item = it.Item() facetVal := "" @@ -301,11 +301,11 @@ func parseFacetsRDF(it *lex.ItemIterator, rnq *api.NQuad) error { continue } if item.Typ != itemText { - return errors.Errorf("Expected , or ) or text but found %s", item.Val) + return fmt.Errorf("expected , or ) or text but found %s", item.Val) } - // value was present.. + // value was present... if !it.Next() { // get either ')' or ',' - return errors.Errorf("Unexpected end of facets.") + return errors.New("unexpected end of facets") } item = it.Item() if item.Typ == itemRightRound { @@ -314,7 +314,7 @@ func parseFacetsRDF(it *lex.ItemIterator, rnq *api.NQuad) error { if item.Typ == itemComma { continue } - return errors.Errorf("Expected , or ) after facet. Received %s", item.Val) + return fmt.Errorf("expected , or ) after facet. Received %s", item.Val) } return nil