diff --git a/.golangci.yaml b/.golangci.yaml index 6b077f56f27..70731344878 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -11,7 +11,6 @@ linters: - testpackage # TODO: consider enabling the 'testpackage' linter to make sure that separate _test packages are used. - gosec # TODO: consider enabling the 'gosec' linter to inspect source code for security problems. - tagliatelle # TODO: consider enabling the 'tagliatelle' linter to check the struct tags. - - stylecheck # TODO: consider enabling the 'stylecheck' linter to enforce style rules. - thelper # TODO: consider enabling the 'thelper' linter to detect golang test helpers without t.Helper() call and check the consistency of test helpers. - predeclared # TODO: consider enabling the 'predeclared' linter to find code that shadows one of Go's predeclared identifiers. - paralleltest # TODO: consider enabling the 'paralleltest' linter to detect missing usage of t.Parallel() method in Go test. @@ -37,16 +36,13 @@ linters: - contextcheck # TODO: consider enabling the 'contextcheck' linter to check whether the function uses a non-inherited context. - asasalint # TODO: consider enabling the 'asasalint' linter to check for pass []any as any in variadic func(...any). - containedctx # TODO: consider enabling the 'containedctx' linter to detect struct contained context.Context field. - - whitespace # TODO: consider enabling the 'whitespace' linter to detect leading and trailing whitespaces. - unparam # TODO: consider enabling the 'unparam' linter to report unused function parameters. - nakedret # TODO: consider enabling the 'nakedret' linter to find naked returns in functions greater than a specified function length. - - dupword # TODO: consider enabling the 'dupword' linter to check for duplicate words in the source code. - makezero # TODO: consider enabling the 'makezero' linter to find slice declarations with non-zero initial length. - lll # TODO: consider enabling the 'lll' linter to report long lines. - gomoddirectives # TODO: consider enabling the 'gomoddirectives' linter to manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. - gofumpt # TODO: consider enabling the 'gofumpt' linter to check whether code was gofumpt-ed. - godox # TODO: consider enabling the 'godox' linter to detect FIXME, TODO and other comment keywords. - - godot # TODO: consider enabling the 'godot' linter to if comments end in a period. - goconst # TODO: consider enabling the 'goconst' linter to find repeated strings that could be replaced by a constant. - gocognit # TODO: consider enabling the 'gocognit' linter to compute and check the cognitive complexity of functions. - gochecknoinits # TODO: consider enabling the 'gochecknoinits' linter to check that no init functions are present in Go code. @@ -56,7 +52,6 @@ linters: - gocyclo # TODO: consider enabling the 'gocyclo' linter to compute and check the cyclomatic complexity of functions. - forbidigo # TODO: consider enabling the 'forbidigo' linter to forbid identifiers. - dupl # TODO: consider enabling the 'dupl' linter to detect code cloning. - - dogsled # TODO: consider enabling the 'dogsled' linter to check assignments with too many blank identifiers (e.g. x, , , _, := f()). - golint # deprecated since v1.41.0 - replaced by 'revive'. - ifshort # deprecated since v1.48.0 - structcheck # deprecated since v1.49.0 - replaced by 'unused'. diff --git a/changelog/unreleased/enhancement-stylecheck.md b/changelog/unreleased/enhancement-stylecheck.md new file mode 100644 index 00000000000..79bb0397079 --- /dev/null +++ b/changelog/unreleased/enhancement-stylecheck.md @@ -0,0 +1,5 @@ +Enhancement: Enable the style linters + +We've enabled the stylecheck, whitespace, dupword, godot and dogsled linters in golangci-lint and solved the related issues. + +https://github.com/cs3org/reva/pull/3475 \ No newline at end of file diff --git a/cmd/reva/app-tokens-create.go b/cmd/reva/app-tokens-create.go index 64da5ef5306..2a9428f6c68 100644 --- a/cmd/reva/app-tokens-create.go +++ b/cmd/reva/app-tokens-create.go @@ -73,7 +73,6 @@ func appTokensCreateCommand() *command { } cmd.Action = func(w ...io.Writer) error { - createOpts := &appTokenCreateOpts{ Expiration: *expiration, Label: *label, @@ -215,7 +214,7 @@ func getPathScope(ctx context.Context, client gateway.GatewayAPIClient, path, pe return scope.AddResourceInfoScope(statResponse.GetInfo(), role, scopes) } -// parse permission string in the form of "rw" to create a role +// parse permission string in the form of "rw" to create a role. func parsePermission(perm string) (authpb.Role, error) { switch perm { case "r": diff --git a/cmd/reva/app-tokens-list.go b/cmd/reva/app-tokens-list.go index 62605d434fd..d040a7c8182 100644 --- a/cmd/reva/app-tokens-list.go +++ b/cmd/reva/app-tokens-list.go @@ -38,7 +38,6 @@ func appTokensListCommand() *command { cmd.Usage = func() string { return "Usage: token-list" } cmd.Action = func(w ...io.Writer) error { - client, err := getClient() if err != nil { return err diff --git a/cmd/reva/arguments.go b/cmd/reva/arguments.go index b618a159b5c..650fde846d4 100644 --- a/cmd/reva/arguments.go +++ b/cmd/reva/arguments.go @@ -195,7 +195,6 @@ func (c *Completer) shareReceivedArgumentCompleter() []prompt.Suggest { } func executeCommand(cmd *command, args ...string) (bytes.Buffer, error) { - var b bytes.Buffer var err error diff --git a/cmd/reva/command.go b/cmd/reva/command.go index 9757704b17d..30e2c86acc7 100644 --- a/cmd/reva/command.go +++ b/cmd/reva/command.go @@ -24,7 +24,7 @@ import ( "io" ) -// Command is the representation to create commands +// Command is the representation to create commands. type command struct { *flag.FlagSet Name string @@ -34,7 +34,7 @@ type command struct { ResetFlags func() } -// newCommand creates a new command +// newCommand creates a new command. func newCommand(name string) *command { fs := flag.NewFlagSet(name, flag.ExitOnError) cmd := &command{ diff --git a/cmd/reva/completer.go b/cmd/reva/completer.go index 0b0bd906572..a7f82bad676 100644 --- a/cmd/reva/completer.go +++ b/cmd/reva/completer.go @@ -25,7 +25,7 @@ import ( "github.com/c-bata/go-prompt" ) -// Completer provides completion command handler +// Completer provides completion command handler. type Completer struct { Commands []*command DisableArgPrompt bool @@ -45,7 +45,7 @@ func (c *Completer) init() { c.lsDirArguments = new(argumentCompleter) } -// Complete provides completion to prompt +// Complete provides completion to prompt. func (c *Completer) Complete(d prompt.Document) []prompt.Suggest { if d.TextBeforeCursor() == "" { return []prompt.Suggest{} @@ -80,7 +80,6 @@ func (c *Completer) argumentCompleter(args ...string) []prompt.Suggest { } switch args[0] { - case "login": if len(args) == 2 { return prompt.FilterHasPrefix(c.loginArgumentCompleter(), args[1], true) diff --git a/cmd/reva/executor.go b/cmd/reva/executor.go index 90558d00cf8..787c6002972 100644 --- a/cmd/reva/executor.go +++ b/cmd/reva/executor.go @@ -28,12 +28,12 @@ import ( "time" ) -// Executor provides exec command handler +// Executor provides exec command handler. type Executor struct { Timeout int64 } -// Execute provides execute commands +// Execute provides execute commands. func (e *Executor) Execute(s string) { s = strings.TrimSpace(s) switch s { @@ -109,7 +109,7 @@ func executeWithContext(ctx context.Context, cmd *command) error { }() select { case <-ctx.Done(): - return errors.New("Cancelled by user") + return errors.New("cancelled by user") case err := <-c: return err } diff --git a/cmd/reva/grpc.go b/cmd/reva/grpc.go index 74988d9f885..db0d8aedc85 100644 --- a/cmd/reva/grpc.go +++ b/cmd/reva/grpc.go @@ -24,12 +24,11 @@ import ( "fmt" "log" - "google.golang.org/grpc/credentials" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" ctxpkg "github.com/cs3org/reva/pkg/ctx" "google.golang.org/grpc" + "google.golang.org/grpc/credentials" ins "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" ) diff --git a/cmd/reva/main.go b/cmd/reva/main.go index 27e754d70a4..8aa10e74715 100644 --- a/cmd/reva/main.go +++ b/cmd/reva/main.go @@ -115,7 +115,6 @@ func init() { } func main() { - if host != "" { conf = &config{host} if err := writeConfig(conf); err != nil { diff --git a/cmd/reva/upload.go b/cmd/reva/upload.go index 8fb567e5389..86011d92833 100644 --- a/cmd/reva/upload.go +++ b/cmd/reva/upload.go @@ -27,24 +27,23 @@ import ( "path/filepath" "strconv" - "github.com/cs3org/reva/internal/http/services/datagateway" - "github.com/pkg/errors" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/errtypes" - "github.com/eventials/go-tus" - "github.com/eventials/go-tus/memorystore" - "github.com/studio-b12/gowebdav" // TODO(labkode): this should not come from this package. "github.com/cs3org/reva/internal/grpc/services/storageprovider" + "github.com/cs3org/reva/internal/http/services/datagateway" "github.com/cs3org/reva/pkg/crypto" + ctxpkg "github.com/cs3org/reva/pkg/ctx" + "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/rhttp" "github.com/cs3org/reva/pkg/utils" + "github.com/eventials/go-tus" + "github.com/eventials/go-tus/memorystore" + "github.com/pkg/errors" + "github.com/studio-b12/gowebdav" ) func uploadCommand() *command { @@ -292,7 +291,6 @@ func computeXS(t provider.ResourceChecksumType, r io.Reader) (string, error) { return "", nil default: return "", fmt.Errorf("invalid checksum: %s", t) - } } diff --git a/cmd/revad/internal/grace/grace.go b/cmd/revad/internal/grace/grace.go index 339a8c5c1e6..2935a07ee01 100644 --- a/cmd/revad/internal/grace/grace.go +++ b/cmd/revad/internal/grace/grace.go @@ -171,7 +171,7 @@ func (w *Watcher) WritePID() error { // w.log.Info().Msg("error reading pidfile") //} - // If we get here, then the pidfile didn't exist or we are are in graceful reload and thus we overwrite + // If we get here, then the pidfile didn't exist or we are in graceful reload and thus we overwrite // or the pid in it doesn't belong to the user running this app. err := os.WriteFile(w.pidFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0664) if err != nil { @@ -208,7 +208,6 @@ func (w *Watcher) GetListeners(servers map[string]Server) (map[string]net.Listen } else { lns[k] = ln } - } // kill parent @@ -241,7 +240,6 @@ func (w *Watcher) GetListeners(servers map[string]Server) (map[string]net.Listen return nil, err } lns[k] = ln - } w.lns = lns return lns, nil diff --git a/cmd/revad/main.go b/cmd/revad/main.go index 6d0ab9a09d5..ba8022d3a88 100644 --- a/cmd/revad/main.go +++ b/cmd/revad/main.go @@ -32,7 +32,6 @@ import ( "github.com/cs3org/reva/cmd/revad/internal/grace" "github.com/cs3org/reva/cmd/revad/runtime" "github.com/cs3org/reva/pkg/sysinfo" - "github.com/google/uuid" ) @@ -71,7 +70,7 @@ func main() { // the pid flag has been set we abort as the pid flag // is meant to work only with one main configuration. if len(confs) != 1 && *pidFlag != "" { - fmt.Fprintf(os.Stderr, "cannot run with with multiple configurations and one pid file, remote the -p flag\n") + fmt.Fprintf(os.Stderr, "cannot run with multiple configurations and one pid file, remote the -p flag\n") os.Exit(1) } diff --git a/cmd/revad/runtime/loader.go b/cmd/revad/runtime/loader.go index fc917052a9f..ffae933fe70 100644 --- a/cmd/revad/runtime/loader.go +++ b/cmd/revad/runtime/loader.go @@ -19,7 +19,7 @@ package runtime import ( - // These are all the extensions points for REVA + // These are all the extensions points for REVA. _ "github.com/cs3org/reva/internal/grpc/interceptors/loader" _ "github.com/cs3org/reva/internal/grpc/services/loader" _ "github.com/cs3org/reva/internal/http/interceptors/auth/credential/loader" diff --git a/internal/grpc/interceptors/auth/scope.go b/internal/grpc/interceptors/auth/scope.go index 78d481ad36a..3f75e025800 100644 --- a/internal/grpc/interceptors/auth/scope.go +++ b/internal/grpc/interceptors/auth/scope.go @@ -78,11 +78,9 @@ func expandAndVerifyScope(ctx context.Context, req interface{}, tokenScope map[s if err = resolveUserShare(ctx, ref, tokenScope[k], client, mgr); err == nil { return nil } - } log.Err(err).Msgf("error resolving reference %s under scope %+v", ref.String(), k) } - } if checkLightweightScope(ctx, req, tokenScope, client) { @@ -289,7 +287,6 @@ func checkIfNestedResource(ctx context.Context, ref *provider.Reference, parent } return strings.HasPrefix(childPath, parentPath), nil - } func extractRefForReaderRole(req interface{}) (*provider.Reference, bool) { @@ -314,7 +311,6 @@ func extractRefForReaderRole(req interface{}) (*provider.Reference, bool) { } return nil, false - } func extractRefForUploaderRole(req interface{}) (*provider.Reference, bool) { @@ -333,7 +329,6 @@ func extractRefForUploaderRole(req interface{}) (*provider.Reference, bool) { } return nil, false - } func extractRefForEditorRole(req interface{}) (*provider.Reference, bool) { @@ -350,7 +345,6 @@ func extractRefForEditorRole(req interface{}) (*provider.Reference, bool) { } return nil, false - } func extractRef(req interface{}, tokenScope map[string]*authpb.Scope) (*provider.Reference, bool) { diff --git a/internal/grpc/interceptors/eventsmiddleware/conversion.go b/internal/grpc/interceptors/eventsmiddleware/conversion.go index aa1ef2453da..966261a8e69 100644 --- a/internal/grpc/interceptors/eventsmiddleware/conversion.go +++ b/internal/grpc/interceptors/eventsmiddleware/conversion.go @@ -23,7 +23,7 @@ import ( "github.com/cs3org/reva/pkg/events" ) -// ShareCreated converts response to event +// ShareCreated converts response to event. func ShareCreated(r *collaboration.CreateShareResponse) events.ShareCreated { e := events.ShareCreated{ Sharer: r.Share.Creator, diff --git a/internal/grpc/interceptors/eventsmiddleware/events.go b/internal/grpc/interceptors/eventsmiddleware/events.go index 7d8067218de..d3ce9e0f976 100644 --- a/internal/grpc/interceptors/eventsmiddleware/events.go +++ b/internal/grpc/interceptors/eventsmiddleware/events.go @@ -22,14 +22,13 @@ import ( "context" "fmt" - "go-micro.dev/v4/util/log" - "google.golang.org/grpc" - "github.com/asim/go-micro/plugins/events/nats/v4" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" "github.com/cs3org/reva/pkg/events" "github.com/cs3org/reva/pkg/events/server" "github.com/cs3org/reva/pkg/rgrpc" + "go-micro.dev/v4/util/log" + "google.golang.org/grpc" ) const ( diff --git a/internal/grpc/interceptors/loader/loader.go b/internal/grpc/interceptors/loader/loader.go index f0d525f045d..0386fe4ec6c 100644 --- a/internal/grpc/interceptors/loader/loader.go +++ b/internal/grpc/interceptors/loader/loader.go @@ -19,8 +19,8 @@ package loader import ( - // Load core GRPC services + // Load core GRPC services. _ "github.com/cs3org/reva/internal/grpc/interceptors/eventsmiddleware" _ "github.com/cs3org/reva/internal/grpc/interceptors/readonly" - // Add your own service here + // Add your own service here. ) diff --git a/internal/grpc/interceptors/recovery/recovery.go b/internal/grpc/interceptors/recovery/recovery.go index 7ebe0983ae5..5dfbbd00ad2 100644 --- a/internal/grpc/interceptors/recovery/recovery.go +++ b/internal/grpc/interceptors/recovery/recovery.go @@ -20,7 +20,6 @@ package recovery import ( "context" - "runtime/debug" "github.com/cs3org/reva/pkg/appctx" diff --git a/internal/grpc/services/applicationauth/applicationauth.go b/internal/grpc/services/applicationauth/applicationauth.go index cccf72e8e28..712f6f8bb14 100644 --- a/internal/grpc/services/applicationauth/applicationauth.go +++ b/internal/grpc/services/applicationauth/applicationauth.go @@ -72,9 +72,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a app auth provider svc +// New creates a app auth provider svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/appprovider/appprovider.go b/internal/grpc/services/appprovider/appprovider.go index 4daa20b323b..6160603e66d 100644 --- a/internal/grpc/services/appprovider/appprovider.go +++ b/internal/grpc/services/appprovider/appprovider.go @@ -82,7 +82,7 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new AppProviderService +// New creates a new AppProviderService. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c, err := parseConfig(m) if err != nil { diff --git a/internal/grpc/services/appprovider/appprovider_test.go b/internal/grpc/services/appprovider/appprovider_test.go index cb490ec60ea..5f903ca5830 100644 --- a/internal/grpc/services/appprovider/appprovider_test.go +++ b/internal/grpc/services/appprovider/appprovider_test.go @@ -26,7 +26,6 @@ import ( ) func Test_parseConfig(t *testing.T) { - tests := []struct { name string m map[string]interface{} diff --git a/internal/grpc/services/appregistry/appregistry.go b/internal/grpc/services/appregistry/appregistry.go index 4b8c08f6d7b..afa8e909876 100644 --- a/internal/grpc/services/appregistry/appregistry.go +++ b/internal/grpc/services/appregistry/appregistry.go @@ -21,8 +21,6 @@ package appregistry import ( "context" - "google.golang.org/grpc" - registrypb "github.com/cs3org/go-cs3apis/cs3/app/registry/v1beta1" "github.com/cs3org/reva/pkg/app" "github.com/cs3org/reva/pkg/app/registry/registry" @@ -30,6 +28,7 @@ import ( "github.com/cs3org/reva/pkg/rgrpc" "github.com/cs3org/reva/pkg/rgrpc/status" "github.com/mitchellh/mapstructure" + "google.golang.org/grpc" ) func init() { @@ -63,9 +62,8 @@ func (c *config) init() { } } -// New creates a new StorageRegistryService +// New creates a new StorageRegistryService. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/appregistry/appregistry_test.go b/internal/grpc/services/appregistry/appregistry_test.go index 4230a1ffe87..15aedf448ad 100644 --- a/internal/grpc/services/appregistry/appregistry_test.go +++ b/internal/grpc/services/appregistry/appregistry_test.go @@ -324,7 +324,6 @@ func Test_GetAppProviders(t *testing.T) { } func TestNew(t *testing.T) { - tests := []struct { name string m map[string]interface{} diff --git a/internal/grpc/services/authprovider/authprovider.go b/internal/grpc/services/authprovider/authprovider.go index 2fdc5ce4ab5..cf4ec3c1e86 100644 --- a/internal/grpc/services/authprovider/authprovider.go +++ b/internal/grpc/services/authprovider/authprovider.go @@ -170,5 +170,4 @@ func (s *service) Authenticate(ctx context.Context, req *provider.AuthenticateRe Status: status.NewUnauthenticated(ctx, err, "error authenticating user"), }, nil } - } diff --git a/internal/grpc/services/authregistry/authregistry.go b/internal/grpc/services/authregistry/authregistry.go index a449a28be9e..432ea0eaa33 100644 --- a/internal/grpc/services/authregistry/authregistry.go +++ b/internal/grpc/services/authregistry/authregistry.go @@ -65,7 +65,7 @@ func (c *config) init() { } } -// New creates a new AuthRegistry +// New creates a new AuthRegistry. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c, err := parseConfig(m) if err != nil { diff --git a/internal/grpc/services/datatx/datatx.go b/internal/grpc/services/datatx/datatx.go index cb293886be5..a574eb06d2a 100644 --- a/internal/grpc/services/datatx/datatx.go +++ b/internal/grpc/services/datatx/datatx.go @@ -116,9 +116,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new datatx svc +// New creates a new datatx svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/gateway/appprovider.go b/internal/grpc/services/gateway/appprovider.go index 413ad77b90f..b8fdf61b70a 100644 --- a/internal/grpc/services/gateway/appprovider.go +++ b/internal/grpc/services/gateway/appprovider.go @@ -170,7 +170,6 @@ func (s *svc) openFederatedShares(ctx context.Context, targetURL string, vm gate func (s *svc) openLocalResources(ctx context.Context, ri *storageprovider.ResourceInfo, vm gateway.OpenInAppRequest_ViewMode, app string) (*providerpb.OpenInAppResponse, error) { - accessToken, ok := ctxpkg.ContextGetToken(ctx) if !ok || accessToken == "" { return &providerpb.OpenInAppResponse{ @@ -233,7 +232,6 @@ func (s *svc) findAppProvider(ctx context.Context, ri *storageprovider.ResourceI if err != nil { err = errors.Wrap(err, "gateway: error calling GetDefaultAppProviderForMimeType") return nil, err - } // we've found a provider @@ -297,7 +295,6 @@ func (s *svc) findAppProvider(ctx context.Context, ri *storageprovider.ResourceI // we should never arrive to the point of having more than one // provider for the given "app" parameters sent by the user return nil, errtypes.InternalError(fmt.Sprintf("gateway: user requested app %q and we provided %d applications", app, len(res.Providers))) - } func getGRPCConfig(opaque *typespb.Opaque) (bool, bool) { diff --git a/internal/grpc/services/gateway/gateway.go b/internal/grpc/services/gateway/gateway.go index 5108abf5017..61a41a00cd1 100644 --- a/internal/grpc/services/gateway/gateway.go +++ b/internal/grpc/services/gateway/gateway.go @@ -24,9 +24,8 @@ import ( "strings" "time" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" - "github.com/ReneKroon/ttlcache/v2" + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/rgrpc" "github.com/cs3org/reva/pkg/sharedconf" @@ -74,7 +73,7 @@ type config struct { CreateHomeCacheTTL int `mapstructure:"create_home_cache_ttl"` } -// sets defaults +// sets defaults. func (c *config) init() { if c.ShareFolder == "" { c.ShareFolder = "MyShares" diff --git a/internal/grpc/services/gateway/ocmshareprovider.go b/internal/grpc/services/gateway/ocmshareprovider.go index f15bd2eb1f9..76588c340b5 100644 --- a/internal/grpc/services/gateway/ocmshareprovider.go +++ b/internal/grpc/services/gateway/ocmshareprovider.go @@ -451,7 +451,6 @@ func (s *svc) GetReceivedOCMShare(ctx context.Context, req *ocm.GetReceivedOCMSh } func (s *svc) createOCMReference(ctx context.Context, share *ocm.Share) (*rpc.Status, error) { - log := appctx.GetLogger(ctx) var token string diff --git a/internal/grpc/services/gateway/storageprovider.go b/internal/grpc/services/gateway/storageprovider.go index 1fbad971fc3..01accf96e73 100644 --- a/internal/grpc/services/gateway/storageprovider.go +++ b/internal/grpc/services/gateway/storageprovider.go @@ -27,29 +27,26 @@ import ( "sync" "time" - "google.golang.org/protobuf/types/known/fieldmaskpb" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" registry "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - ctxpkg "github.com/cs3org/reva/pkg/ctx" - rtrace "github.com/cs3org/reva/pkg/trace" - "github.com/cs3org/reva/pkg/appctx" + ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/rgrpc/status" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" "github.com/cs3org/reva/pkg/storage/utils/etag" + rtrace "github.com/cs3org/reva/pkg/trace" "github.com/cs3org/reva/pkg/utils" "github.com/golang-jwt/jwt" "github.com/google/uuid" "github.com/pkg/errors" - "google.golang.org/grpc/codes" gstatus "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/fieldmaskpb" ) // transferClaims are custom claims for a JWT token to be used between the metadata and data gateways. @@ -348,7 +345,6 @@ func (s *svc) InitiateFileDownload(ctx context.Context, req *provider.InitiateFi return &gateway.InitiateFileDownloadResponse{ Status: status.NewInvalidArg(ctx, "path points to share folder"), }, nil - } if s.isShareName(ctx, p) { @@ -552,7 +548,6 @@ func (s *svc) InitiateFileUpload(ctx context.Context, req *provider.InitiateFile return &gateway.InitiateFileUploadResponse{ Status: status.NewInvalidArg(ctx, "path points to share folder"), }, nil - } if s.isShareName(ctx, p) { @@ -619,7 +614,6 @@ func (s *svc) InitiateFileUpload(ctx context.Context, req *provider.InitiateFile return &gateway.InitiateFileUploadResponse{ Status: status.NewInvalidArg(ctx, "path points to share name"), }, nil - } if s.isShareChild(ctx, p) { @@ -782,7 +776,6 @@ func (s *svc) CreateContainer(ctx context.Context, req *provider.CreateContainer return &provider.CreateContainerResponse{ Status: status.NewInvalidArg(ctx, "path points to share folder or share name"), }, nil - } if s.isShareChild(ctx, p) { @@ -868,7 +861,7 @@ func (s *svc) TouchFile(ctx context.Context, req *provider.TouchFileRequest) (*p return res, nil } -// check if the path contains the prefix of the shared folder +// check if the path contains the prefix of the shared folder. func (s *svc) inSharedFolder(ctx context.Context, p string) bool { sharedFolder := s.getSharedFolder(ctx) return strings.HasPrefix(p, sharedFolder) @@ -897,7 +890,6 @@ func (s *svc) Delete(ctx context.Context, req *provider.DeleteRequest) (*provide return &provider.DeleteResponse{ Status: status.NewInvalidArg(ctx, "path points to share folder or share name"), }, nil - } if s.isShareName(ctx, p) { @@ -1225,7 +1217,7 @@ func (s *svc) UnsetArbitraryMetadata(ctx context.Context, req *provider.UnsetArb return res, nil } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (s *svc) SetLock(ctx context.Context, req *provider.SetLockRequest) (*provider.SetLockResponse, error) { c, err := s.find(ctx, req.Ref) if err != nil { @@ -1245,7 +1237,7 @@ func (s *svc) SetLock(ctx context.Context, req *provider.SetLockRequest) (*provi return res, nil } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (s *svc) GetLock(ctx context.Context, req *provider.GetLockRequest) (*provider.GetLockResponse, error) { c, err := s.find(ctx, req.Ref) if err != nil { @@ -1265,7 +1257,7 @@ func (s *svc) GetLock(ctx context.Context, req *provider.GetLockRequest) (*provi return res, nil } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (s *svc) RefreshLock(ctx context.Context, req *provider.RefreshLockRequest) (*provider.RefreshLockResponse, error) { c, err := s.find(ctx, req.Ref) if err != nil { @@ -1285,7 +1277,7 @@ func (s *svc) RefreshLock(ctx context.Context, req *provider.RefreshLockRequest) return res, nil } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (s *svc) Unlock(ctx context.Context, req *provider.UnlockRequest) (*provider.UnlockResponse, error) { c, err := s.find(ctx, req.Ref) if err != nil { @@ -1556,7 +1548,6 @@ func (s *svc) Stat(ctx context.Context, req *provider.StatRequest) (*provider.St res.Info = ri res.Info.Path = orgPath return res, nil - } if s.isShareChild(ctx, p) { @@ -1990,7 +1981,6 @@ func (s *svc) ListContainer(ctx context.Context, req *provider.ListContainerRequ } return newRes, nil - } if s.isShareChild(ctx, p) { @@ -2067,14 +2057,12 @@ func (s *svc) ListContainer(ctx context.Context, req *provider.ListContainerRequ } return newRes, nil - } panic("gateway: stating an unknown path:" + p) } func (s *svc) getPath(ctx context.Context, ref *provider.Reference, keys ...string) (string, *rpc.Status) { - // check if it is an id based or combined reference first if ref.ResourceId != nil { req := &provider.StatRequest{Ref: ref, ArbitraryMetadataKeys: keys} @@ -2095,23 +2083,23 @@ func (s *svc) getPath(ctx context.Context, ref *provider.Reference, keys ...stri return "", &rpc.Status{Code: rpc.Code_CODE_INTERNAL} } -// /home/MyShares/ +// /home/MyShares/. func (s *svc) isSharedFolder(ctx context.Context, p string) bool { return s.split(ctx, p, 2) } -// /home/MyShares/photos/ +// /home/MyShares/photos/. func (s *svc) isShareName(ctx context.Context, p string) bool { return s.split(ctx, p, 3) } -// /home/MyShares/photos/Ibiza/beach.png +// /home/MyShares/photos/Ibiza/beach.png. func (s *svc) isShareChild(ctx context.Context, p string) bool { return s.split(ctx, p, 4) } // always validate that the path contains the share folder -// split cannot be called with i<2 +// split cannot be called with i<2. func (s *svc) split(ctx context.Context, p string, i int) bool { log := appctx.GetLogger(ctx) if i < 2 { @@ -2141,7 +2129,7 @@ func (s *svc) split(ctx context.Context, p string, i int) bool { } // path must contain a share path with share children, if not it will panic. -// should be called after checking isShareChild == true +// should be called after checking isShareChild == true. func (s *svc) splitShare(ctx context.Context, p string) (string, string) { parts := s.splitPath(ctx, p) if len(parts) != 4 { @@ -2206,7 +2194,7 @@ func (s *svc) ListRecycleStream(_ *provider.ListRecycleStreamRequest, _ gateway. return errtypes.NotSupported("ListRecycleStream unimplemented") } -// TODO use the ListRecycleRequest.Ref to only list the trash of a specific storage +// TODO use the ListRecycleRequest.Ref to only list the trash of a specific storage. func (s *svc) ListRecycle(ctx context.Context, req *provider.ListRecycleRequest) (*provider.ListRecycleResponse, error) { c, err := s.find(ctx, req.GetRef()) if err != nil { diff --git a/internal/grpc/services/gateway/usershareprovider.go b/internal/grpc/services/gateway/usershareprovider.go index fee83561f09..ba70ada3858 100644 --- a/internal/grpc/services/gateway/usershareprovider.go +++ b/internal/grpc/services/gateway/usershareprovider.go @@ -39,7 +39,6 @@ import ( // TODO(labkode): add multi-phase commit logic when commit share or commit ref is enabled. func (s *svc) CreateShare(ctx context.Context, req *collaboration.CreateShareRequest) (*collaboration.CreateShareResponse, error) { - if s.isSharedFolder(ctx, req.ResourceInfo.GetPath()) { return nil, errtypes.AlreadyExists("gateway: can't share the share folder itself") } diff --git a/internal/grpc/services/helloworld/helloworld.go b/internal/grpc/services/helloworld/helloworld.go index 1f8bac38150..ad34fda3f1a 100644 --- a/internal/grpc/services/helloworld/helloworld.go +++ b/internal/grpc/services/helloworld/helloworld.go @@ -42,7 +42,7 @@ type service struct { // New returns a new PreferencesServiceServer // It can be tested like this: -// prototool grpc --address 0.0.0.0:9999 --method 'revad.helloworld.HelloWorldService/Hello' --data '{"name": "Alice"}' +// prototool grpc --address 0.0.0.0:9999 --method 'revad.helloworld.HelloWorldService/Hello' --data '{"name": "Alice"}'. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c := &conf{} if err := mapstructure.Decode(m, c); err != nil { diff --git a/internal/grpc/services/loader/loader.go b/internal/grpc/services/loader/loader.go index e0161997d24..8714e1ea90f 100644 --- a/internal/grpc/services/loader/loader.go +++ b/internal/grpc/services/loader/loader.go @@ -41,5 +41,5 @@ import ( _ "github.com/cs3org/reva/internal/grpc/services/storageregistry" _ "github.com/cs3org/reva/internal/grpc/services/userprovider" _ "github.com/cs3org/reva/internal/grpc/services/usershareprovider" - // Add your own service here + // Add your own service here. ) diff --git a/internal/grpc/services/ocmcore/ocmcore.go b/internal/grpc/services/ocmcore/ocmcore.go index 2f2dcf615f0..575b6336b7b 100644 --- a/internal/grpc/services/ocmcore/ocmcore.go +++ b/internal/grpc/services/ocmcore/ocmcore.go @@ -77,9 +77,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new ocm core svc +// New creates a new ocm core svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err @@ -107,7 +106,7 @@ func (s *service) UnprotectedEndpoints() []string { return []string{"/cs3.ocm.core.v1beta1.OcmCoreAPI/CreateOCMCoreShare"} } -// CreateOCMCoreShare is called when an OCM request comes into this reva instance from +// CreateOCMCoreShare is called when an OCM request comes into this reva instance from. func (s *service) CreateOCMCoreShare(ctx context.Context, req *ocmcore.CreateOCMCoreShareRequest) (*ocmcore.CreateOCMCoreShareResponse, error) { resource := &provider.ResourceId{ StorageId: "remote", diff --git a/internal/grpc/services/ocminvitemanager/ocminvitemanager.go b/internal/grpc/services/ocminvitemanager/ocminvitemanager.go index 6821f7d29e9..2ab9bb653a9 100644 --- a/internal/grpc/services/ocminvitemanager/ocminvitemanager.go +++ b/internal/grpc/services/ocminvitemanager/ocminvitemanager.go @@ -72,9 +72,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new OCM invite manager svc +// New creates a new OCM invite manager svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go b/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go index 8d89fccdd12..3a70d3dc791 100644 --- a/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go +++ b/internal/grpc/services/ocmproviderauthorizer/ocmproviderauthorizer.go @@ -72,9 +72,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new OCM provider authorizer svc +// New creates a new OCM provider authorizer svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/ocmshareprovider/ocmshareprovider.go b/internal/grpc/services/ocmshareprovider/ocmshareprovider.go index 2cf80c15f39..e70a6b8c557 100644 --- a/internal/grpc/services/ocmshareprovider/ocmshareprovider.go +++ b/internal/grpc/services/ocmshareprovider/ocmshareprovider.go @@ -72,9 +72,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new ocm share provider svc +// New creates a new ocm share provider svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err @@ -114,7 +113,7 @@ func (s *service) UnprotectedEndpoints() []string { // internal/grpc/service/ocmcore/ocmcore.go // Both functions end up calling the same s.sm.Share function // on the OCM share manager: -// pkg/ocm/share/manager/{json|nextcloud|...} +// pkg/ocm/share/manager/{json|nextcloud|...}. func (s *service) CreateOCMShare(ctx context.Context, req *ocm.CreateOCMShareRequest) (*ocm.CreateOCMShareResponse, error) { if req.Opaque == nil { return &ocm.CreateOCMShareResponse{ diff --git a/internal/grpc/services/permissions/permissions.go b/internal/grpc/services/permissions/permissions.go index 4479fdb88c6..d8bdfc93651 100644 --- a/internal/grpc/services/permissions/permissions.go +++ b/internal/grpc/services/permissions/permissions.go @@ -54,7 +54,7 @@ type service struct { manager permission.Manager } -// New returns a new PermissionsServiceServer +// New returns a new PermissionsServiceServer. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c, err := parseConfig(m) if err != nil { diff --git a/internal/grpc/services/preferences/preferences.go b/internal/grpc/services/preferences/preferences.go index 6920fc70699..c42e8856bbd 100644 --- a/internal/grpc/services/preferences/preferences.go +++ b/internal/grpc/services/preferences/preferences.go @@ -21,8 +21,6 @@ package preferences import ( "context" - "google.golang.org/grpc" - preferencespb "github.com/cs3org/go-cs3apis/cs3/preferences/v1beta1" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/preferences" @@ -31,6 +29,7 @@ import ( "github.com/cs3org/reva/pkg/rgrpc/status" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" + "google.golang.org/grpc" ) func init() { @@ -69,7 +68,7 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New returns a new PreferencesServiceServer +// New returns a new PreferencesServiceServer. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c, err := parseConfig(m) if err != nil { diff --git a/internal/grpc/services/publicshareprovider/publicshareprovider.go b/internal/grpc/services/publicshareprovider/publicshareprovider.go index b43a2bf22e7..7cfd191d18a 100644 --- a/internal/grpc/services/publicshareprovider/publicshareprovider.go +++ b/internal/grpc/services/publicshareprovider/publicshareprovider.go @@ -86,9 +86,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new user share provider svc +// New creates a new user share provider svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/grpc/services/publicstorageprovider/publicstorageprovider.go b/internal/grpc/services/publicstorageprovider/publicstorageprovider.go index 13c3d779690..6a3b38f970a 100644 --- a/internal/grpc/services/publicstorageprovider/publicstorageprovider.go +++ b/internal/grpc/services/publicstorageprovider/publicstorageprovider.go @@ -124,22 +124,22 @@ func (s *service) UnsetArbitraryMetadata(ctx context.Context, req *provider.Unse return nil, gstatus.Errorf(codes.Unimplemented, "method not implemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (s *service) SetLock(ctx context.Context, req *provider.SetLockRequest) (*provider.SetLockResponse, error) { return nil, gstatus.Errorf(codes.Unimplemented, "method not implemented") } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (s *service) GetLock(ctx context.Context, req *provider.GetLockRequest) (*provider.GetLockResponse, error) { return nil, gstatus.Errorf(codes.Unimplemented, "method not implemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (s *service) RefreshLock(ctx context.Context, req *provider.RefreshLockRequest) (*provider.RefreshLockResponse, error) { return nil, gstatus.Errorf(codes.Unimplemented, "method not implemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (s *service) Unlock(ctx context.Context, req *provider.UnlockRequest) (*provider.UnlockResponse, error) { return nil, gstatus.Errorf(codes.Unimplemented, "method not implemented") } diff --git a/internal/grpc/services/storageprovider/storageprovider.go b/internal/grpc/services/storageprovider/storageprovider.go index ad47edbbcb6..423f17a4f66 100644 --- a/internal/grpc/services/storageprovider/storageprovider.go +++ b/internal/grpc/services/storageprovider/storageprovider.go @@ -160,9 +160,8 @@ func registerMimeTypes(mappingFile string) error { return nil } -// New creates a new storage provider svc +// New creates a new storage provider svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err @@ -277,7 +276,7 @@ func (s *service) UnsetArbitraryMetadata(ctx context.Context, req *provider.Unse return res, nil } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (s *service) SetLock(ctx context.Context, req *provider.SetLockRequest) (*provider.SetLockResponse, error) { newRef, err := s.unwrap(ctx, req.Ref) if err != nil { @@ -310,7 +309,7 @@ func (s *service) SetLock(ctx context.Context, req *provider.SetLockRequest) (*p return res, nil } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (s *service) GetLock(ctx context.Context, req *provider.GetLockRequest) (*provider.GetLockResponse, error) { newRef, err := s.unwrap(ctx, req.Ref) if err != nil { @@ -343,7 +342,7 @@ func (s *service) GetLock(ctx context.Context, req *provider.GetLockRequest) (*p return res, nil } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (s *service) RefreshLock(ctx context.Context, req *provider.RefreshLockRequest) (*provider.RefreshLockResponse, error) { newRef, err := s.unwrap(ctx, req.Ref) if err != nil { @@ -376,7 +375,7 @@ func (s *service) RefreshLock(ctx context.Context, req *provider.RefreshLockRequ return res, nil } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (s *service) Unlock(ctx context.Context, req *provider.UnlockRequest) (*provider.UnlockResponse, error) { newRef, err := s.unwrap(ctx, req.Ref) if err != nil { @@ -579,7 +578,7 @@ func (s *service) CreateHome(ctx context.Context, req *provider.CreateHomeReques return res, nil } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (s *service) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { resp, err := s.storage.CreateStorageSpace(ctx, req) if err != nil { diff --git a/internal/grpc/services/storageprovider/transcoder.go b/internal/grpc/services/storageprovider/transcoder.go index 4fa6cc52ba0..84dac65b36e 100644 --- a/internal/grpc/services/storageprovider/transcoder.go +++ b/internal/grpc/services/storageprovider/transcoder.go @@ -32,11 +32,11 @@ const ( XSInvalid XS = "invalid" // XSUnset means the checksum is optional. XSUnset = "unset" - // XSAdler32 means the checksum is adler32 + // XSAdler32 means the checksum is adler32. XSAdler32 = "adler32" - // XSMD5 means the checksum is md5 + // XSMD5 means the checksum is md5. XSMD5 = "md5" - // XSSHA1 means the checksum is SHA1 + // XSSHA1 means the checksum is SHA1. XSSHA1 = "sha1" // XSSHA256 means the checksum is SHA256. XSSHA256 = "sha256" diff --git a/internal/grpc/services/storageregistry/storageregistry.go b/internal/grpc/services/storageregistry/storageregistry.go index 4f59ae56496..fa74dc216d9 100644 --- a/internal/grpc/services/storageregistry/storageregistry.go +++ b/internal/grpc/services/storageregistry/storageregistry.go @@ -63,7 +63,7 @@ func (c *config) init() { } } -// New creates a new StorageBrokerService +// New creates a new StorageBrokerService. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { c, err := parseConfig(m) if err != nil { diff --git a/internal/grpc/services/usershareprovider/usershareprovider.go b/internal/grpc/services/usershareprovider/usershareprovider.go index 372020704ff..b69a2778dc4 100644 --- a/internal/grpc/services/usershareprovider/usershareprovider.go +++ b/internal/grpc/services/usershareprovider/usershareprovider.go @@ -88,9 +88,8 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New creates a new user share provider svc +// New creates a new user share provider svc. func New(m map[string]interface{}, ss *grpc.Server) (rgrpc.Service, error) { - c, err := parseConfig(m) if err != nil { return nil, err diff --git a/internal/http/interceptors/appctx/appctx.go b/internal/http/interceptors/appctx/appctx.go index 9d34a789819..04ac9810d5a 100644 --- a/internal/http/interceptors/appctx/appctx.go +++ b/internal/http/interceptors/appctx/appctx.go @@ -40,7 +40,6 @@ func New(log zerolog.Logger) func(http.Handler) http.Handler { } func handler(log zerolog.Logger, h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() span := trace.SpanFromContext(ctx) diff --git a/internal/http/interceptors/auth/auth.go b/internal/http/interceptors/auth/auth.go index cca7cc4e179..8d7bd9b002a 100644 --- a/internal/http/interceptors/auth/auth.go +++ b/internal/http/interceptors/auth/auth.go @@ -362,7 +362,6 @@ func getCredsForUserAgent(ua string, uam map[string]string, creds []string) []st } } return creds - } } diff --git a/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go b/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go index 713aa463965..87817939df8 100644 --- a/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go +++ b/internal/http/interceptors/auth/credential/strategy/bearer/bearer.go @@ -54,7 +54,6 @@ func (s *strategy) GetCredentials(w http.ResponseWriter, r *http.Request) (*auth return nil, fmt.Errorf("no bearer auth provided") } return &auth.Credentials{Type: "bearer", ClientSecret: tokens[0]}, nil - } func (s *strategy) AddWWWAuthenticate(w http.ResponseWriter, r *http.Request, realm string) { diff --git a/internal/http/interceptors/auth/credential/strategy/publicshares/publicshares.go b/internal/http/interceptors/auth/credential/strategy/publicshares/publicshares.go index e39289dfd08..4da411696cb 100644 --- a/internal/http/interceptors/auth/credential/strategy/publicshares/publicshares.go +++ b/internal/http/interceptors/auth/credential/strategy/publicshares/publicshares.go @@ -37,7 +37,7 @@ const ( type strategy struct{} -// New returns a new auth strategy that handles public share verification +// New returns a new auth strategy that handles public share verification. func New(m map[string]interface{}) (auth.CredentialStrategy, error) { return &strategy{}, nil } diff --git a/internal/http/interceptors/log/log.go b/internal/http/interceptors/log/log.go index 9e587c59bc9..035af653e56 100644 --- a/internal/http/interceptors/log/log.go +++ b/internal/http/interceptors/log/log.go @@ -36,7 +36,7 @@ func New() func(http.Handler) http.Handler { return handler } -// handler is a logging middleware +// handler is a logging middleware. func handler(h http.Handler) http.Handler { return newLoggingHandler(h) } @@ -129,7 +129,7 @@ type commonLoggingResponseWriter interface { } // responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP -// status code and body size +// status code and body size. type responseLogger struct { w http.ResponseWriter status int diff --git a/internal/http/interceptors/providerauthorizer/providerauthorizer.go b/internal/http/interceptors/providerauthorizer/providerauthorizer.go index 76ac951f802..b85f3a65e83 100644 --- a/internal/http/interceptors/providerauthorizer/providerauthorizer.go +++ b/internal/http/interceptors/providerauthorizer/providerauthorizer.go @@ -56,7 +56,6 @@ func getDriver(c *config) (provider.Authorizer, error) { // New returns a new HTTP middleware that verifies that the provider is registered in OCM. func New(m map[string]interface{}, unprotected []string, ocmPrefix string) (global.Middleware, error) { - if ocmPrefix == "" { ocmPrefix = "ocm" } @@ -74,7 +73,6 @@ func New(m map[string]interface{}, unprotected []string, ocmPrefix string) (glob handler := func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() log := appctx.GetLogger(ctx) head, _ := router.ShiftPath(r.URL.Path) @@ -110,5 +108,4 @@ func New(m map[string]interface{}, unprotected []string, ocmPrefix string) (glob } return handler, nil - } diff --git a/internal/http/services/appprovider/appprovider.go b/internal/http/services/appprovider/appprovider.go index 7cf0e79fab2..2c8c8f94663 100644 --- a/internal/http/services/appprovider/appprovider.go +++ b/internal/http/services/appprovider/appprovider.go @@ -47,7 +47,7 @@ func init() { global.Register("appprovider", New) } -// Config holds the config options for the HTTP appprovider service +// Config holds the config options for the HTTP appprovider service. type Config struct { Prefix string `mapstructure:"prefix"` GatewaySvc string `mapstructure:"gatewaysvc"` @@ -66,9 +66,8 @@ type svc struct { router *chi.Mux } -// New returns a new ocmd object +// New returns a new ocmd object. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { - conf := &Config{} if err := mapstructure.Decode(m, conf); err != nil { return nil, err diff --git a/internal/http/services/appprovider/errors.go b/internal/http/services/appprovider/errors.go index 353925423df..306850e3379 100644 --- a/internal/http/services/appprovider/errors.go +++ b/internal/http/services/appprovider/errors.go @@ -25,7 +25,7 @@ import ( "github.com/cs3org/reva/pkg/appctx" ) -// appErrorCode stores the type of error encountered +// appErrorCode stores the type of error encountered. type appErrorCode string const ( @@ -37,7 +37,7 @@ const ( appErrorServerError appErrorCode = "SERVER_ERROR" ) -// appErrorCodeMapping stores the HTTP error code mapping for various APIErrorCodes +// appErrorCodeMapping stores the HTTP error code mapping for various APIErrorCodes. var appErrorCodeMapping = map[appErrorCode]int{ appErrorNotFound: http.StatusNotFound, appErrorAlreadyExists: http.StatusForbidden, @@ -47,13 +47,13 @@ var appErrorCodeMapping = map[appErrorCode]int{ appErrorServerError: http.StatusInternalServerError, } -// APIError encompasses the error type and message +// APIError encompasses the error type and message. type appError struct { Code appErrorCode `json:"code"` Message string `json:"message"` } -// writeError handles writing error responses +// writeError handles writing error responses. func writeError(w http.ResponseWriter, r *http.Request, code appErrorCode, message string, err error) { if err != nil { appctx.GetLogger(r.Context()).Error().Err(err).Msg(message) diff --git a/internal/http/services/archiver/handler.go b/internal/http/services/archiver/handler.go index bbfe4e8642a..01838c463ba 100644 --- a/internal/http/services/archiver/handler.go +++ b/internal/http/services/archiver/handler.go @@ -23,14 +23,12 @@ import ( "errors" "fmt" "net/http" + "regexp" "time" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - - "regexp" - "github.com/cs3org/reva/internal/http/services/archiver/manager" "github.com/cs3org/reva/pkg/appctx" "github.com/cs3org/reva/pkg/errtypes" @@ -57,7 +55,7 @@ type svc struct { allowedFolders []*regexp.Regexp } -// Config holds the config options that need to be passed down to all ocdav handlers +// Config holds the config options that need to be passed down to all ocdav handlers. type Config struct { Prefix string `mapstructure:"prefix"` GatewaySvc string `mapstructure:"gatewaysvc"` @@ -73,7 +71,7 @@ func init() { global.Register("archiver", New) } -// New creates a new archiver service +// New creates a new archiver service. func New(conf map[string]interface{}, log *zerolog.Logger) (global.Service, error) { c := &Config{} err := mapstructure.Decode(conf, c) @@ -151,7 +149,6 @@ func (s *svc) getFiles(ctx context.Context, files, ids []string) ([]string, erro } f = append(f, resp.Info.Path) - } f = append(f, files...) @@ -165,7 +162,7 @@ func (s *svc) getFiles(ctx context.Context, files, ids []string) ([]string, erro return f, nil } -// return true if path match with at least with one allowed folder regex +// return true if path match with at least with one allowed folder regex. func (s *svc) isPathAllowed(path string) bool { for _, reg := range s.allowedFolders { if reg.MatchString(path) { @@ -175,7 +172,7 @@ func (s *svc) isPathAllowed(path string) bool { return false } -// return nil if all the paths in the slide match with at least one allowed folder regex +// return nil if all the paths in the slide match with at least one allowed folder regex. func (s *svc) allAllowed(paths []string) error { if len(s.allowedFolders) == 0 { return nil @@ -262,7 +259,6 @@ func (s *svc) Handler() http.Handler { s.writeHTTPError(rw, err) return } - }) } diff --git a/internal/http/services/archiver/manager/archiver.go b/internal/http/services/archiver/manager/archiver.go index 7c90b6a459b..e53035e129f 100644 --- a/internal/http/services/archiver/manager/archiver.go +++ b/internal/http/services/archiver/manager/archiver.go @@ -32,13 +32,13 @@ import ( "github.com/cs3org/reva/pkg/storage/utils/walker" ) -// Config is the config for the Archiver +// Config is the config for the Archiver. type Config struct { MaxNumFiles int64 MaxSize int64 } -// Archiver is the struct able to create an archive +// Archiver is the struct able to create an archive. type Archiver struct { files []string dir string @@ -47,7 +47,7 @@ type Archiver struct { config Config } -// NewArchiver creates a new archiver able to create an archive containing the files in the list +// NewArchiver creates a new archiver able to create an archive containing the files in the list. func NewArchiver(files []string, w walker.Walker, d downloader.Downloader, config Config) (*Archiver, error) { if len(files) == 0 { return nil, ErrEmptyList{} @@ -68,7 +68,7 @@ func NewArchiver(files []string, w walker.Walker, d downloader.Downloader, confi return arc, nil } -// pathIn verifies that the path `f`is in the `files`list +// pathIn verifies that the path `f`is in the `files`list. func pathIn(files []string, f string) bool { f = filepath.Clean(f) for _, file := range files { @@ -80,7 +80,6 @@ func pathIn(files []string, f string) bool { } func getDeepestCommonDir(files []string) string { - if len(files) == 0 { return "" } @@ -100,7 +99,6 @@ func getDeepestCommonDir(files []string) string { res = res[:i] } } - } // the common substring could be between two / - inside a file name @@ -113,14 +111,13 @@ func getDeepestCommonDir(files []string) string { return filepath.Clean(res) } -// CreateTar creates a tar and write it into the dst Writer +// CreateTar creates a tar and write it into the dst Writer. func (a *Archiver) CreateTar(ctx context.Context, dst io.Writer) error { w := tar.NewWriter(dst) var filesCount, sizeFiles int64 for _, root := range a.files { - err := a.walker.Walk(ctx, root, func(path string, info *provider.ResourceInfo, err error) error { if err != nil { return err @@ -182,19 +179,17 @@ func (a *Archiver) CreateTar(ctx context.Context, dst io.Writer) error { if err != nil { return err } - } return w.Close() } -// CreateZip creates a zip and write it into the dst Writer +// CreateZip creates a zip and write it into the dst Writer. func (a *Archiver) CreateZip(ctx context.Context, dst io.Writer) error { w := zip.NewWriter(dst) var filesCount, sizeFiles int64 for _, root := range a.files { - err := a.walker.Walk(ctx, root, func(path string, info *provider.ResourceInfo, err error) error { if err != nil { return err @@ -255,7 +250,6 @@ func (a *Archiver) CreateZip(ctx context.Context, dst io.Writer) error { if err != nil { return err } - } return w.Close() } diff --git a/internal/http/services/archiver/manager/archiver_test.go b/internal/http/services/archiver/manager/archiver_test.go index fd102c55490..ca4c7eff062 100644 --- a/internal/http/services/archiver/manager/archiver_test.go +++ b/internal/http/services/archiver/manager/archiver_test.go @@ -95,14 +95,11 @@ func TestGetDeepestCommonDir(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - res := getDeepestCommonDir(tt.paths) if res != tt.expected { t.Fatalf("getDeepestCommondDir() failed: paths=%+v expected=%s got=%s", tt.paths, tt.expected, res) } - }) - } } @@ -147,7 +144,6 @@ func UnTar(dir string, r io.Reader) error { } func TestCreateTar(t *testing.T) { - tests := []struct { name string src test.Dir @@ -471,9 +467,7 @@ func TestCreateTar(t *testing.T) { } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() tmpdir, cleanup, err := test.NewTestDir(tt.src) @@ -523,11 +517,8 @@ func TestCreateTar(t *testing.T) { t.Fatalf("untar dir different from expected") } } - }) - } - } func UnZip(dir string, r io.Reader) error { @@ -558,7 +549,6 @@ func UnZip(dir string, r io.Reader) error { defer zr.Close() for _, f := range zr.File { - p := path.Join(dir, f.Name) d := path.Dir(p) @@ -595,7 +585,6 @@ func UnZip(dir string, r io.Reader) error { } func TestCreateZip(t *testing.T) { - tests := []struct { name string src test.Dir @@ -919,9 +908,7 @@ func TestCreateZip(t *testing.T) { } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() tmpdir, cleanup, err := test.NewTestDir(tt.src) @@ -971,9 +958,6 @@ func TestCreateZip(t *testing.T) { t.Fatalf("unzip dir different from expected") } } - }) - } - } diff --git a/internal/http/services/archiver/manager/errors.go b/internal/http/services/archiver/manager/errors.go index 178e76b25d1..78bfc91c50f 100644 --- a/internal/http/services/archiver/manager/errors.go +++ b/internal/http/services/archiver/manager/errors.go @@ -18,26 +18,26 @@ package manager -// ErrMaxFileCount is the error returned when the max files count specified in the config has reached +// ErrMaxFileCount is the error returned when the max files count specified in the config has reached. type ErrMaxFileCount struct{} -// ErrMaxSize is the error returned when the max total files size specified in the config has reached +// ErrMaxSize is the error returned when the max total files size specified in the config has reached. type ErrMaxSize struct{} -// ErrEmptyList is the error returned when an empty list is passed when an archiver is created +// ErrEmptyList is the error returned when an empty list is passed when an archiver is created. type ErrEmptyList struct{} -// Error returns the string error msg for ErrMaxFileCount +// Error returns the string error msg for ErrMaxFileCount. func (ErrMaxFileCount) Error() string { return "reached max files count" } -// Error returns the string error msg for ErrMaxSize +// Error returns the string error msg for ErrMaxSize. func (ErrMaxSize) Error() string { return "reached max total files size" } -// Error returns the string error msg for ErrEmptyList +// Error returns the string error msg for ErrEmptyList. func (ErrEmptyList) Error() string { return "list of files to archive empty" } diff --git a/internal/http/services/datagateway/datagateway.go b/internal/http/services/datagateway/datagateway.go index 65d201e801c..c66dd5803eb 100644 --- a/internal/http/services/datagateway/datagateway.go +++ b/internal/http/services/datagateway/datagateway.go @@ -39,7 +39,7 @@ import ( ) const ( - // TokenTransportHeader holds the header key for the reva transfer token + // TokenTransportHeader holds the header key for the reva transfer token. TokenTransportHeader = "X-Reva-Transfer" // UploadExpiresHeader holds the timestamp for the transport token expiry, defined in https://tus.io/protocols/resumable-upload.html#expiration UploadExpiresHeader = "Upload-Expires" @@ -75,7 +75,7 @@ type svc struct { client *http.Client } -// New returns a new datagateway +// New returns a new datagateway. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/dataprovider/dataprovider.go b/internal/http/services/dataprovider/dataprovider.go index a149e7118db..e07863032df 100644 --- a/internal/http/services/dataprovider/dataprovider.go +++ b/internal/http/services/dataprovider/dataprovider.go @@ -61,7 +61,7 @@ type svc struct { dataTXs map[string]http.Handler } -// New returns a new datasvc +// New returns a new datasvc. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { @@ -139,7 +139,6 @@ func (s *svc) Handler() http.Handler { } func (s *svc) setHandler() error { - s.handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log := appctx.GetLogger(r.Context()) log.Debug().Msgf("dataprovider routing: path=%s", r.URL.Path) diff --git a/internal/http/services/helloworld/helloworld.go b/internal/http/services/helloworld/helloworld.go index f194b346028..6f09e2e3eb3 100644 --- a/internal/http/services/helloworld/helloworld.go +++ b/internal/http/services/helloworld/helloworld.go @@ -31,7 +31,7 @@ func init() { global.Register("helloworld", New) } -// New returns a new helloworld service +// New returns a new helloworld service. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/loader/loader.go b/internal/http/services/loader/loader.go index 40d78b583e4..47add60ad43 100644 --- a/internal/http/services/loader/loader.go +++ b/internal/http/services/loader/loader.go @@ -19,7 +19,7 @@ package loader import ( - // Load core HTTP services + // Load core HTTP services. _ "github.com/cs3org/reva/internal/http/services/appprovider" _ "github.com/cs3org/reva/internal/http/services/archiver" _ "github.com/cs3org/reva/internal/http/services/datagateway" @@ -38,5 +38,5 @@ import ( _ "github.com/cs3org/reva/internal/http/services/siteacc" _ "github.com/cs3org/reva/internal/http/services/sysinfo" _ "github.com/cs3org/reva/internal/http/services/wellknown" - // Add your own service here + // Add your own service here. ) diff --git a/internal/http/services/mailer/mailer.go b/internal/http/services/mailer/mailer.go index 3f47a5f64df..3888cf883b1 100644 --- a/internal/http/services/mailer/mailer.go +++ b/internal/http/services/mailer/mailer.go @@ -68,7 +68,7 @@ type svc struct { tplSubj *template.Template } -// New creates a new mailer service +// New creates a new mailer service. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/mentix/mentix.go b/internal/http/services/mentix/mentix.go index af9adb90ed9..d6dd998b526 100644 --- a/internal/http/services/mentix/mentix.go +++ b/internal/http/services/mentix/mentix.go @@ -21,15 +21,14 @@ package mentix import ( "net/http" - "github.com/cs3org/reva/pkg/mentix/meshdata" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix" "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers" + "github.com/cs3org/reva/pkg/mentix/meshdata" "github.com/cs3org/reva/pkg/rhttp/global" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" + "github.com/rs/zerolog" ) func init() { diff --git a/internal/http/services/meshdirectory/meshdirectory.go b/internal/http/services/meshdirectory/meshdirectory.go index dba4c3d79b3..183a2cb2c72 100644 --- a/internal/http/services/meshdirectory/meshdirectory.go +++ b/internal/http/services/meshdirectory/meshdirectory.go @@ -23,20 +23,17 @@ import ( "fmt" "net/http" - meshdirectoryweb "github.com/sciencemesh/meshdirectory-web" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" - "github.com/cs3org/reva/internal/http/services/ocmd" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" + "github.com/cs3org/reva/pkg/rhttp/global" "github.com/cs3org/reva/pkg/rhttp/router" "github.com/cs3org/reva/pkg/sharedconf" + "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "github.com/rs/zerolog" - - "github.com/cs3org/reva/pkg/rhttp/global" - "github.com/mitchellh/mapstructure" + meshdirectoryweb "github.com/sciencemesh/meshdirectory-web" ) func init() { @@ -69,7 +66,7 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New returns a new Mesh Directory HTTP service +// New returns a new Mesh Directory HTTP service. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { c, err := parseConfig(m) if err != nil { @@ -84,12 +81,12 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) return service, nil } -// Service prefix +// Service prefix. func (s *svc) Prefix() string { return s.conf.Prefix } -// Unprotected endpoints +// Unprotected endpoints. func (s *svc) Unprotected() []string { return []string{"/"} } @@ -137,7 +134,7 @@ func (s *svc) serveJSON(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// HTTP service handler +// HTTP service handler. func (s *svc) Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var head string diff --git a/internal/http/services/metrics/metrics.go b/internal/http/services/metrics/metrics.go index 7fee35c6c49..9bea289c364 100644 --- a/internal/http/services/metrics/metrics.go +++ b/internal/http/services/metrics/metrics.go @@ -26,12 +26,11 @@ import ( "os" "github.com/cs3org/reva/pkg/logger" - "github.com/mitchellh/mapstructure" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/metrics" "github.com/cs3org/reva/pkg/metrics/config" "github.com/cs3org/reva/pkg/rhttp/global" + "github.com/mitchellh/mapstructure" + "github.com/rs/zerolog" ) func init() { diff --git a/internal/http/services/ocmd/config.go b/internal/http/services/ocmd/config.go index 79364d890ba..f7f05084201 100644 --- a/internal/http/services/ocmd/config.go +++ b/internal/http/services/ocmd/config.go @@ -85,6 +85,5 @@ func (h *configHandler) Handler() http.Handler { if _, err := w.Write(indentedConf); err != nil { log.Err(err).Msg("Error writing to ResponseWriter") } - }) } diff --git a/internal/http/services/ocmd/invites.go b/internal/http/services/ocmd/invites.go index 9f6d27bc077..32cd4048505 100644 --- a/internal/http/services/ocmd/invites.go +++ b/internal/http/services/ocmd/invites.go @@ -79,7 +79,6 @@ func (h *invitesHandler) Handler() http.Handler { } func (h *invitesHandler) generateInviteToken(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() gatewayClient, err := pool.GetGatewayServiceClient(pool.Endpoint(h.gatewayAddr)) @@ -95,7 +94,6 @@ func (h *invitesHandler) generateInviteToken(w http.ResponseWriter, r *http.Requ } if r.FormValue("recipient") != "" && h.smtpCredentials != nil { - usr := ctxpkg.ContextMustGetUser(ctx) // TODO: the message body needs to point to the meshdirectory service diff --git a/internal/http/services/ocmd/ocmd.go b/internal/http/services/ocmd/ocmd.go index c65cec5d67b..b2f23d02ef8 100644 --- a/internal/http/services/ocmd/ocmd.go +++ b/internal/http/services/ocmd/ocmd.go @@ -34,7 +34,7 @@ func init() { global.Register("ocmd", New) } -// Config holds the config options that need to be passed down to all ocdav handlers +// Config holds the config options that need to be passed down to all ocdav handlers. type Config struct { SMTPCredentials *smtpclient.SMTPCredentials `mapstructure:"smtp_credentials"` Prefix string `mapstructure:"prefix"` @@ -61,9 +61,8 @@ type svc struct { SendHandler *sendHandler } -// New returns a new ocmd object +// New returns a new ocmd object. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { - conf := &Config{} if err := mapstructure.Decode(m, conf); err != nil { return nil, err @@ -104,7 +103,6 @@ func (s *svc) Unprotected() []string { func (s *svc) Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() log := appctx.GetLogger(ctx) diff --git a/internal/http/services/ocmd/reqres.go b/internal/http/services/ocmd/reqres.go index d37824a8fc8..8203fb0e40f 100644 --- a/internal/http/services/ocmd/reqres.go +++ b/internal/http/services/ocmd/reqres.go @@ -25,10 +25,10 @@ import ( "github.com/cs3org/reva/pkg/appctx" ) -// APIErrorCode stores the type of error encountered +// APIErrorCode stores the type of error encountered. type APIErrorCode string -// The various types of errors that can be expected to occur +// The various types of errors that can be expected to occur. const ( APIErrorNotFound APIErrorCode = "RESOURCE_NOT_FOUND" APIErrorUnauthenticated APIErrorCode = "UNAUTHENTICATED" @@ -39,7 +39,7 @@ const ( APIErrorServerError APIErrorCode = "SERVER_ERROR" ) -// APIErrorCodeMapping stores the HTTP error code mapping for various APIErrorCodes +// APIErrorCodeMapping stores the HTTP error code mapping for various APIErrorCodes. var APIErrorCodeMapping = map[APIErrorCode]int{ APIErrorNotFound: http.StatusNotFound, APIErrorUnauthenticated: http.StatusUnauthorized, @@ -50,13 +50,13 @@ var APIErrorCodeMapping = map[APIErrorCode]int{ APIErrorServerError: http.StatusInternalServerError, } -// APIError encompasses the error type and message +// APIError encompasses the error type and message. type APIError struct { Code APIErrorCode `json:"code"` Message string `json:"message"` } -// WriteError handles writing error responses +// WriteError handles writing error responses. func WriteError(w http.ResponseWriter, r *http.Request, code APIErrorCode, message string, e error) { if e != nil { appctx.GetLogger(r.Context()).Error().Err(e).Msg(message) diff --git a/internal/http/services/ocmd/send.go b/internal/http/services/ocmd/send.go index d0106abed36..2315c61a440 100644 --- a/internal/http/services/ocmd/send.go +++ b/internal/http/services/ocmd/send.go @@ -35,9 +35,8 @@ import ( types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/cs3org/reva/pkg/appctx" ctxpkg "github.com/cs3org/reva/pkg/ctx" - "google.golang.org/grpc/metadata" - "github.com/cs3org/reva/pkg/rgrpc/todo/pool" + "google.golang.org/grpc/metadata" ) type sendHandler struct { diff --git a/internal/http/services/ocmd/shares.go b/internal/http/services/ocmd/shares.go index 197ea8903cf..64bb5237201 100644 --- a/internal/http/services/ocmd/shares.go +++ b/internal/http/services/ocmd/shares.go @@ -51,7 +51,6 @@ func (h *sharesHandler) init(c *Config) { func (h *sharesHandler) Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.Method { case http.MethodPost: h.createShare(w, r) diff --git a/internal/http/services/owncloud/ocdav/avatars.go b/internal/http/services/owncloud/ocdav/avatars.go index 2271d2901bd..915930176a1 100644 --- a/internal/http/services/owncloud/ocdav/avatars.go +++ b/internal/http/services/owncloud/ocdav/avatars.go @@ -26,7 +26,7 @@ import ( "github.com/cs3org/reva/pkg/rhttp/router" ) -// AvatarsHandler handles avatar requests +// AvatarsHandler handles avatar requests. type AvatarsHandler struct { } @@ -34,7 +34,7 @@ func (h *AvatarsHandler) init(c *Config) error { return nil } -// Handler handles requests +// Handler handles requests. func (h *AvatarsHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() diff --git a/internal/http/services/owncloud/ocdav/copy.go b/internal/http/services/owncloud/ocdav/copy.go index ac8caa70c07..f9614bf85d0 100644 --- a/internal/http/services/owncloud/ocdav/copy.go +++ b/internal/http/services/owncloud/ocdav/copy.go @@ -167,7 +167,6 @@ func (s *svc) executePathCopy(ctx context.Context, client gateway.GatewayAPIClie return err } } - } else { // copy file @@ -268,7 +267,6 @@ func (s *svc) executePathCopy(ctx context.Context, client gateway.GatewayAPIClie if httpUploadRes.StatusCode != http.StatusOK { return err } - } return nil } diff --git a/internal/http/services/owncloud/ocdav/dav.go b/internal/http/services/owncloud/ocdav/dav.go index 1e07c570ce7..3967ea9f267 100644 --- a/internal/http/services/owncloud/ocdav/dav.go +++ b/internal/http/services/owncloud/ocdav/dav.go @@ -27,7 +27,6 @@ import ( gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" - rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/appctx" ctxpkg "github.com/cs3org/reva/pkg/ctx" @@ -38,7 +37,7 @@ import ( type tokenStatInfoKey struct{} -// DavHandler routes to the different sub handlers +// DavHandler routes to the different sub handlers. type DavHandler struct { AvatarsHandler *AvatarsHandler FilesHandler *WebDavHandler @@ -91,7 +90,7 @@ func isOwner(userIDorName string, user *userv1beta1.User) bool { return userIDorName != "" && (userIDorName == user.Id.OpaqueId || strings.EqualFold(userIDorName, user.Username)) } -// Handler handles requests +// Handler handles requests. func (h *DavHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -200,15 +199,15 @@ func (h *DavHandler) Handler(s *svc) http.Handler { case err != nil: w.WriteHeader(http.StatusInternalServerError) return - case res.Status.Code == rpcv1beta1.Code_CODE_PERMISSION_DENIED: + case res.Status.Code == rpc.Code_CODE_PERMISSION_DENIED: fallthrough - case res.Status.Code == rpcv1beta1.Code_CODE_UNAUTHENTICATED: + case res.Status.Code == rpc.Code_CODE_UNAUTHENTICATED: w.WriteHeader(http.StatusUnauthorized) return - case res.Status.Code == rpcv1beta1.Code_CODE_NOT_FOUND: + case res.Status.Code == rpc.Code_CODE_NOT_FOUND: w.WriteHeader(http.StatusNotFound) return - case res.Status.Code != rpcv1beta1.Code_CODE_OK: + case res.Status.Code != rpc.Code_CODE_OK: w.WriteHeader(http.StatusInternalServerError) return } diff --git a/internal/http/services/owncloud/ocdav/error.go b/internal/http/services/owncloud/ocdav/error.go index fec06430c50..a7b32f309a1 100644 --- a/internal/http/services/owncloud/ocdav/error.go +++ b/internal/http/services/owncloud/ocdav/error.go @@ -31,19 +31,19 @@ type code int const ( - // SabredavBadRequest maps to HTTP 400 + // SabredavBadRequest maps to HTTP 400. SabredavBadRequest code = iota - // SabredavMethodNotAllowed maps to HTTP 405 + // SabredavMethodNotAllowed maps to HTTP 405. SabredavMethodNotAllowed - // SabredavNotAuthenticated maps to HTTP 401 + // SabredavNotAuthenticated maps to HTTP 401. SabredavNotAuthenticated - // SabredavPreconditionFailed maps to HTTP 412 + // SabredavPreconditionFailed maps to HTTP 412. SabredavPreconditionFailed - // SabredavPermissionDenied maps to HTTP 403 + // SabredavPermissionDenied maps to HTTP 403. SabredavPermissionDenied - // SabredavNotFound maps to HTTP 404 + // SabredavNotFound maps to HTTP 404. SabredavNotFound - // SabredavConflict maps to HTTP 409 + // SabredavConflict maps to HTTP 409. SabredavConflict ) @@ -95,7 +95,7 @@ type errorXML struct { var errInvalidPropfind = errors.New("webdav: invalid propfind") // HandleErrorStatus checks the status code, logs a Debug or Error level message -// and writes an appropriate http status +// and writes an appropriate http status. func HandleErrorStatus(log *zerolog.Logger, w http.ResponseWriter, s *rpc.Status) { switch s.Code { case rpc.Code_CODE_OK: @@ -129,7 +129,7 @@ func HandleErrorStatus(log *zerolog.Logger, w http.ResponseWriter, s *rpc.Status } // HandleWebdavError checks the status code, logs an error and creates a webdav response body -// if needed +// if needed. func HandleWebdavError(log *zerolog.Logger, w http.ResponseWriter, b []byte, err error) { if err != nil { log.Error().Msgf("error marshaling xml response: %s", b) diff --git a/internal/http/services/owncloud/ocdav/head.go b/internal/http/services/owncloud/ocdav/head.go index 88b03379ebb..ba1b6e16e5e 100644 --- a/internal/http/services/owncloud/ocdav/head.go +++ b/internal/http/services/owncloud/ocdav/head.go @@ -27,14 +27,13 @@ import ( "strings" "time" - rtrace "github.com/cs3org/reva/pkg/trace" - "github.com/cs3org/reva/pkg/utils/resourceid" - rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/internal/grpc/services/storageprovider" "github.com/cs3org/reva/pkg/appctx" + rtrace "github.com/cs3org/reva/pkg/trace" "github.com/cs3org/reva/pkg/utils" + "github.com/cs3org/reva/pkg/utils/resourceid" "github.com/rs/zerolog" ) diff --git a/internal/http/services/owncloud/ocdav/lock.go b/internal/http/services/owncloud/ocdav/lock.go index 65f43cf64c2..4e15a24359c 100644 --- a/internal/http/services/owncloud/ocdav/lock.go +++ b/internal/http/services/owncloud/ocdav/lock.go @@ -24,7 +24,7 @@ import ( "github.com/cs3org/reva/pkg/appctx" ) -// TODO(jfd) implement lock +// TODO(jfd) implement lock. func (s *svc) handleLock(w http.ResponseWriter, r *http.Request, ns string) { log := appctx.GetLogger(r.Context()) xml := ` diff --git a/internal/http/services/owncloud/ocdav/meta.go b/internal/http/services/owncloud/ocdav/meta.go index 7aaffea1420..2888b2e7992 100644 --- a/internal/http/services/owncloud/ocdav/meta.go +++ b/internal/http/services/owncloud/ocdav/meta.go @@ -25,7 +25,7 @@ import ( "github.com/cs3org/reva/pkg/utils/resourceid" ) -// MetaHandler handles meta requests +// MetaHandler handles meta requests. type MetaHandler struct { VersionsHandler *VersionsHandler } @@ -35,10 +35,9 @@ func (h *MetaHandler) init(c *Config) error { return h.VersionsHandler.init(c) } -// Handler handles requests +// Handler handles requests. func (h *MetaHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var id string id, r.URL.Path = router.ShiftPath(r.URL.Path) if id == "" { @@ -56,6 +55,5 @@ func (h *MetaHandler) Handler(s *svc) http.Handler { default: w.WriteHeader(http.StatusNotFound) } - }) } diff --git a/internal/http/services/owncloud/ocdav/mkcol.go b/internal/http/services/owncloud/ocdav/mkcol.go index 17cd6543fa6..2cd1f5093e5 100644 --- a/internal/http/services/owncloud/ocdav/mkcol.go +++ b/internal/http/services/owncloud/ocdav/mkcol.go @@ -81,7 +81,6 @@ func (s *svc) handleSpacesMkCol(w http.ResponseWriter, r *http.Request, spaceID } s.handleMkcol(ctx, w, r, parentRef, childRef, sublog) - } func (s *svc) handleMkcol(ctx context.Context, w http.ResponseWriter, r *http.Request, parentRef, childRef *provider.Reference, log zerolog.Logger) { diff --git a/internal/http/services/owncloud/ocdav/ocdav.go b/internal/http/services/owncloud/ocdav/ocdav.go index 33020ddde23..8a45c7ac9a7 100644 --- a/internal/http/services/owncloud/ocdav/ocdav.go +++ b/internal/http/services/owncloud/ocdav/ocdav.go @@ -83,7 +83,7 @@ func init() { global.Register("ocdav", New) } -// Config holds the config options that need to be passed down to all ocdav handlers +// Config holds the config options that need to be passed down to all ocdav handlers. type Config struct { Prefix string `mapstructure:"prefix"` // FilesNamespace prefixes the namespace, optionally with user information. @@ -130,7 +130,7 @@ func getFavoritesManager(c *Config) (favorite.Manager, error) { return nil, errtypes.NotFound("driver not found: " + c.FavoriteStorageDriver) } -// New returns a new ocdav +// New returns a new ocdav. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &Config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/owncloud/ocdav/ocdav_test.go b/internal/http/services/owncloud/ocdav/ocdav_test.go index 941a4b99a8c..f5b2e30ebfb 100644 --- a/internal/http/services/owncloud/ocdav/ocdav_test.go +++ b/internal/http/services/owncloud/ocdav/ocdav_test.go @@ -157,5 +157,4 @@ func TestNameDoesNotContainRule(t *testing.T) { } } } - } diff --git a/internal/http/services/owncloud/ocdav/propfind.go b/internal/http/services/owncloud/ocdav/propfind.go index e5a94c6521d..fc5fd14472f 100644 --- a/internal/http/services/owncloud/ocdav/propfind.go +++ b/internal/http/services/owncloud/ocdav/propfind.go @@ -62,12 +62,12 @@ const ( // RFC1123 time that mimics oc10. time.RFC1123 would end in "UTC", see https://github.com/golang/go/issues/13781 RFC1123 = "Mon, 02 Jan 2006 15:04:05 GMT" - // _propQuotaUncalculated = "-1" + // _propQuotaUncalculated = "-1". _propQuotaUnknown = "-2" - // _propQuotaUnlimited = "-3" + // _propQuotaUnlimited = "-3". ) -// ns is the namespace that is prefixed to the path in the cs3 namespace +// ns is the namespace that is prefixed to the path in the cs3 namespace. func (s *svc) handlePathPropfind(w http.ResponseWriter, r *http.Request, ns string) { ctx, span := rtrace.Provider.Tracer("reva").Start(r.Context(), fmt.Sprintf("%s %v", r.Method, r.URL.Path)) defer span.End() @@ -140,7 +140,6 @@ func (s *svc) handleSpacesPropfind(w http.ResponseWriter, r *http.Request, space } s.propfindResponse(ctx, w, r, "", pf, parentInfo, resourceInfos, sublog) - } func (s *svc) propfindResponse(ctx context.Context, w http.ResponseWriter, r *http.Request, namespace string, pf propfindXML, parentInfo *provider.ResourceInfo, resourceInfos []*provider.ResourceInfo, log zerolog.Logger) { @@ -484,7 +483,7 @@ func (s *svc) newPropNS(namespace string, local string, val string) *propertyXML } } -// TODO properly use the space +// TODO properly use the space. func (s *svc) newProp(key, val string) *propertyXML { return &propertyXML{ XMLName: xml.Name{Space: "", Local: key}, @@ -493,7 +492,7 @@ func (s *svc) newProp(key, val string) *propertyXML { } } -// TODO properly use the space +// TODO properly use the space. func (s *svc) newPropRaw(key, val string) *propertyXML { return &propertyXML{ XMLName: xml.Name{Space: "", Local: key}, @@ -504,7 +503,7 @@ func (s *svc) newPropRaw(key, val string) *propertyXML { // mdToPropResponse converts the CS3 metadata into a webdav PropResponse // ns is the CS3 namespace that needs to be removed from the CS3 path before -// prefixing it with the baseURI +// prefixing it with the baseURI. func (s *svc) mdToPropResponse(ctx context.Context, pf *propfindXML, md *provider.ResourceInfo, ns string, usershares, linkshares map[string]struct{}) (*responseXML, error) { sublog := appctx.GetLogger(ctx).With().Str("ns", ns).Logger() md.Path = strings.TrimPrefix(md.Path, ns) @@ -1013,7 +1012,7 @@ func (s *svc) mdToPropResponse(ctx context.Context, pf *propfindXML, md *provide return &response, nil } -// be defensive about wrong encoded etags +// be defensive about wrong encoded etags. func quoteEtag(etag string) string { if strings.HasPrefix(etag, "W/") { return `W/"` + strings.Trim(etag[2:], `"`) + `"` @@ -1021,7 +1020,7 @@ func quoteEtag(etag string) string { return `"` + strings.Trim(etag, `"`) + `"` } -// a file is only yours if you are the owner +// a file is only yours if you are the owner. func isCurrentUserOwner(ctx context.Context, owner *userv1beta1.UserId) bool { contextUser, ok := ctxpkg.ContextGetUser(ctx) if ok && contextUser.Id != nil && owner != nil && diff --git a/internal/http/services/owncloud/ocdav/publicfile.go b/internal/http/services/owncloud/ocdav/publicfile.go index d5b6c54c9a9..b6162124364 100644 --- a/internal/http/services/owncloud/ocdav/publicfile.go +++ b/internal/http/services/owncloud/ocdav/publicfile.go @@ -30,7 +30,7 @@ import ( rtrace "github.com/cs3org/reva/pkg/trace" ) -// PublicFileHandler handles requests on a shared file. it needs to be wrapped in a collection +// PublicFileHandler handles requests on a shared file. it needs to be wrapped in a collection. type PublicFileHandler struct { namespace string } @@ -40,7 +40,7 @@ func (h *PublicFileHandler) init(ns string) error { return nil } -// Handler handles requests +// Handler handles requests. func (h *PublicFileHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log := appctx.GetLogger(r.Context()) @@ -123,7 +123,7 @@ func (s *svc) adjustResourcePathInURL(w http.ResponseWriter, r *http.Request) bo return true } -// ns is the namespace that is prefixed to the path in the cs3 namespace +// ns is the namespace that is prefixed to the path in the cs3 namespace. func (s *svc) handlePropfindOnToken(w http.ResponseWriter, r *http.Request, ns string, onContainer bool) { ctx, span := rtrace.Provider.Tracer("ocdav").Start(r.Context(), "token_propfind") defer span.End() @@ -196,7 +196,7 @@ func (s *svc) handlePropfindOnToken(w http.ResponseWriter, r *http.Request, ns s // there are only two possible entries // 1. the non existing collection -// 2. the shared file +// 2. the shared file. func (s *svc) getPublicFileInfos(onContainer, onlyRoot bool, i *provider.ResourceInfo) []*provider.ResourceInfo { infos := []*provider.ResourceInfo{} if onContainer { diff --git a/internal/http/services/owncloud/ocdav/report.go b/internal/http/services/owncloud/ocdav/report.go index da921905aff..421776efa66 100644 --- a/internal/http/services/owncloud/ocdav/report.go +++ b/internal/http/services/owncloud/ocdav/report.go @@ -26,7 +26,6 @@ import ( rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/appctx" ctxpkg "github.com/cs3org/reva/pkg/ctx" ) @@ -97,7 +96,7 @@ func (s *svc) doFilterFiles(w http.ResponseWriter, r *http.Request, ff *reportFi infos := make([]*provider.ResourceInfo, 0, len(favorites)) for i := range favorites { - statRes, err := client.Stat(ctx, &providerv1beta1.StatRequest{Ref: &providerv1beta1.Reference{ResourceId: favorites[i]}}) + statRes, err := client.Stat(ctx, &provider.StatRequest{Ref: &provider.Reference{ResourceId: favorites[i]}}) if err != nil { log.Error().Err(err).Msg("error getting resource info") continue diff --git a/internal/http/services/owncloud/ocdav/spaces.go b/internal/http/services/owncloud/ocdav/spaces.go index 36d31f5f57f..6c942efef14 100644 --- a/internal/http/services/owncloud/ocdav/spaces.go +++ b/internal/http/services/owncloud/ocdav/spaces.go @@ -29,7 +29,7 @@ import ( "github.com/cs3org/reva/pkg/utils" ) -// SpacesHandler handles trashbin requests +// SpacesHandler handles trashbin requests. type SpacesHandler struct { gatewaySvc string } @@ -39,7 +39,7 @@ func (h *SpacesHandler) init(c *Config) error { return nil } -// Handler handles requests +// Handler handles requests. func (h *SpacesHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // ctx := r.Context() diff --git a/internal/http/services/owncloud/ocdav/tpc.go b/internal/http/services/owncloud/ocdav/tpc.go index aa324064bfd..a1a9aaae5e6 100644 --- a/internal/http/services/owncloud/ocdav/tpc.go +++ b/internal/http/services/owncloud/ocdav/tpc.go @@ -39,11 +39,11 @@ import ( ) const ( - // PerfMarkerResponseTime corresponds to the interval at which a performance marker is sent back to the TPC client + // PerfMarkerResponseTime corresponds to the interval at which a performance marker is sent back to the TPC client. PerfMarkerResponseTime float64 = 5 ) -// PerfResponse provides a single chunk of permormance marker response +// PerfResponse provides a single chunk of permormance marker response. type PerfResponse struct { Timestamp time.Time Bytes uint64 @@ -85,7 +85,6 @@ func (wc *WriteCounter) SendPerfMarker(size uint64) { } func (wc *WriteCounter) Write(p []byte) (int, error) { - n := len(p) wc.Total += uint64(n) NowTime := time.Now() @@ -377,7 +376,7 @@ func (s *svc) performHTTPPush(ctx context.Context, client gateway.GatewayAPIClie defer httpDownloadRes.Body.Close() if httpDownloadRes.StatusCode != http.StatusOK { w.WriteHeader(httpDownloadRes.StatusCode) - return fmt.Errorf("Remote PUT returned status code %d", httpDownloadRes.StatusCode) + return fmt.Errorf("remote PUT returned status code %d", httpDownloadRes.StatusCode) } // send performance markers periodically every PerfMarkerResponseTime (5 seconds unless configured) diff --git a/internal/http/services/owncloud/ocdav/trashbin.go b/internal/http/services/owncloud/ocdav/trashbin.go index 3cdd91a6ac3..e58f106bdba 100644 --- a/internal/http/services/owncloud/ocdav/trashbin.go +++ b/internal/http/services/owncloud/ocdav/trashbin.go @@ -29,9 +29,6 @@ import ( "strings" "time" - rtrace "github.com/cs3org/reva/pkg/trace" - "github.com/cs3org/reva/pkg/utils/resourceid" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -39,10 +36,12 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" "github.com/cs3org/reva/pkg/rhttp/router" + rtrace "github.com/cs3org/reva/pkg/trace" "github.com/cs3org/reva/pkg/utils" + "github.com/cs3org/reva/pkg/utils/resourceid" ) -// TrashbinHandler handles trashbin requests +// TrashbinHandler handles trashbin requests. type TrashbinHandler struct { gatewaySvc string } @@ -52,7 +51,7 @@ func (h *TrashbinHandler) init(c *Config) error { return nil } -// Handler handles requests +// Handler handles requests. func (h *TrashbinHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -330,9 +329,8 @@ func (h *TrashbinHandler) formatTrashPropfind(ctx context.Context, s *svc, u *us // itemToPropResponse needs to create a listing that contains a key and destination // the key is the name of an entry in the trash listing -// for now we need to limit trash to the users home, so we can expect all trash keys to have the home storage as the opaque id +// for now we need to limit trash to the users home, so we can expect all trash keys to have the home storage as the opaque id. func (h *TrashbinHandler) itemToPropResponse(ctx context.Context, s *svc, u *userpb.User, pf *propfindXML, item *provider.RecycleItem, basePath string) (*responseXML, error) { - baseURI := ctx.Value(ctxKeyBaseURI).(string) ref := path.Join(baseURI, u.Username, item.Key) if item.Type == provider.ResourceType_RESOURCE_TYPE_CONTAINER { @@ -371,7 +369,6 @@ func (h *TrashbinHandler) itemToPropResponse(ctx context.Context, s *svc, u *use s.newProp("d:getcontentlength", fmt.Sprintf("%d", item.Size)), ) } - } else { // otherwise return only the requested properties propstatOK := propstatXML{ @@ -588,7 +585,7 @@ func (h *TrashbinHandler) restore(w http.ResponseWriter, r *http.Request, s *svc w.WriteHeader(successCode) } -// delete has only a key +// delete has only a key. func (h *TrashbinHandler) delete(w http.ResponseWriter, r *http.Request, s *svc, u *userpb.User, basePath, key, itemPath string) { ctx, span := rtrace.Provider.Tracer("trash-bin").Start(r.Context(), "erase") defer span.End() diff --git a/internal/http/services/owncloud/ocdav/tus.go b/internal/http/services/owncloud/ocdav/tus.go index b795d482d42..4468d798354 100644 --- a/internal/http/services/owncloud/ocdav/tus.go +++ b/internal/http/services/owncloud/ocdav/tus.go @@ -217,7 +217,6 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http. // for creation-with-upload extension forward bytes to dataprovider // TODO check this really streams if r.Header.Get(HeaderContentType) == "application/offset+octet-stream" { - length, err := strconv.ParseInt(r.Header.Get(HeaderContentLength), 10, 64) if err != nil { log.Debug().Err(err).Msg("wrong request") @@ -271,7 +270,6 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http. } if sRes.Status.Code != rpc.Code_CODE_OK && sRes.Status.Code != rpc.Code_CODE_NOT_FOUND { - if sRes.Status.Code == rpc.Code_CODE_PERMISSION_DENIED { // the token expired during upload, so the stat failed // and we can't do anything about it. diff --git a/internal/http/services/owncloud/ocdav/unlock.go b/internal/http/services/owncloud/ocdav/unlock.go index 3b20189c38a..af7c855ff86 100644 --- a/internal/http/services/owncloud/ocdav/unlock.go +++ b/internal/http/services/owncloud/ocdav/unlock.go @@ -22,7 +22,7 @@ import ( "net/http" ) -// TODO(jfd): implement unlock +// TODO(jfd): implement unlock. func (s *svc) handleUnlock(w http.ResponseWriter, r *http.Request, ns string) { w.WriteHeader(http.StatusNotImplemented) } diff --git a/internal/http/services/owncloud/ocdav/versions.go b/internal/http/services/owncloud/ocdav/versions.go index b1f3db1eae5..b8ff7d8bb38 100644 --- a/internal/http/services/owncloud/ocdav/versions.go +++ b/internal/http/services/owncloud/ocdav/versions.go @@ -23,17 +23,16 @@ import ( "net/http" "path" - rtrace "github.com/cs3org/reva/pkg/trace" - "github.com/cs3org/reva/pkg/utils/resourceid" - rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/cs3org/reva/pkg/appctx" "github.com/cs3org/reva/pkg/rhttp/router" + rtrace "github.com/cs3org/reva/pkg/trace" + "github.com/cs3org/reva/pkg/utils/resourceid" ) -// VersionsHandler handles version requests +// VersionsHandler handles version requests. type VersionsHandler struct { } @@ -43,7 +42,7 @@ func (h *VersionsHandler) init(c *Config) error { // Handler handles requests // versions can be listed with a PROPFIND to /remote.php/dav/meta//v -// a version is identified by a timestamp, eg. /remote.php/dav/meta//v/1561410426 +// a version is identified by a timestamp, eg. /remote.php/dav/meta//v/1561410426. func (h *VersionsHandler) Handler(s *svc, rid *provider.ResourceId) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -179,7 +178,6 @@ func (h *VersionsHandler) doListVersions(w http.ResponseWriter, r *http.Request, sublog.Error().Err(err).Msg("error writing body") return } - } func (h *VersionsHandler) doRestore(w http.ResponseWriter, r *http.Request, s *svc, rid *provider.ResourceId, key string) { diff --git a/internal/http/services/owncloud/ocdav/webdav.go b/internal/http/services/owncloud/ocdav/webdav.go index 8ad8f1333d4..c6987e10a0c 100644 --- a/internal/http/services/owncloud/ocdav/webdav.go +++ b/internal/http/services/owncloud/ocdav/webdav.go @@ -78,7 +78,7 @@ const ( HeaderTransferAuth = "TransferHeaderAuthorization" ) -// WebDavHandler implements a dav endpoint +// WebDavHandler implements a dav endpoint. type WebDavHandler struct { namespace string useLoggedInUserNS bool @@ -90,7 +90,7 @@ func (h *WebDavHandler) init(ns string, useLoggedInUserNS bool) error { return nil } -// Handler handles requests +// Handler handles requests. func (h *WebDavHandler) Handler(s *svc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ns := applyLayout(r.Context(), h.namespace, h.useLoggedInUserNS, r.URL.Path) diff --git a/internal/http/services/owncloud/ocs/config/config.go b/internal/http/services/owncloud/ocs/config/config.go index a291c51c468..8404e42f7d1 100644 --- a/internal/http/services/owncloud/ocs/config/config.go +++ b/internal/http/services/owncloud/ocs/config/config.go @@ -23,7 +23,7 @@ import ( "github.com/cs3org/reva/pkg/sharedconf" ) -// Config holds the config options that need to be passed down to all ocs handlers +// Config holds the config options that need to be passed down to all ocs handlers. type Config struct { Prefix string `mapstructure:"prefix"` Config data.ConfigData `mapstructure:"config"` @@ -44,7 +44,7 @@ type Config struct { UserIdentifierCacheTTL int `mapstructure:"user_identifier_cache_ttl"` } -// Init sets sane defaults +// Init sets sane defaults. func (c *Config) Init() { if c.Prefix == "" { c.Prefix = "ocs" diff --git a/internal/http/services/owncloud/ocs/conversions/main.go b/internal/http/services/owncloud/ocs/conversions/main.go index f240152bcd3..625f4220b6d 100644 --- a/internal/http/services/owncloud/ocs/conversions/main.go +++ b/internal/http/services/owncloud/ocs/conversions/main.go @@ -26,37 +26,36 @@ import ( "path" "time" - "github.com/cs3org/reva/pkg/publicshare" - "github.com/cs3org/reva/pkg/user" - grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + "github.com/cs3org/reva/pkg/publicshare" publicsharemgr "github.com/cs3org/reva/pkg/publicshare/manager/registry" + "github.com/cs3org/reva/pkg/user" usermgr "github.com/cs3org/reva/pkg/user/manager/registry" ) const ( - // ShareTypeUser refers to user shares + // ShareTypeUser refers to user shares. ShareTypeUser ShareType = 0 - // ShareTypePublicLink refers to public link shares + // ShareTypePublicLink refers to public link shares. ShareTypePublicLink ShareType = 3 - // ShareTypeGroup represents a group share + // ShareTypeGroup represents a group share. ShareTypeGroup ShareType = 1 - // ShareTypeFederatedCloudShare represents a federated share + // ShareTypeFederatedCloudShare represents a federated share. ShareTypeFederatedCloudShare ShareType = 6 - // ShareTypeSpaceMembership represents an action regarding space members + // ShareTypeSpaceMembership represents an action regarding space members. ShareTypeSpaceMembership ShareType = 7 ) -// ResourceType indicates the OCS type of the resource +// ResourceType indicates the OCS type of the resource. type ResourceType int func (rt ResourceType) String() (s string) { @@ -75,7 +74,7 @@ func (rt ResourceType) String() (s string) { return } -// ShareType denotes a type of share +// ShareType denotes a type of share. type ShareType int // ShareData represents https://doc.owncloud.com/server/developer_manual/core/ocs-share-api.html#response-attributes-1 @@ -149,7 +148,7 @@ type ShareData struct { Description string `json:"description" xml:"description"` } -// ShareeData holds share recipient search results +// ShareeData holds share recipient search results. type ShareeData struct { Exact *ExactMatchesData `json:"exact" xml:"exact"` Users []*MatchData `json:"users" xml:"users>element"` @@ -157,27 +156,27 @@ type ShareeData struct { Remotes []*MatchData `json:"remotes" xml:"remotes>element"` } -// ExactMatchesData hold exact matches +// ExactMatchesData hold exact matches. type ExactMatchesData struct { Users []*MatchData `json:"users" xml:"users>element"` Groups []*MatchData `json:"groups" xml:"groups>element"` Remotes []*MatchData `json:"remotes" xml:"remotes>element"` } -// MatchData describes a single match +// MatchData describes a single match. type MatchData struct { Label string `json:"label" xml:"label,omitempty"` Value *MatchValueData `json:"value" xml:"value"` } -// MatchValueData holds the type and actual value +// MatchValueData holds the type and actual value. type MatchValueData struct { ShareType int `json:"shareType" xml:"shareType"` ShareWith string `json:"shareWith" xml:"shareWith"` ShareWithAdditionalInfo string `json:"shareWithAdditionalInfo" xml:"shareWithAdditionalInfo"` } -// CS3Share2ShareData converts a cs3api user share into shareData data model +// CS3Share2ShareData converts a cs3api user share into shareData data model. func CS3Share2ShareData(ctx context.Context, share *collaboration.Share) (*ShareData, error) { sd := &ShareData{ // share.permissions are mapped below @@ -206,7 +205,7 @@ func CS3Share2ShareData(ctx context.Context, share *collaboration.Share) (*Share return sd, nil } -// PublicShare2ShareData converts a cs3api public share into shareData data model +// PublicShare2ShareData converts a cs3api public share into shareData data model. func PublicShare2ShareData(share *link.PublicShare, r *http.Request, publicURL string) *ShareData { sd := &ShareData{ // share.permissions are mapped below @@ -244,7 +243,7 @@ func PublicShare2ShareData(share *link.PublicShare, r *http.Request, publicURL s } // LocalUserIDToString transforms a cs3api user id into an ocs data model without domain name -// TODO ocs uses user names ... so an additional lookup is needed. see mapUserIds() +// TODO ocs uses user names ... so an additional lookup is needed. see mapUserIds(). func LocalUserIDToString(userID *userpb.UserId) string { if userID == nil || userID.OpaqueId == "" { return "" @@ -252,7 +251,7 @@ func LocalUserIDToString(userID *userpb.UserId) string { return userID.OpaqueId } -// LocalGroupIDToString transforms a cs3api group id into an ocs data model without domain name +// LocalGroupIDToString transforms a cs3api group id into an ocs data model without domain name. func LocalGroupIDToString(groupID *grouppb.GroupId) string { if groupID == nil || groupID.OpaqueId == "" { return "" @@ -260,7 +259,7 @@ func LocalGroupIDToString(groupID *grouppb.GroupId) string { return groupID.OpaqueId } -// GetUserManager returns a connection to a user share manager +// GetUserManager returns a connection to a user share manager. func GetUserManager(manager string, m map[string]map[string]interface{}) (user.Manager, error) { if f, ok := usermgr.NewFuncs[manager]; ok { return f(m[manager]) @@ -269,7 +268,7 @@ func GetUserManager(manager string, m map[string]map[string]interface{}) (user.M return nil, fmt.Errorf("driver %s not found for user manager", manager) } -// GetPublicShareManager returns a connection to a public share manager +// GetPublicShareManager returns a connection to a public share manager. func GetPublicShareManager(manager string, m map[string]map[string]interface{}) (publicshare.Manager, error) { if f, ok := publicsharemgr.NewFuncs[manager]; ok { return f(m[manager]) @@ -284,7 +283,7 @@ func timestampToExpiration(t *types.Timestamp) string { return time.Unix(int64(t.Seconds), int64(t.Nanos)).UTC().Format("2006-01-02 15:05:05") } -// ParseTimestamp tries to parses the ocs expiry into a CS3 Timestamp +// ParseTimestamp tries to parses the ocs expiry into a CS3 Timestamp. func ParseTimestamp(timestampString string) (*types.Timestamp, error) { parsedTime, err := time.Parse("2006-01-02T15:04:05Z0700", timestampString) if err != nil { @@ -301,7 +300,7 @@ func ParseTimestamp(timestampString string) (*types.Timestamp, error) { }, nil } -// UserTypeString returns human readable strings for various user types +// UserTypeString returns human readable strings for various user types. func UserTypeString(userType userpb.UserType) string { switch userType { case userpb.UserType_USER_TYPE_PRIMARY: diff --git a/internal/http/services/owncloud/ocs/conversions/permissions.go b/internal/http/services/owncloud/ocs/conversions/permissions.go index 4d860fb6943..1f90a8cfeb5 100644 --- a/internal/http/services/owncloud/ocs/conversions/permissions.go +++ b/internal/http/services/owncloud/ocs/conversions/permissions.go @@ -22,29 +22,29 @@ import ( "fmt" ) -// Permissions reflects the CRUD permissions used in the OCS sharing API +// Permissions reflects the CRUD permissions used in the OCS sharing API. type Permissions uint const ( - // PermissionInvalid grants no permissions on a resource + // PermissionInvalid grants no permissions on a resource. PermissionInvalid Permissions = 0 - // PermissionRead grants read permissions on a resource + // PermissionRead grants read permissions on a resource. PermissionRead Permissions = 1 << (iota - 1) - // PermissionWrite grants write permissions on a resource + // PermissionWrite grants write permissions on a resource. PermissionWrite - // PermissionCreate grants create permissions on a resource + // PermissionCreate grants create permissions on a resource. PermissionCreate - // PermissionDelete grants delete permissions on a resource + // PermissionDelete grants delete permissions on a resource. PermissionDelete - // PermissionShare grants share permissions on a resource + // PermissionShare grants share permissions on a resource. PermissionShare - // PermissionAll grants all permissions on a resource + // PermissionAll grants all permissions on a resource. PermissionAll Permissions = (1 << (iota - 1)) - 1 ) var ( // ErrPermissionNotInRange defines a permission specific error. - ErrPermissionNotInRange = fmt.Errorf("The provided permission is not between %d and %d", PermissionInvalid, PermissionAll) + ErrPermissionNotInRange = fmt.Errorf("the provided permission is not between %d and %d", PermissionInvalid, PermissionAll) ) // NewPermissions creates a new Permissions instance. diff --git a/internal/http/services/owncloud/ocs/conversions/role.go b/internal/http/services/owncloud/ocs/conversions/role.go index 3ede7b81df5..3b03d0a92a5 100644 --- a/internal/http/services/owncloud/ocs/conversions/role.go +++ b/internal/http/services/owncloud/ocs/conversions/role.go @@ -53,12 +53,12 @@ const ( RoleLegacy = "legacy" ) -// CS3ResourcePermissions for the role +// CS3ResourcePermissions for the role. func (r *Role) CS3ResourcePermissions() *provider.ResourcePermissions { return r.cS3ResourcePermissions } -// OCSPermissions for the role +// OCSPermissions for the role. func (r *Role) OCSPermissions() Permissions { return r.ocsPermissions } @@ -91,7 +91,7 @@ func (r *Role) OCSPermissions() Permissions { // CK = create (folders only) // S = Shared // R = Shareable -// M = Mounted +// M = Mounted. func (r *Role) WebDAVPermissions(isDir, isShared, isMountpoint, isPublic bool) string { var b strings.Builder if !isPublic && isShared { @@ -118,7 +118,7 @@ func (r *Role) WebDAVPermissions(isDir, isShared, isMountpoint, isPublic bool) s return b.String() } -// RoleFromName creates a role from the name +// RoleFromName creates a role from the name. func RoleFromName(name string) *Role { switch name { case RoleViewer: @@ -147,7 +147,7 @@ func NewUnknownRole() *Role { } } -// NewViewerRole creates a viewer role +// NewViewerRole creates a viewer role. func NewViewerRole() *Role { return &Role{ Name: RoleViewer, @@ -165,7 +165,7 @@ func NewViewerRole() *Role { } } -// NewEditorRole creates an editor role +// NewEditorRole creates an editor role. func NewEditorRole() *Role { return &Role{ Name: RoleEditor, @@ -190,7 +190,7 @@ func NewEditorRole() *Role { } } -// NewFileEditorRole creates a file-editor role +// NewFileEditorRole creates a file-editor role. func NewFileEditorRole() *Role { return &Role{ Name: RoleEditor, @@ -211,7 +211,7 @@ func NewFileEditorRole() *Role { } } -// NewCoownerRole creates a coowner role +// NewCoownerRole creates a coowner role. func NewCoownerRole() *Role { return &Role{ Name: RoleCoowner, @@ -239,7 +239,7 @@ func NewCoownerRole() *Role { } } -// NewUploaderRole creates an uploader role +// NewUploaderRole creates an uploader role. func NewUploaderRole() *Role { return &Role{ Name: RoleUploader, @@ -254,7 +254,7 @@ func NewUploaderRole() *Role { } } -// NewManagerRole creates an editor role +// NewManagerRole creates an editor role. func NewManagerRole() *Role { return &Role{ Name: RoleManager, @@ -284,7 +284,7 @@ func NewManagerRole() *Role { } } -// RoleFromOCSPermissions tries to map ocs permissions to a role +// RoleFromOCSPermissions tries to map ocs permissions to a role. func RoleFromOCSPermissions(p Permissions) *Role { if p.Contain(PermissionRead) { if p.Contain(PermissionWrite) && p.Contain(PermissionCreate) && p.Contain(PermissionDelete) { @@ -304,7 +304,7 @@ func RoleFromOCSPermissions(p Permissions) *Role { return NewLegacyRoleFromOCSPermissions(p) } -// NewLegacyRoleFromOCSPermissions tries to map a legacy combination of ocs permissions to cs3 resource permissions as a legacy role +// NewLegacyRoleFromOCSPermissions tries to map a legacy combination of ocs permissions to cs3 resource permissions as a legacy role. func NewLegacyRoleFromOCSPermissions(p Permissions) *Role { r := &Role{ Name: RoleLegacy, // TODO custom role? @@ -350,7 +350,7 @@ func NewLegacyRoleFromOCSPermissions(p Permissions) *Role { return r } -// RoleFromResourcePermissions tries to map cs3 resource permissions to a role +// RoleFromResourcePermissions tries to map cs3 resource permissions to a role. func RoleFromResourcePermissions(rp *provider.ResourcePermissions) *Role { r := &Role{ Name: RoleUnknown, diff --git a/internal/http/services/owncloud/ocs/data/capabilities.go b/internal/http/services/owncloud/ocs/data/capabilities.go index 5329d2b6621..714e4ca1382 100644 --- a/internal/http/services/owncloud/ocs/data/capabilities.go +++ b/internal/http/services/owncloud/ocs/data/capabilities.go @@ -42,13 +42,13 @@ func (c ocsBool) MarshalXML(e *xml.Encoder, start xml.StartElement) error { return e.EncodeElement("0", start) } -// CapabilitiesData TODO document +// CapabilitiesData TODO document. type CapabilitiesData struct { Capabilities *Capabilities `json:"capabilities" xml:"capabilities"` Version *Version `json:"version" xml:"version"` } -// Capabilities groups several capability aspects +// Capabilities groups several capability aspects. type Capabilities struct { Core *CapabilitiesCore `json:"core" xml:"core"` Checksums *CapabilitiesChecksums `json:"checksums" xml:"checksums"` @@ -68,7 +68,7 @@ type Spaces struct { Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` } -// CapabilitiesCore holds webdav config +// CapabilitiesCore holds webdav config. type CapabilitiesCore struct { PollInterval int `json:"pollinterval" xml:"pollinterval" mapstructure:"poll_interval"` WebdavRoot string `json:"webdav-root,omitempty" xml:"webdav-root,omitempty" mapstructure:"webdav_root"` @@ -76,7 +76,7 @@ type CapabilitiesCore struct { SupportURLSigning ocsBool `json:"support-url-signing" xml:"support-url-signing" mapstructure:"support_url_signing"` } -// Status holds basic status information +// Status holds basic status information. type Status struct { Installed ocsBool `json:"installed" xml:"installed"` Maintenance ocsBool `json:"maintenance" xml:"maintenance"` @@ -89,13 +89,13 @@ type Status struct { Hostname string `json:"hostname,omitempty" xml:"hostname,omitempty"` } -// CapabilitiesChecksums holds available hashes +// CapabilitiesChecksums holds available hashes. type CapabilitiesChecksums struct { SupportedTypes []string `json:"supportedTypes" xml:"supportedTypes>element" mapstructure:"supported_types"` PreferredUploadType string `json:"preferredUploadType" xml:"preferredUploadType" mapstructure:"preferred_upload_type"` } -// CapabilitiesFilesTusSupport TODO this must be a summary of storages +// CapabilitiesFilesTusSupport TODO this must be a summary of storages. type CapabilitiesFilesTusSupport struct { Version string `json:"version" xml:"version"` Resumable string `json:"resumable" xml:"resumable"` @@ -104,7 +104,7 @@ type CapabilitiesFilesTusSupport struct { HTTPMethodOverride string `json:"http_method_override" xml:"http_method_override" mapstructure:"http_method_override"` } -// CapabilitiesArchiver holds available archivers information +// CapabilitiesArchiver holds available archivers information. type CapabilitiesArchiver struct { Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` Version string `json:"version" xml:"version" mapstructure:"version"` @@ -114,7 +114,7 @@ type CapabilitiesArchiver struct { MaxSize string `json:"max_size" xml:"max_size" mapstructure:"max_size"` } -// CapabilitiesAppProvider holds available app provider information +// CapabilitiesAppProvider holds available app provider information. type CapabilitiesAppProvider struct { Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` Version string `json:"version" xml:"version" mapstructure:"version"` @@ -137,7 +137,7 @@ type CapabilitiesFiles struct { AppProviders []*CapabilitiesAppProvider `json:"app_providers" xml:"app_providers" mapstructure:"app_providers"` } -// CapabilitiesDav holds dav endpoint config +// CapabilitiesDav holds dav endpoint config. type CapabilitiesDav struct { Chunking string `json:"chunking" xml:"chunking"` Trashbin string `json:"trashbin" xml:"trashbin"` @@ -145,7 +145,7 @@ type CapabilitiesDav struct { ChunkingParallelUploadDisabled bool `json:"chunkingParallelUploadDisabled" xml:"chunkingParallelUploadDisabled"` } -// CapabilitiesFilesSharing TODO document +// CapabilitiesFilesSharing TODO document. type CapabilitiesFilesSharing struct { APIEnabled ocsBool `json:"api_enabled" xml:"api_enabled" mapstructure:"api_enabled"` Resharing ocsBool `json:"resharing" xml:"resharing"` @@ -163,7 +163,7 @@ type CapabilitiesFilesSharing struct { User *CapabilitiesFilesSharingUser `json:"user" xml:"user"` } -// CapabilitiesFilesSharingPublic TODO document +// CapabilitiesFilesSharingPublic TODO document. type CapabilitiesFilesSharingPublic struct { Enabled ocsBool `json:"enabled" xml:"enabled"` SendMail ocsBool `json:"send_mail" xml:"send_mail" mapstructure:"send_mail"` @@ -176,60 +176,60 @@ type CapabilitiesFilesSharingPublic struct { ExpireDate *CapabilitiesFilesSharingPublicExpireDate `json:"expire_date" xml:"expire_date" mapstructure:"expire_date"` } -// CapabilitiesFilesSharingPublicPassword TODO document +// CapabilitiesFilesSharingPublicPassword TODO document. type CapabilitiesFilesSharingPublicPassword struct { EnforcedFor *CapabilitiesFilesSharingPublicPasswordEnforcedFor `json:"enforced_for" xml:"enforced_for" mapstructure:"enforced_for"` Enforced ocsBool `json:"enforced" xml:"enforced"` } -// CapabilitiesFilesSharingPublicPasswordEnforcedFor TODO document +// CapabilitiesFilesSharingPublicPasswordEnforcedFor TODO document. type CapabilitiesFilesSharingPublicPasswordEnforcedFor struct { ReadOnly ocsBool `json:"read_only" xml:"read_only,omitempty" mapstructure:"read_only"` ReadWrite ocsBool `json:"read_write" xml:"read_write,omitempty" mapstructure:"read_write"` UploadOnly ocsBool `json:"upload_only" xml:"upload_only,omitempty" mapstructure:"upload_only"` } -// CapabilitiesFilesSharingPublicExpireDate TODO document +// CapabilitiesFilesSharingPublicExpireDate TODO document. type CapabilitiesFilesSharingPublicExpireDate struct { Enabled ocsBool `json:"enabled" xml:"enabled"` } -// CapabilitiesFilesSharingUser TODO document +// CapabilitiesFilesSharingUser TODO document. type CapabilitiesFilesSharingUser struct { SendMail ocsBool `json:"send_mail" xml:"send_mail" mapstructure:"send_mail"` ProfilePicture ocsBool `json:"profile_picture" xml:"profile_picture" mapstructure:"profile_picture"` Settings []*CapabilitiesUserSettings `json:"settings" xml:"settings" mapstructure:"settings"` } -// CapabilitiesUserSettings holds available user settings service information +// CapabilitiesUserSettings holds available user settings service information. type CapabilitiesUserSettings struct { Enabled bool `json:"enabled" xml:"enabled" mapstructure:"enabled"` Version string `json:"version" xml:"version" mapstructure:"version"` } -// CapabilitiesFilesSharingUserEnumeration TODO document +// CapabilitiesFilesSharingUserEnumeration TODO document. type CapabilitiesFilesSharingUserEnumeration struct { Enabled ocsBool `json:"enabled" xml:"enabled"` GroupMembersOnly ocsBool `json:"group_members_only" xml:"group_members_only" mapstructure:"group_members_only"` } -// CapabilitiesFilesSharingFederation holds outgoing and incoming flags +// CapabilitiesFilesSharingFederation holds outgoing and incoming flags. type CapabilitiesFilesSharingFederation struct { Outgoing ocsBool `json:"outgoing" xml:"outgoing"` Incoming ocsBool `json:"incoming" xml:"incoming"` } -// CapabilitiesNotifications holds a list of notification endpoints +// CapabilitiesNotifications holds a list of notification endpoints. type CapabilitiesNotifications struct { Endpoints []string `json:"ocs-endpoints,omitempty" xml:"ocs-endpoints>element,omitempty" mapstructure:"endpoints"` } -// CapabilitiesGroupBased holds capabilities based on the groups a user belongs to +// CapabilitiesGroupBased holds capabilities based on the groups a user belongs to. type CapabilitiesGroupBased struct { Capabilities []string `json:"capabilities" xml:"capabilities" mapstructure:"capabilities"` } -// Version holds version information +// Version holds version information. type Version struct { Major int `json:"major" xml:"major"` Minor int `json:"minor" xml:"minor"` diff --git a/internal/http/services/owncloud/ocs/data/config.go b/internal/http/services/owncloud/ocs/data/config.go index 20de941665a..f721d9b1499 100644 --- a/internal/http/services/owncloud/ocs/data/config.go +++ b/internal/http/services/owncloud/ocs/data/config.go @@ -18,7 +18,7 @@ package data -// ConfigData holds basic config +// ConfigData holds basic config. type ConfigData struct { Version string `json:"version" xml:"version"` Website string `json:"website" xml:"website"` diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/sharees/sharees.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/sharees/sharees.go index 9966927fa96..6b493397e87 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/sharees/sharees.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/sharees/sharees.go @@ -23,7 +23,6 @@ import ( grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - "github.com/cs3org/reva/internal/http/services/owncloud/ocs/config" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" @@ -32,19 +31,19 @@ import ( "github.com/cs3org/reva/pkg/storage/utils/templates" ) -// Handler implements the ownCloud sharing API +// Handler implements the ownCloud sharing API. type Handler struct { gatewayAddr string additionalInfoAttribute string } -// Init initializes this and any contained handlers +// Init initializes this and any contained handlers. func (h *Handler) Init(c *config.Config) { h.gatewayAddr = c.GatewaySvc h.additionalInfoAttribute = c.AdditionalInfoAttribute } -// FindSharees implements the /apps/files_sharing/api/v1/sharees endpoint +// FindSharees implements the /apps/files_sharing/api/v1/sharees endpoint. func (h *Handler) FindSharees(w http.ResponseWriter, r *http.Request) { log := appctx.GetLogger(r.Context()) term := r.URL.Query().Get("search") diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/group.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/group.go index ef979783fba..243150c2e2e 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/group.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/group.go @@ -26,7 +26,6 @@ import ( collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/pending.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/pending.go index c6646edb0d3..8c9705625f3 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/pending.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/pending.go @@ -33,13 +33,13 @@ import ( "google.golang.org/protobuf/types/known/fieldmaskpb" ) -// AcceptReceivedShare handles Post Requests on /apps/files_sharing/api/v1/shares/{shareid} +// AcceptReceivedShare handles Post Requests on /apps/files_sharing/api/v1/shares/{shareid}. func (h *Handler) AcceptReceivedShare(w http.ResponseWriter, r *http.Request) { shareID := chi.URLParam(r, "shareid") h.updateReceivedShare(w, r, shareID, false) } -// RejectReceivedShare handles DELETE Requests on /apps/files_sharing/api/v1/shares/{shareid} +// RejectReceivedShare handles DELETE Requests on /apps/files_sharing/api/v1/shares/{shareid}. func (h *Handler) RejectReceivedShare(w http.ResponseWriter, r *http.Request) { shareID := chi.URLParam(r, "shareid") h.updateReceivedShare(w, r, shareID, true) diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/public.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/public.go index 917a6d9d182..39ea398f488 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/public.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/public.go @@ -28,14 +28,13 @@ import ( link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/rs/zerolog/log" - "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" "github.com/cs3org/reva/pkg/appctx" "github.com/cs3org/reva/pkg/publicshare" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" "github.com/pkg/errors" + "github.com/rs/zerolog/log" ) func (h *Handler) createPublicLinkShare(w http.ResponseWriter, r *http.Request, statInfo *provider.ResourceInfo) { @@ -82,7 +81,6 @@ func (h *Handler) createPublicLinkShare(w http.ResponseWriter, r *http.Request, return } } - } newPermissions, err := permissionFromRequest(r, h) @@ -215,7 +213,6 @@ func (h *Handler) listPublicShares(r *http.Request, filters []*link.ListPublicSh log.Debug().Interface("share", share).Interface("info", info).Interface("shareData", share).Msg("mapped") ocsDataPayload = append(ocsDataPayload, sData) - } return ocsDataPayload, nil, nil @@ -520,7 +517,7 @@ func permissionFromRequest(r *http.Request, h *Handler) (*provider.ResourcePermi // TODO: add mapping for user share permissions to role -// Maps oc10 public link permissions to roles +// Maps oc10 public link permissions to roles. var ocPublicPermToRole = map[int]string{ // Recipients can view and download contents. 1: "viewer", diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/remote.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/remote.go index 038a8e6ca2b..d0e8b4e34cf 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/remote.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/remote.go @@ -29,11 +29,10 @@ import ( ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/go-chi/chi/v5" - "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" + "github.com/go-chi/chi/v5" ) func (h *Handler) createFederatedCloudShare(w http.ResponseWriter, r *http.Request, statInfo *provider.ResourceInfo, role *conversions.Role, roleVal []byte) { @@ -120,9 +119,8 @@ func (h *Handler) createFederatedCloudShare(w http.ResponseWriter, r *http.Reque response.WriteOCSSuccess(w, r, "OCM Share created") } -// GetFederatedShare handles GET requests on /apps/files_sharing/api/v1/shares/remote_shares/{shareid} +// GetFederatedShare handles GET requests on /apps/files_sharing/api/v1/shares/remote_shares/{shareid}. func (h *Handler) GetFederatedShare(w http.ResponseWriter, r *http.Request) { - // TODO: Implement response with HAL schemating ctx := r.Context() @@ -156,9 +154,8 @@ func (h *Handler) GetFederatedShare(w http.ResponseWriter, r *http.Request) { response.WriteOCSSuccess(w, r, share) } -// ListFederatedShares handles GET requests on /apps/files_sharing/api/v1/shares/remote_shares +// ListFederatedShares handles GET requests on /apps/files_sharing/api/v1/shares/remote_shares. func (h *Handler) ListFederatedShares(w http.ResponseWriter, r *http.Request) { - // TODO Implement pagination. // TODO Implement response with HAL schemating ctx := r.Context() diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/shares.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/shares.go index a44f7628216..f2a7324101a 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/shares.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/shares.go @@ -31,6 +31,7 @@ import ( "text/template" "time" + "github.com/ReneKroon/ttlcache/v2" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" @@ -38,10 +39,6 @@ import ( collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/go-chi/chi/v5" - "github.com/rs/zerolog" - - "github.com/ReneKroon/ttlcache/v2" "github.com/cs3org/reva/internal/http/services/owncloud/ocdav" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/config" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" @@ -55,14 +52,16 @@ import ( warmupreg "github.com/cs3org/reva/pkg/share/cache/warmup/registry" "github.com/cs3org/reva/pkg/utils" "github.com/cs3org/reva/pkg/utils/resourceid" + "github.com/go-chi/chi/v5" "github.com/pkg/errors" + "github.com/rs/zerolog" ) const ( storageIDPrefix string = "shared::" ) -// Handler implements the shares part of the ownCloud sharing API +// Handler implements the shares part of the ownCloud sharing API. type Handler struct { gatewayAddr string storageRegistryAddr string @@ -75,7 +74,7 @@ type Handler struct { resourceInfoCacheTTL time.Duration } -// we only cache the minimal set of data instead of the full user metadata +// we only cache the minimal set of data instead of the full user metadata. type userIdentifiers struct { DisplayName string Username string @@ -96,7 +95,7 @@ func getCacheManager(c *config.Config) (cache.ResourceInfoCache, error) { return nil, fmt.Errorf("driver not found: %s", c.ResourceInfoCacheDriver) } -// Init initializes this and any contained handlers +// Init initializes this and any contained handlers. func (h *Handler) Init(c *config.Config) { h.gatewayAddr = c.GatewaySvc h.storageRegistryAddr = c.StorageregistrySvc @@ -149,7 +148,7 @@ func (h *Handler) extractReference(r *http.Request) (provider.Reference, error) return ref, nil } -// CreateShare handles POST requests on /apps/files_sharing/api/v1/shares +// CreateShare handles POST requests on /apps/files_sharing/api/v1/shares. func (h *Handler) CreateShare(w http.ResponseWriter, r *http.Request) { ctx := r.Context() shareType, err := strconv.Atoi(r.FormValue("shareType")) @@ -290,10 +289,10 @@ func (h *Handler) extractPermissions(w http.ResponseWriter, r *http.Request, ri return role, val, nil } -// PublicShareContextName represent cross boundaries context for the name of the public share +// PublicShareContextName represent cross boundaries context for the name of the public share. type PublicShareContextName string -// GetShare handles GET requests on /apps/files_sharing/api/v1/shares/(shareid) +// GetShare handles GET requests on /apps/files_sharing/api/v1/shares/(shareid). func (h *Handler) GetShare(w http.ResponseWriter, r *http.Request) { var share *conversions.ShareData var resourceID *provider.ResourceId @@ -408,7 +407,7 @@ func (h *Handler) GetShare(w http.ResponseWriter, r *http.Request) { response.WriteOCSSuccess(w, r, []*conversions.ShareData{share}) } -// UpdateShare handles PUT requests on /apps/files_sharing/api/v1/shares/(shareid) +// UpdateShare handles PUT requests on /apps/files_sharing/api/v1/shares/(shareid). func (h *Handler) UpdateShare(w http.ResponseWriter, r *http.Request) { shareID := chi.URLParam(r, "shareid") // FIXME: isPublicShare is already doing a GetShare and GetPublicShare, @@ -516,7 +515,7 @@ func (h *Handler) updateShare(w http.ResponseWriter, r *http.Request, shareID st response.WriteOCSSuccess(w, r, share) } -// RemoveShare handles DELETE requests on /apps/files_sharing/api/v1/shares/(shareid) +// RemoveShare handles DELETE requests on /apps/files_sharing/api/v1/shares/(shareid). func (h *Handler) RemoveShare(w http.ResponseWriter, r *http.Request) { shareID := chi.URLParam(r, "shareid") switch { @@ -530,7 +529,7 @@ func (h *Handler) RemoveShare(w http.ResponseWriter, r *http.Request) { } } -// ListShares handles GET requests on /apps/files_sharing/api/v1/shares +// ListShares handles GET requests on /apps/files_sharing/api/v1/shares. func (h *Handler) ListShares(w http.ResponseWriter, r *http.Request) { if r.FormValue("shared_with_me") != "" { var err error @@ -712,7 +711,7 @@ func (h *Handler) listSharesWithMe(w http.ResponseWriter, r *http.Request) { // can we return the mountpoint when the gateway resolves the listing of shares? // - no, the gateway only sees the same list any has the same options as the ocs service - // - we would need to have a list of mountpoints for the shares -> owncloudstorageprovider for hot migration migration + // - we would need to have a list of mountpoints for the shares -> owncloudstorageprovider for hot migration // best we can do for now is stat the /Shares jail if it is set and return those paths @@ -912,7 +911,7 @@ func (h *Handler) addFileInfo(ctx context.Context, s *conversions.ShareData, inf return nil } -// mustGetIdentifiers always returns a struct with identifiers, if the user or group could not be found they will all be empty +// mustGetIdentifiers always returns a struct with identifiers, if the user or group could not be found they will all be empty. func (h *Handler) mustGetIdentifiers(ctx context.Context, client gateway.GatewayAPIClient, id string, isGroup bool) *userIdentifiers { log := appctx.GetLogger(ctx).With().Str("id", id).Logger() if id == "" { diff --git a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/user.go b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/user.go index 59bc498f468..061b037e383 100644 --- a/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/user.go +++ b/internal/http/services/owncloud/ocs/handlers/apps/sharing/shares/user.go @@ -26,7 +26,6 @@ import ( collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" "github.com/cs3org/reva/pkg/appctx" diff --git a/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go b/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go index edf85ee6dae..ef421b8460d 100644 --- a/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go +++ b/internal/http/services/owncloud/ocs/handlers/cloud/capabilities/capabilities.go @@ -26,7 +26,7 @@ import ( "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" ) -// Handler renders the capability endpoint +// Handler renders the capability endpoint. type Handler struct { c data.CapabilitiesData defaultUploadProtocol string @@ -34,7 +34,7 @@ type Handler struct { groupBasedCapabilities map[string][]string } -// Init initializes this and any contained handlers +// Init initializes this and any contained handlers. func (h *Handler) Init(c *config.Config) { h.c = c.Capabilities h.defaultUploadProtocol = c.DefaultUploadProtocol @@ -233,10 +233,9 @@ func (h *Handler) Init(c *config.Config) { // upload protocol-specific details setCapabilitiesForChunkProtocol(chunkProtocol(h.defaultUploadProtocol), h.c.Capabilities) - } -// Handler renders the capabilities +// GetCapabilities renders the capabilities. func (h *Handler) GetCapabilities(w http.ResponseWriter, r *http.Request) { c := h.getCapabilitiesForUserAgent(r.Context(), r.UserAgent()) response.WriteOCSSuccess(w, r, c) diff --git a/internal/http/services/owncloud/ocs/handlers/cloud/user/user.go b/internal/http/services/owncloud/ocs/handlers/cloud/user/user.go index 22c71908460..d8df9543e55 100644 --- a/internal/http/services/owncloud/ocs/handlers/cloud/user/user.go +++ b/internal/http/services/owncloud/ocs/handlers/cloud/user/user.go @@ -27,11 +27,11 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" ) -// The Handler renders the user endpoint +// The Handler renders the user endpoint. type Handler struct { } -// GetSelf handles GET requests on /cloud/user +// GetSelf handles GET requests on /cloud/user. func (h *Handler) GetSelf(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -50,7 +50,7 @@ func (h *Handler) GetSelf(w http.ResponseWriter, r *http.Request) { }) } -// User holds user data +// User holds user data. type User struct { // TODO needs better naming, clarify if we need a userid, a username or both ID string `json:"id" xml:"id"` diff --git a/internal/http/services/owncloud/ocs/handlers/cloud/users/users.go b/internal/http/services/owncloud/ocs/handlers/cloud/users/users.go index 6a49ff56e94..e9385fd5430 100644 --- a/internal/http/services/owncloud/ocs/handlers/cloud/users/users.go +++ b/internal/http/services/owncloud/ocs/handlers/cloud/users/users.go @@ -36,23 +36,23 @@ import ( "github.com/go-chi/chi/v5" ) -// Handler renders user data for the user id given in the url path +// Handler renders user data for the user id given in the url path. type Handler struct { gatewayAddr string } -// Init initializes this and any contained handlers +// Init initializes this and any contained handlers. func (h *Handler) Init(c *config.Config) { h.gatewayAddr = c.GatewaySvc } // GetGroups handles GET requests on /cloud/users/groups -// TODO: implement +// TODO: implement. func (h *Handler) GetGroups(w http.ResponseWriter, r *http.Request) { response.WriteOCSSuccess(w, r, &Groups{}) } -// Quota holds quota information +// Quota holds quota information. type Quota struct { Free int64 `json:"free" xml:"free"` Used int64 `json:"used" xml:"used"` @@ -61,7 +61,7 @@ type Quota struct { Definition string `json:"definition" xml:"definition"` } -// Users holds users data +// Users holds users data. type Users struct { Quota *Quota `json:"quota" xml:"quota"` Email string `json:"email" xml:"email"` @@ -72,14 +72,14 @@ type Users struct { TwoFactorAuthEnabled bool `json:"two_factor_auth_enabled" xml:"two_factor_auth_enabled"` } -// Groups holds group data +// Groups holds group data. type Groups struct { Groups []string `json:"groups" xml:"groups>element"` } // GetUsers handles GET requests on /cloud/users // Only allow self-read currently. TODO: List Users and Get on other users (both require -// administrative privileges) +// administrative privileges). func (h *Handler) GetUsers(w http.ResponseWriter, r *http.Request) { ctx := r.Context() sublog := appctx.GetLogger(r.Context()) diff --git a/internal/http/services/owncloud/ocs/handlers/config/config.go b/internal/http/services/owncloud/ocs/handlers/config/config.go index 852e12b8133..e9076d08358 100644 --- a/internal/http/services/owncloud/ocs/handlers/config/config.go +++ b/internal/http/services/owncloud/ocs/handlers/config/config.go @@ -26,12 +26,12 @@ import ( "github.com/cs3org/reva/internal/http/services/owncloud/ocs/response" ) -// Handler renders the config endpoint +// Handler renders the config endpoint. type Handler struct { c data.ConfigData } -// Init initializes this and any contained handlers +// Init initializes this and any contained handlers. func (h *Handler) Init(c *config.Config) { h.c = c.Config // config @@ -52,7 +52,7 @@ func (h *Handler) Init(c *config.Config) { } } -// Handler renders the config +// GetConfig renders the config. func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) { response.WriteOCSSuccess(w, r, h.c) } diff --git a/internal/http/services/owncloud/ocs/response/response.go b/internal/http/services/owncloud/ocs/response/response.go index f92af90875f..7959181261c 100644 --- a/internal/http/services/owncloud/ocs/response/response.go +++ b/internal/http/services/owncloud/ocs/response/response.go @@ -40,12 +40,12 @@ var ( defaultStatusCodeMapper = OcsV2StatusCodes ) -// Response is the top level response structure +// Response is the top level response structure. type Response struct { OCS *Payload `json:"ocs"` } -// Payload combines response metadata and data +// Payload combines response metadata and data. type Payload struct { XMLName struct{} `json:"-" xml:"ocs"` Meta Meta `json:"meta" xml:"meta"` @@ -59,7 +59,7 @@ var ( dataName = xml.Name{Local: "data"} ) -// MarshalXML handles ocs specific wrapping of array members in 'element' tags for the data +// MarshalXML handles ocs specific wrapping of array members in 'element' tags for the data. func (p Payload) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) { // first the easy part // use ocs as the surrounding tag @@ -100,7 +100,7 @@ func (p Payload) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) return } -// Meta holds response metadata +// Meta holds response metadata. type Meta struct { Status string `json:"status" xml:"status"` StatusCode int `json:"statuscode" xml:"statuscode"` @@ -109,35 +109,35 @@ type Meta struct { ItemsPerPage string `json:"itemsperpage,omitempty" xml:"itemsperpage,omitempty"` } -// MetaOK is the default ok response +// MetaOK is the default ok response. var MetaOK = Meta{Status: "ok", StatusCode: 100, Message: "OK"} -// MetaBadRequest is used for unknown errors +// MetaBadRequest is used for unknown errors. var MetaBadRequest = Meta{Status: "error", StatusCode: 400, Message: "Bad Request"} -// MetaServerError is returned on server errors +// MetaServerError is returned on server errors. var MetaServerError = Meta{Status: "error", StatusCode: 996, Message: "Server Error"} -// MetaUnauthorized is returned on unauthorized requests +// MetaUnauthorized is returned on unauthorized requests. var MetaUnauthorized = Meta{Status: "error", StatusCode: 997, Message: "Unauthorised"} -// MetaNotFound is returned when trying to access not existing resources +// MetaNotFound is returned when trying to access not existing resources. var MetaNotFound = Meta{Status: "error", StatusCode: 998, Message: "Not Found"} -// MetaUnknownError is used for unknown errors +// MetaUnknownError is used for unknown errors. var MetaUnknownError = Meta{Status: "error", StatusCode: 999, Message: "Unknown Error"} -// WriteOCSSuccess handles writing successful ocs response data +// WriteOCSSuccess handles writing successful ocs response data. func WriteOCSSuccess(w http.ResponseWriter, r *http.Request, d interface{}) { WriteOCSData(w, r, MetaOK, d, nil) } -// WriteOCSError handles writing error ocs responses +// WriteOCSError handles writing error ocs responses. func WriteOCSError(w http.ResponseWriter, r *http.Request, c int, m string, err error) { WriteOCSData(w, r, Meta{Status: "error", StatusCode: c, Message: m}, nil, err) } -// WriteOCSData handles writing ocs data in json and xml +// WriteOCSData handles writing ocs data in json and xml. func WriteOCSData(w http.ResponseWriter, r *http.Request, m Meta, d interface{}, err error) { WriteOCSResponse(w, r, Response{ OCS: &Payload{ @@ -147,7 +147,7 @@ func WriteOCSData(w http.ResponseWriter, r *http.Request, m Meta, d interface{}, }, err) } -// WriteOCSResponse handles writing ocs responses in json and xml +// WriteOCSResponse handles writing ocs responses in json and xml. func WriteOCSResponse(w http.ResponseWriter, r *http.Request, res Response, err error) { if err != nil { appctx.GetLogger(r.Context()).Error().Err(err).Msg(res.OCS.Meta.Message) diff --git a/internal/http/services/preferences/preferences.go b/internal/http/services/preferences/preferences.go index 7ae1d3221a1..622d29396ed 100644 --- a/internal/http/services/preferences/preferences.go +++ b/internal/http/services/preferences/preferences.go @@ -37,7 +37,7 @@ func init() { global.Register("preferences", New) } -// Config holds the config options that for the preferences HTTP service +// Config holds the config options that for the preferences HTTP service. type Config struct { Prefix string `mapstructure:"prefix"` GatewaySvc string `mapstructure:"gatewaysvc"` @@ -55,9 +55,8 @@ type svc struct { router *chi.Mux } -// New returns a new ocmd object +// New returns a new ocmd object. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { - conf := &Config{} if err := mapstructure.Decode(m, conf); err != nil { return nil, err @@ -116,7 +115,6 @@ func (s *svc) handleGet(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } return - } client, err := pool.GetGatewayServiceClient(pool.Endpoint(s.conf.GatewaySvc)) @@ -164,7 +162,6 @@ func (s *svc) handleGet(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) return } - } func (s *svc) handlePost(w http.ResponseWriter, r *http.Request) { @@ -182,7 +179,6 @@ func (s *svc) handlePost(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } return - } client, err := pool.GetGatewayServiceClient(pool.Endpoint(s.conf.GatewaySvc)) diff --git a/internal/http/services/prometheus/prometheus.go b/internal/http/services/prometheus/prometheus.go index 14b6b9ed2f6..832d67e3fe0 100644 --- a/internal/http/services/prometheus/prometheus.go +++ b/internal/http/services/prometheus/prometheus.go @@ -22,19 +22,18 @@ import ( "net/http" "contrib.go.opencensus.io/exporter/prometheus" + "github.com/cs3org/reva/pkg/rhttp/global" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "github.com/rs/zerolog" "go.opencensus.io/stats/view" - - "github.com/cs3org/reva/pkg/rhttp/global" ) func init() { global.Register("prometheus", New) } -// New returns a new prometheus service +// New returns a new prometheus service. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/reverseproxy/reverseproxy.go b/internal/http/services/reverseproxy/reverseproxy.go index 6439667ee67..fa7e84e294e 100644 --- a/internal/http/services/reverseproxy/reverseproxy.go +++ b/internal/http/services/reverseproxy/reverseproxy.go @@ -55,7 +55,7 @@ type svc struct { router *chi.Mux } -// New returns an instance of the reverse proxy service +// New returns an instance of the reverse proxy service. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/internal/http/services/siteacc/siteacc.go b/internal/http/services/siteacc/siteacc.go index 8bed2526ba9..1163b95d503 100644 --- a/internal/http/services/siteacc/siteacc.go +++ b/internal/http/services/siteacc/siteacc.go @@ -21,13 +21,12 @@ package siteacc import ( "net/http" + "github.com/cs3org/reva/pkg/rhttp/global" "github.com/cs3org/reva/pkg/siteacc" "github.com/cs3org/reva/pkg/siteacc/config" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "github.com/rs/zerolog" - - "github.com/cs3org/reva/pkg/rhttp/global" ) func init() { diff --git a/internal/http/services/sysinfo/sysinfo.go b/internal/http/services/sysinfo/sysinfo.go index 65ce0d7949d..c8e69e98e39 100644 --- a/internal/http/services/sysinfo/sysinfo.go +++ b/internal/http/services/sysinfo/sysinfo.go @@ -21,13 +21,12 @@ package sysinfo import ( "net/http" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/appctx" "github.com/cs3org/reva/pkg/rhttp/global" "github.com/cs3org/reva/pkg/sysinfo" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" + "github.com/rs/zerolog" ) func init() { diff --git a/internal/http/services/wellknown/wellknown.go b/internal/http/services/wellknown/wellknown.go index 524cc4cffd9..2ef81bd5d4f 100644 --- a/internal/http/services/wellknown/wellknown.go +++ b/internal/http/services/wellknown/wellknown.go @@ -55,7 +55,7 @@ type svc struct { handler http.Handler } -// New returns a new webuisvc +// New returns a new webuisvc. func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { diff --git a/pkg/app/app.go b/pkg/app/app.go index 50e6ce28d8b..b4874d0cef2 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -27,7 +27,7 @@ import ( ) // Registry is the interface that application registries implement -// for discovering application providers +// for discovering application providers. type Registry interface { FindProviders(ctx context.Context, mimeType string) ([]*registry.ProviderInfo, error) ListProviders(ctx context.Context) ([]*registry.ProviderInfo, error) diff --git a/pkg/app/provider/loader/loader.go b/pkg/app/provider/loader/loader.go index f373136de9c..fc7dcf87c5c 100644 --- a/pkg/app/provider/loader/loader.go +++ b/pkg/app/provider/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load core application providers. _ "github.com/cs3org/reva/pkg/app/provider/demo" _ "github.com/cs3org/reva/pkg/app/provider/wopi" - // Add your own here + // Add your own here. ) diff --git a/pkg/app/provider/wopi/wopi.go b/pkg/app/provider/wopi/wopi.go index 7f0d096dc46..08b70a698b4 100644 --- a/pkg/app/provider/wopi/wopi.go +++ b/pkg/app/provider/wopi/wopi.go @@ -390,7 +390,6 @@ func parseWopiDiscovery(body io.Reader) (map[string]map[string]string, error) { } for _, netzone := range root.SelectElements("net-zone") { - if strings.Contains(netzone.SelectAttrValue("name", ""), "external") { for _, app := range netzone.SelectElements("app") { for _, action := range app.SelectElements("action") { diff --git a/pkg/app/registry/loader/loader.go b/pkg/app/registry/loader/loader.go index 7c06a89f925..fa18c262c46 100644 --- a/pkg/app/registry/loader/loader.go +++ b/pkg/app/registry/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load core app registry drivers. _ "github.com/cs3org/reva/pkg/app/registry/static" - // Add your own here + // Add your own here. ) diff --git a/pkg/app/registry/static/static.go b/pkg/app/registry/static/static.go index 255627b0b7f..520d73e8d94 100644 --- a/pkg/app/registry/static/static.go +++ b/pkg/app/registry/static/static.go @@ -120,7 +120,7 @@ func New(m map[string]interface{}) (app.Registry, error) { } // remove a provider from the provider list in a mime type -// it's a no-op if the provider is not in the list of providers in the mime type +// it's a no-op if the provider is not in the list of providers in the mime type. func unregisterProvider(p *registrypb.ProviderInfo, mime *mimeTypeConfig) { if index, in := getIndex(mime.apps, p); in { // remove the provider from the list @@ -231,7 +231,6 @@ func (m *manager) ListSupportedMimeTypes(ctx context.Context) ([]*registrypb.Mim res := make([]*registrypb.MimeTypeInfo, 0, m.mimetypes.Len()) for pair := m.mimetypes.Oldest(); pair != nil; pair = pair.Next() { - mime := pair.Value.(*mimeTypeConfig) res = append(res, ®istrypb.MimeTypeInfo{ @@ -244,7 +243,6 @@ func (m *manager) ListSupportedMimeTypes(ctx context.Context) ([]*registrypb.Mim AllowCreation: mime.AllowCreation, DefaultApplication: mime.DefaultApp, }) - } return res, nil @@ -332,7 +330,7 @@ func equalsProviderInfo(p1, p2 *registrypb.ProviderInfo) bool { return p1.Name == p2.Name } -// check that all providers in the two lists are equals +// check that all providers in the two lists are equals. func providersEquals(l1, l2 []*registrypb.ProviderInfo) bool { if len(l1) != len(l2) { return false diff --git a/pkg/app/registry/static/static_test.go b/pkg/app/registry/static/static_test.go index f23d4005c58..2dc46072b5f 100644 --- a/pkg/app/registry/static/static_test.go +++ b/pkg/app/registry/static/static_test.go @@ -29,7 +29,6 @@ import ( ) func TestFindProviders(t *testing.T) { - testCases := []struct { name string mimeTypes []*mimeTypeConfig @@ -173,9 +172,7 @@ func TestFindProviders(t *testing.T) { } for _, tt := range testCases { - t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() registry, err := New(map[string]interface{}{ @@ -196,15 +193,11 @@ func TestFindProviders(t *testing.T) { if !providersEquals(providers, tt.expectedRes) { t.Errorf("providers list different from expected: \n\tgot=%v\n\texp=%v", providers, tt.expectedRes) } - }) - } - } func TestFindProvidersWithPriority(t *testing.T) { - testCases := []struct { name string mimeTypes []*mimeTypeConfig @@ -478,9 +471,7 @@ func TestFindProvidersWithPriority(t *testing.T) { } for _, tt := range testCases { - t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() registry, err := New(map[string]interface{}{ @@ -508,15 +499,11 @@ func TestFindProvidersWithPriority(t *testing.T) { if !providersEquals(providers, tt.expectedRes) { t.Errorf("providers list different from expected: \n\tgot=%v\n\texp=%v", providers, tt.expectedRes) } - }) - } - } func TestAddProvider(t *testing.T) { - testCases := []struct { name string mimeTypes []*mimeTypeConfig @@ -774,7 +761,6 @@ func TestAddProvider(t *testing.T) { for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() registry, err := New(map[string]interface{}{ @@ -812,10 +798,8 @@ func TestAddProvider(t *testing.T) { t.Errorf("list of addresses different from expected: \n\tgot=%v\n\texp=%v", addrsReg, expAddrs) } } - }) } - } func TestListSupportedMimeTypes(t *testing.T) { @@ -1028,7 +1012,6 @@ func TestListSupportedMimeTypes(t *testing.T) { for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() registry, err := New(map[string]interface{}{ @@ -1054,7 +1037,6 @@ func TestListSupportedMimeTypes(t *testing.T) { if !mimeTypesEquals(got, tt.expected) { t.Errorf("mime types list different from expected: \n\tgot=%v\n\texp=%v", got, tt.expected) } - }) } } @@ -1157,7 +1139,6 @@ func TestSetDefaultProviderForMimeType(t *testing.T) { for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() registry, err := New(map[string]interface{}{ @@ -1190,7 +1171,6 @@ func TestSetDefaultProviderForMimeType(t *testing.T) { if !equalsProviderInfo(got, tt.newDefault.provider) { t.Errorf("provider differ from expected:\n\tgot=%v\n\texp=%v", got, tt.newDefault.provider) } - }) } } diff --git a/pkg/appauth/manager/json/json_test.go b/pkg/appauth/manager/json/json_test.go index 428fa6d9a6c..b759b4ef821 100644 --- a/pkg/appauth/manager/json/json_test.go +++ b/pkg/appauth/manager/json/json_test.go @@ -136,7 +136,6 @@ func TestNewManager(t *testing.T) { } }) } - } func TestGenerateAppPassword(t *testing.T) { @@ -284,10 +283,8 @@ func TestGenerateAppPassword(t *testing.T) { if !reflect.DeepEqual(jsonState, test.expectedState) { t.Fatalf("json state differ: expected=%v got=%v", render.AsCode(jsonState), render.AsCode(test.expectedState)) } - }) } - } func TestListAppPasswords(t *testing.T) { @@ -412,10 +409,8 @@ func TestListAppPasswords(t *testing.T) { if !reflect.DeepEqual(pws, test.expectedState) { t.Fatalf("list passwords differ: expected=%v got=%v", test.expectedState, pws) } - }) } - } func TestInvalidateAppPassword(t *testing.T) { @@ -538,10 +533,8 @@ func TestInvalidateAppPassword(t *testing.T) { if !reflect.DeepEqual(test.expectedState, manager.(*jsonManager).passwords) { t.Fatalf("apppauth state differ: expected=%v got=%v", render.AsCode(test.expectedState), render.AsCode(manager.(*jsonManager).passwords)) } - }) } - } func TestGetAppPassword(t *testing.T) { @@ -695,7 +688,6 @@ func TestGetAppPassword(t *testing.T) { if !reflect.DeepEqual(test.expectedState, pw) { t.Fatalf("apppauth state differ: expected=%v got=%v", render.AsCode(test.expectedState), render.AsCode(pw)) } - }) } } diff --git a/pkg/appauth/manager/loader/loader.go b/pkg/appauth/manager/loader/loader.go index ffe3ce1a187..2293f265890 100644 --- a/pkg/appauth/manager/loader/loader.go +++ b/pkg/appauth/manager/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load core application auth manager drivers. _ "github.com/cs3org/reva/pkg/appauth/manager/json" - // Add your own here + // Add your own here. ) diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index a3cd390338e..67ddf5d7c2a 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -28,7 +28,7 @@ import ( "github.com/cs3org/reva/pkg/plugin" ) -// Manager is the interface to implement to authenticate users +// Manager is the interface to implement to authenticate users. type Manager interface { plugin.Plugin Authenticate(ctx context.Context, clientID, clientSecret string) (*user.User, map[string]*authpb.Scope, error) @@ -59,7 +59,7 @@ type TokenWriter interface { } // Registry is the interface that auth registries implement -// for discovering auth providers +// for discovering auth providers. type Registry interface { ListProviders(ctx context.Context) ([]*registry.ProviderInfo, error) GetProvider(ctx context.Context, authType string) (*registry.ProviderInfo, error) diff --git a/pkg/auth/manager/demo/demo.go b/pkg/auth/manager/demo/demo.go index c3a23790ca8..3f9fcffdbfa 100644 --- a/pkg/auth/manager/demo/demo.go +++ b/pkg/auth/manager/demo/demo.go @@ -37,7 +37,7 @@ type manager struct { credentials map[string]Credentials } -// Credentials holds a pair of secret and userid +// Credentials holds a pair of secret and userid. type Credentials struct { User *user.User Secret string diff --git a/pkg/auth/manager/demo/demo_test.go b/pkg/auth/manager/demo/demo_test.go index 2b73d153c92..14d8cff2b8c 100644 --- a/pkg/auth/manager/demo/demo_test.go +++ b/pkg/auth/manager/demo/demo_test.go @@ -40,5 +40,4 @@ func TestUserManager(t *testing.T) { if err == nil { t.Fatalf("no error (but we expected one) while authenticate with bad credentials") } - } diff --git a/pkg/auth/manager/json/json.go b/pkg/auth/manager/json/json.go index bf66c465ebe..d403b311ed2 100644 --- a/pkg/auth/manager/json/json.go +++ b/pkg/auth/manager/json/json.go @@ -38,7 +38,7 @@ func init() { registry.Register("json", New) } -// Credentials holds a pair of secret and userid +// Credentials holds a pair of secret and userid. type Credentials struct { ID *user.UserId `mapstructure:"id" json:"id"` Username string `mapstructure:"username" json:"username"` diff --git a/pkg/auth/manager/ldap/ldap.go b/pkg/auth/manager/ldap/ldap.go index 900d272daf5..450780ac42d 100644 --- a/pkg/auth/manager/ldap/ldap.go +++ b/pkg/auth/manager/ldap/ldap.go @@ -76,7 +76,7 @@ type attributes struct { GIDNumber string `mapstructure:"gidNumber"` } -// Default attributes (Active Directory) +// Default attributes (Active Directory). var ldapDefaults = attributes{ DN: "dn", UID: "ms-DS-ConsistencyGuid", // you can fall back to objectguid or even samaccountname but you will run into trouble when user names change. You have been warned. @@ -228,7 +228,6 @@ func (am *mgr) Authenticate(ctx context.Context, clientID, clientSecret string) log.Debug().Interface("entry", sr.Entries[0]).Interface("user", u).Msg("authenticated user") return u, scopes, nil - } func (am *mgr) getLoginFilter(login string) string { diff --git a/pkg/auth/manager/loader/loader.go b/pkg/auth/manager/loader/loader.go index 69862bc1446..97b9882d8d1 100644 --- a/pkg/auth/manager/loader/loader.go +++ b/pkg/auth/manager/loader/loader.go @@ -30,5 +30,5 @@ import ( _ "github.com/cs3org/reva/pkg/auth/manager/oidc" _ "github.com/cs3org/reva/pkg/auth/manager/owncloudsql" _ "github.com/cs3org/reva/pkg/auth/manager/publicshares" - // Add your own here + // Add your own here. ) diff --git a/pkg/auth/manager/machine/machine.go b/pkg/auth/manager/machine/machine.go index a124bbba478..94509ab747a 100644 --- a/pkg/auth/manager/machine/machine.go +++ b/pkg/auth/manager/machine/machine.go @@ -38,7 +38,7 @@ import ( // To impersonate the given user it's only needed an api-key, saved // in a config file. -// supported claims +// supported claims. var claims = []string{"mail", "uid", "username", "gid", "userid"} type manager struct { @@ -50,7 +50,7 @@ func init() { registry.Register("machine", New) } -// Configure parses the map conf +// Configure parses the map conf. func (m *manager) Configure(conf map[string]interface{}) error { err := mapstructure.Decode(conf, m) if err != nil { @@ -59,7 +59,7 @@ func (m *manager) Configure(conf map[string]interface{}) error { return nil } -// New creates a new manager for the 'machine' authentication +// New creates a new manager for the 'machine' authentication. func New(conf map[string]interface{}) (auth.Manager, error) { m := &manager{} err := m.Configure(conf) @@ -69,7 +69,7 @@ func New(conf map[string]interface{}) (auth.Manager, error) { return m, nil } -// Authenticate impersonate an user if the provided secret is equal to the api-key +// Authenticate impersonate an user if the provided secret is equal to the api-key. func (m *manager) Authenticate(ctx context.Context, user, secret string) (*userpb.User, map[string]*authpb.Scope, error) { if m.APIKey != secret { return nil, nil, errtypes.InvalidCredentials("") @@ -104,7 +104,6 @@ func (m *manager) Authenticate(ctx context.Context, user, secret string) (*userp } return userResponse.GetUser(), scope, nil - } func contains(lst []string, s string) bool { diff --git a/pkg/auth/manager/nextcloud/nextcloud.go b/pkg/auth/manager/nextcloud/nextcloud.go index 5d01d264b15..8ca2bb534d4 100644 --- a/pkg/auth/manager/nextcloud/nextcloud.go +++ b/pkg/auth/manager/nextcloud/nextcloud.go @@ -47,14 +47,14 @@ type Manager struct { endPoint string } -// AuthManagerConfig contains config for a Nextcloud-based AuthManager +// AuthManagerConfig contains config for a Nextcloud-based AuthManager. type AuthManagerConfig struct { EndPoint string `mapstructure:"endpoint" docs:";The Nextcloud backend endpoint for user check"` SharedSecret string `mapstructure:"shared_secret"` MockHTTP bool `mapstructure:"mock_http"` } -// Action describes a REST request to forward to the Nextcloud backend +// Action describes a REST request to forward to the Nextcloud backend. type Action struct { verb string username string @@ -84,7 +84,7 @@ func New(m map[string]interface{}) (auth.Manager, error) { return NewAuthManager(c) } -// NewAuthManager returns a new Nextcloud-based AuthManager +// NewAuthManager returns a new Nextcloud-based AuthManager. func NewAuthManager(c *AuthManagerConfig) (*Manager, error) { var client *http.Client if c.MockHTTP { @@ -113,7 +113,7 @@ func (am *Manager) Configure(ml map[string]interface{}) error { return nil } -// SetHTTPClient sets the HTTP client +// SetHTTPClient sets the HTTP client. func (am *Manager) SetHTTPClient(c *http.Client) { am.client = c } diff --git a/pkg/auth/manager/nextcloud/nextcloud_server_mock.go b/pkg/auth/manager/nextcloud/nextcloud_server_mock.go index f81e2fcec5b..ecef3d41e57 100644 --- a/pkg/auth/manager/nextcloud/nextcloud_server_mock.go +++ b/pkg/auth/manager/nextcloud/nextcloud_server_mock.go @@ -29,7 +29,7 @@ import ( ) // Response contains data for the Nextcloud mock server to respond -// and to switch to a new server state +// and to switch to a new server state. type Response struct { code int body string @@ -46,7 +46,7 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~einstein/api/auth/Authenticate {"clientID":"einstein","clientSecret":"relativity"}`: {200, `{"user":{"id":{"idp":"some-idp","opaque_id":"some-opaque-user-id","type":1}},"scopes":{"user":{"resource":{"decoder":"json","value":"eyJyZXNvdXJjZV9pZCI6eyJzdG9yYWdlX2lkIjoic3RvcmFnZS1pZCIsIm9wYXF1ZV9pZCI6Im9wYXF1ZS1pZCJ9LCJwYXRoIjoic29tZS9maWxlL3BhdGgudHh0In0="},"role":1}}}`, serverStateHome}, } -// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server +// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server. func GetNextcloudServerMock(called *[]string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf := new(strings.Builder) diff --git a/pkg/auth/manager/nextcloud/nextcloud_test.go b/pkg/auth/manager/nextcloud/nextcloud_test.go index e7f7bdfa846..03b6dedf304 100644 --- a/pkg/auth/manager/nextcloud/nextcloud_test.go +++ b/pkg/auth/manager/nextcloud/nextcloud_test.go @@ -23,19 +23,16 @@ import ( "fmt" "os" - "google.golang.org/grpc/metadata" - authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/cs3org/reva/pkg/auth/manager/nextcloud" "github.com/cs3org/reva/pkg/auth/scope" ctxpkg "github.com/cs3org/reva/pkg/ctx" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/grpc/metadata" ) func setUpNextcloudServer() (*nextcloud.Manager, *[]string, func()) { diff --git a/pkg/auth/manager/oidc/oidc.go b/pkg/auth/manager/oidc/oidc.go index c23aa30ba32..9d0484bbba9 100644 --- a/pkg/auth/manager/oidc/oidc.go +++ b/pkg/auth/manager/oidc/oidc.go @@ -278,7 +278,7 @@ func (am *mgr) getOAuthCtx(ctx context.Context) context.Context { return ctx } -// getOIDCProvider returns a singleton OIDC provider +// getOIDCProvider returns a singleton OIDC provider. func (am *mgr) getOIDCProvider(ctx context.Context) (*oidc.Provider, error) { ctx = am.getOAuthCtx(ctx) log := appctx.GetLogger(ctx) diff --git a/pkg/auth/manager/owncloudsql/accounts/accounts.go b/pkg/auth/manager/owncloudsql/accounts/accounts.go index 1489669892a..ca03938a6fc 100644 --- a/pkg/auth/manager/owncloudsql/accounts/accounts.go +++ b/pkg/auth/manager/owncloudsql/accounts/accounts.go @@ -28,7 +28,7 @@ import ( "github.com/pkg/errors" ) -// Accounts represents oc10-style Accounts +// Accounts represents oc10-style Accounts. type Accounts struct { driver string db *sql.DB @@ -36,7 +36,7 @@ type Accounts struct { selectSQL string } -// NewMysql returns a new accounts instance connecting to a MySQL database +// NewMysql returns a new accounts instance connecting to a MySQL database. func NewMysql(dsn string, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) { sqldb, err := sql.Open("mysql", dsn) if err != nil { @@ -54,9 +54,8 @@ func NewMysql(dsn string, joinUsername, joinUUID, enableMedialSearch bool) (*Acc return New("mysql", sqldb, joinUsername, joinUUID, enableMedialSearch) } -// New returns a new accounts instance connecting to the given sql.DB +// New returns a new accounts instance connecting to the given sql.DB. func New(driver string, sqldb *sql.DB, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) { - sel := "SELECT id, email, user_id, display_name, quota, last_login, backend, home, state, password" from := ` FROM oc_accounts a @@ -120,12 +119,12 @@ func (as *Accounts) rowToAccount(ctx context.Context, row Scannable) (*Account, return &a, nil } -// Scannable describes the interface providing a Scan method +// Scannable describes the interface providing a Scan method. type Scannable interface { Scan(...interface{}) error } -// GetAccountByLogin fetches an account by mail or username +// GetAccountByLogin fetches an account by mail or username. func (as *Accounts) GetAccountByLogin(ctx context.Context, login string) (*Account, error) { var row *sql.Row username := strings.ToLower(login) // usernames are lowercased in owncloud classic @@ -138,7 +137,7 @@ func (as *Accounts) GetAccountByLogin(ctx context.Context, login string) (*Accou return as.rowToAccount(ctx, row) } -// GetAccountGroups reads the groups for an account +// GetAccountGroups reads the groups for an account. func (as *Accounts) GetAccountGroups(ctx context.Context, uid string) ([]string, error) { rows, err := as.db.QueryContext(ctx, "SELECT gid FROM oc_group_user WHERE uid=?", uid) if err != nil { diff --git a/pkg/auth/manager/owncloudsql/accounts/accounts_test.go b/pkg/auth/manager/owncloudsql/accounts/accounts_test.go index 320a291ccad..6998b235d8e 100644 --- a/pkg/auth/manager/owncloudsql/accounts/accounts_test.go +++ b/pkg/auth/manager/owncloudsql/accounts/accounts_test.go @@ -23,10 +23,8 @@ import ( "database/sql" "os" - _ "github.com/mattn/go-sqlite3" - "github.com/cs3org/reva/pkg/auth/manager/owncloudsql/accounts" - + _ "github.com/mattn/go-sqlite3" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -34,30 +32,30 @@ import ( var _ = Describe("Accounts", func() { var ( conn *accounts.Accounts - testDbFile *os.File + testDBFile *os.File sqldb *sql.DB ) BeforeEach(func() { var err error - testDbFile, err = os.CreateTemp("", "example") + testDBFile, err = os.CreateTemp("", "example") Expect(err).ToNot(HaveOccurred()) dbData, err := os.ReadFile("test.sqlite") Expect(err).ToNot(HaveOccurred()) - _, err = testDbFile.Write(dbData) + _, err = testDBFile.Write(dbData) Expect(err).ToNot(HaveOccurred()) - err = testDbFile.Close() + err = testDBFile.Close() Expect(err).ToNot(HaveOccurred()) - sqldb, err = sql.Open("sqlite3", testDbFile.Name()) + sqldb, err = sql.Open("sqlite3", testDBFile.Name()) Expect(err).ToNot(HaveOccurred()) }) AfterEach(func() { - os.Remove(testDbFile.Name()) + os.Remove(testDBFile.Name()) }) Describe("GetAccountByLogin", func() { diff --git a/pkg/auth/manager/owncloudsql/owncloudsql.go b/pkg/auth/manager/owncloudsql/owncloudsql.go index 65bba2c5a35..ad218a966bf 100644 --- a/pkg/auth/manager/owncloudsql/owncloudsql.go +++ b/pkg/auth/manager/owncloudsql/owncloudsql.go @@ -26,8 +26,6 @@ import ( "fmt" "strings" - "golang.org/x/crypto/bcrypt" - authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1" user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" "github.com/cs3org/reva/pkg/appctx" @@ -36,11 +34,12 @@ import ( "github.com/cs3org/reva/pkg/auth/manager/registry" "github.com/cs3org/reva/pkg/auth/scope" "github.com/cs3org/reva/pkg/errtypes" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - // Provides mysql drivers + // Provides mysql drivers. _ "github.com/go-sql-driver/mysql" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" ) func init() { @@ -53,11 +52,11 @@ type manager struct { } type config struct { - DbUsername string `mapstructure:"dbusername"` - DbPassword string `mapstructure:"dbpassword"` - DbHost string `mapstructure:"dbhost"` - DbPort int `mapstructure:"dbport"` - DbName string `mapstructure:"dbname"` + DBUsername string `mapstructure:"dbusername"` + DBPassword string `mapstructure:"dbpassword"` + DBHost string `mapstructure:"dbhost"` + DBPort int `mapstructure:"dbport"` + DBName string `mapstructure:"dbname"` Idp string `mapstructure:"idp"` Nobody int64 `mapstructure:"nobody"` LegacySalt string `mapstructure:"legacy_salt"` @@ -65,7 +64,7 @@ type config struct { JoinOwnCloudUUID bool `mapstructure:"join_ownclouduuid"` } -// NewMysql returns a new auth manager connection to an owncloud mysql database +// NewMysql returns a new auth manager connection to an owncloud mysql database. func NewMysql(m map[string]interface{}) (auth.Manager, error) { mgr := &manager{} err := mgr.Configure(m) @@ -75,7 +74,7 @@ func NewMysql(m map[string]interface{}) (auth.Manager, error) { } mgr.db, err = accounts.NewMysql( - fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mgr.c.DbUsername, mgr.c.DbPassword, mgr.c.DbHost, mgr.c.DbPort, mgr.c.DbName), + fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mgr.c.DBUsername, mgr.c.DBPassword, mgr.c.DBHost, mgr.c.DBPort, mgr.c.DBName), mgr.c.JoinUsername, mgr.c.JoinOwnCloudUUID, false, diff --git a/pkg/auth/manager/owncloudsql/owncloudsql_test.go b/pkg/auth/manager/owncloudsql/owncloudsql_test.go index 302e482b6ef..42afb8ffdcc 100644 --- a/pkg/auth/manager/owncloudsql/owncloudsql_test.go +++ b/pkg/auth/manager/owncloudsql/owncloudsql_test.go @@ -25,7 +25,7 @@ import ( "github.com/pkg/errors" ) -// new returns a dummy auth manager for testing +// new returns a dummy auth manager for testing. func new(m map[string]interface{}) (*manager, error) { mgr := &manager{} err := mgr.Configure(m) diff --git a/pkg/auth/manager/publicshares/publicshares.go b/pkg/auth/manager/publicshares/publicshares.go index 1a6dc62a16d..5989e04c841 100644 --- a/pkg/auth/manager/publicshares/publicshares.go +++ b/pkg/auth/manager/publicshares/publicshares.go @@ -25,7 +25,6 @@ import ( authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1" user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - userprovider "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" @@ -127,7 +126,7 @@ func (m *manager) Authenticate(ctx context.Context, token, secret string) (*user return nil, nil, errtypes.InternalError(publicShareResponse.Status.Message) } - getUserResponse, err := gwConn.GetUser(ctx, &userprovider.GetUserRequest{ + getUserResponse, err := gwConn.GetUser(ctx, &user.GetUserRequest{ UserId: publicShareResponse.GetShare().GetCreator(), }) if err != nil { @@ -163,5 +162,5 @@ func (m *manager) Authenticate(ctx context.Context, token, secret string) (*user return u, scope, nil } -// ErrPasswordNotProvided is returned when the public share is password protected, but there was no password on the request +// ErrPasswordNotProvided is returned when the public share is password protected, but there was no password on the request. var ErrPasswordNotProvided = errors.New("public share is password protected, but password was not provided") diff --git a/pkg/auth/registry/loader/loader.go b/pkg/auth/registry/loader/loader.go index fe0f1ef8bef..53e01018f0c 100644 --- a/pkg/auth/registry/loader/loader.go +++ b/pkg/auth/registry/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load core storage broker drivers. _ "github.com/cs3org/reva/pkg/auth/registry/static" - // Add your own here + // Add your own here. ) diff --git a/pkg/auth/rpc_auth.go b/pkg/auth/rpc_auth.go index 92dbee5bb49..b6160a7ac3b 100644 --- a/pkg/auth/rpc_auth.go +++ b/pkg/auth/rpc_auth.go @@ -38,12 +38,12 @@ type ProviderPlugin struct { Impl Manager } -// Server returns the RPC Server which serves the methods that the Client calls over net/rpc +// Server returns the RPC Server which serves the methods that the Client calls over net/rpc. func (p *ProviderPlugin) Server(*hcplugin.MuxBroker) (interface{}, error) { return &RPCServer{Impl: p.Impl}, nil } -// Client returns interface implementation for the plugin that communicates to the server end of the plugin +// Client returns interface implementation for the plugin that communicates to the server end of the plugin. func (p *ProviderPlugin) Client(b *hcplugin.MuxBroker, c *rpc.Client) (interface{}, error) { return &RPCClient{Client: c}, nil } @@ -51,17 +51,17 @@ func (p *ProviderPlugin) Client(b *hcplugin.MuxBroker, c *rpc.Client) (interface // RPCClient is an implementation of Manager that talks over RPC. type RPCClient struct{ Client *rpc.Client } -// ConfigureArg for RPC +// ConfigureArg for RPC. type ConfigureArg struct { Ml map[string]interface{} } -// ConfigureReply for RPC +// ConfigureReply for RPC. type ConfigureReply struct { Err error } -// Configure RPCClient configure method +// Configure RPCClient configure method. func (m *RPCClient) Configure(ml map[string]interface{}) error { args := ConfigureArg{Ml: ml} resp := ConfigureReply{} @@ -72,21 +72,21 @@ func (m *RPCClient) Configure(ml map[string]interface{}) error { return resp.Err } -// AuthenticateArgs for RPC +// AuthenticateArgs for RPC. type AuthenticateArgs struct { Ctx map[interface{}]interface{} ClientID string ClientSecret string } -// AuthenticateReply for RPC +// AuthenticateReply for RPC. type AuthenticateReply struct { User *user.User Auth map[string]*authpb.Scope Error error } -// Authenticate RPCClient Authenticate method +// Authenticate RPCClient Authenticate method. func (m *RPCClient) Authenticate(ctx context.Context, clientID, clientSecret string) (*user.User, map[string]*authpb.Scope, error) { ctxVal := appctx.GetKeyValuesFromCtx(ctx) args := AuthenticateArgs{Ctx: ctxVal, ClientID: clientID, ClientSecret: clientSecret} @@ -98,19 +98,19 @@ func (m *RPCClient) Authenticate(ctx context.Context, clientID, clientSecret str return reply.User, reply.Auth, reply.Error } -// RPCServer is the server that RPCClient talks to, conforming to the requirements of net/rpc +// RPCServer is the server that RPCClient talks to, conforming to the requirements of net/rpc. type RPCServer struct { // This is the real implementation Impl Manager } -// Configure RPCServer Configure method +// Configure RPCServer Configure method. func (m *RPCServer) Configure(args ConfigureArg, resp *ConfigureReply) error { resp.Err = m.Impl.Configure(args.Ml) return nil } -// Authenticate RPCServer Authenticate method +// Authenticate RPCServer Authenticate method. func (m *RPCServer) Authenticate(args AuthenticateArgs, resp *AuthenticateReply) error { ctx := appctx.PutKeyValuesToCtx(args.Ctx) resp.User, resp.Auth, resp.Error = m.Impl.Authenticate(ctx, args.ClientID, args.ClientSecret) diff --git a/pkg/auth/scope/resourceinfo.go b/pkg/auth/scope/resourceinfo.go index 2066ce56678..ef77cd8b365 100644 --- a/pkg/auth/scope/resourceinfo.go +++ b/pkg/auth/scope/resourceinfo.go @@ -28,11 +28,10 @@ import ( gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" registry "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1" - "github.com/rs/zerolog" - types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/utils" + "github.com/rs/zerolog" ) func resourceinfoScope(_ context.Context, scope *authpb.Scope, resource interface{}, logger *zerolog.Logger) (bool, error) { diff --git a/pkg/auth/scope/utils.go b/pkg/auth/scope/utils.go index a442db9901b..4a50f16446a 100644 --- a/pkg/auth/scope/utils.go +++ b/pkg/auth/scope/utils.go @@ -29,7 +29,7 @@ import ( "github.com/cs3org/reva/pkg/utils" ) -// FormatScope create a pretty print of the scope +// FormatScope create a pretty print of the scope. func FormatScope(scopeType string, scope *authpb.Scope) (string, error) { // TODO(gmgigi96): check decoder type switch { diff --git a/pkg/cbox/favorite/sql/sql.go b/pkg/cbox/favorite/sql/sql.go index ebb6c85ec93..b669e6c7061 100644 --- a/pkg/cbox/favorite/sql/sql.go +++ b/pkg/cbox/favorite/sql/sql.go @@ -37,11 +37,11 @@ func init() { } type config struct { - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` } type mgr struct { @@ -56,7 +56,7 @@ func New(m map[string]interface{}) (favorite.Manager, error) { return nil, err } - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } diff --git a/pkg/cbox/group/rest/rest.go b/pkg/cbox/group/rest/rest.go index 7557b68571b..29f3dedcae3 100644 --- a/pkg/cbox/group/rest/rest.go +++ b/pkg/cbox/group/rest/rest.go @@ -219,7 +219,6 @@ func (m *manager) parseAndCacheGroup(ctx context.Context, groupData map[string]i } return g, nil - } func (m *manager) GetGroup(ctx context.Context, gid *grouppb.GroupId, skipFetchingMembers bool) (*grouppb.Group, error) { @@ -261,7 +260,6 @@ func (m *manager) GetGroupByClaim(ctx context.Context, claim, value string, skip } func (m *manager) FindGroups(ctx context.Context, query string, skipFetchingMembers bool) ([]*grouppb.Group, error) { - // Look at namespaces filters. If the query starts with: // "a" or none => get egroups // other filters => get empty list @@ -280,7 +278,6 @@ func (m *manager) FindGroups(ctx context.Context, query string, skipFetchingMemb } func (m *manager) GetMembers(ctx context.Context, gid *grouppb.GroupId) ([]*userpb.UserId, error) { - users, err := m.fetchCachedGroupMembers(gid) if err == nil { return users, nil diff --git a/pkg/cbox/preferences/sql/sql.go b/pkg/cbox/preferences/sql/sql.go index 67ba2ad7319..cd56ea14278 100644 --- a/pkg/cbox/preferences/sql/sql.go +++ b/pkg/cbox/preferences/sql/sql.go @@ -35,11 +35,11 @@ func init() { } type config struct { - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` } type mgr struct { @@ -54,7 +54,7 @@ func New(m map[string]interface{}) (preferences.Manager, error) { return nil, err } - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } diff --git a/pkg/cbox/publicshare/sql/sql.go b/pkg/cbox/publicshare/sql/sql.go index b7aa9c36c28..38ee467f978 100644 --- a/pkg/cbox/publicshare/sql/sql.go +++ b/pkg/cbox/publicshare/sql/sql.go @@ -29,8 +29,6 @@ import ( "syscall" "time" - "golang.org/x/crypto/bcrypt" - user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" @@ -45,6 +43,7 @@ import ( "github.com/cs3org/reva/pkg/utils" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" + "golang.org/x/crypto/bcrypt" ) const ( @@ -63,11 +62,11 @@ type config struct { SharePasswordHashCost int `mapstructure:"password_hash_cost"` JanitorRunInterval int `mapstructure:"janitor_run_interval"` EnableExpiredSharesCleanup bool `mapstructure:"enable_expired_shares_cleanup"` - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` GatewaySvc string `mapstructure:"gatewaysvc"` } @@ -114,7 +113,7 @@ func New(m map[string]interface{}) (publicshare.Manager, error) { } c.init() - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } @@ -129,7 +128,6 @@ func New(m map[string]interface{}) (publicshare.Manager, error) { } func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *provider.ResourceInfo, g *link.Grant, description string, internal bool) (*link.PublicShare, error) { - tkn := utils.RandString(15) now := time.Now().Unix() @@ -320,7 +318,6 @@ func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.Pu if err := publicshare.AddSignature(s, pw); err != nil { return nil, err } - } return s, nil diff --git a/pkg/cbox/share/sql/sql.go b/pkg/cbox/share/sql/sql.go index ab5c3221d08..3f036974e46 100644 --- a/pkg/cbox/share/sql/sql.go +++ b/pkg/cbox/share/sql/sql.go @@ -39,12 +39,12 @@ import ( "github.com/cs3org/reva/pkg/share/manager/registry" "github.com/cs3org/reva/pkg/sharedconf" "github.com/cs3org/reva/pkg/utils" + + // Provides mysql drivers. + _ "github.com/go-sql-driver/mysql" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "google.golang.org/genproto/protobuf/field_mask" - - // Provides mysql drivers - _ "github.com/go-sql-driver/mysql" ) const ( @@ -61,11 +61,11 @@ func init() { } type config struct { - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` GatewaySvc string `mapstructure:"gatewaysvc"` } @@ -82,7 +82,7 @@ func New(m map[string]interface{}) (share.Manager, error) { return nil, err } - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } @@ -468,7 +468,6 @@ func (m *mgr) GetReceivedShare(ctx context.Context, ref *collaboration.ShareRefe } return s, nil - } func (m *mgr) UpdateReceivedShare(ctx context.Context, share *collaboration.ReceivedShare, fieldMask *field_mask.FieldMask) (*collaboration.ReceivedShare, error) { @@ -571,7 +570,7 @@ func granteeTypeToShareType(granteeType provider.GranteeType) int { return -1 } -// translateFilters translates the filters to sql queries +// translateFilters translates the filters to sql queries. func translateFilters(filters map[collaboration.Filter_Type][]*collaboration.Filter) (string, []interface{}, error) { var ( filterQuery string diff --git a/pkg/cbox/storage/eoswrapper/eoswrapper.go b/pkg/cbox/storage/eoswrapper/eoswrapper.go index 4ec0413cf09..a581694bb81 100644 --- a/pkg/cbox/storage/eoswrapper/eoswrapper.go +++ b/pkg/cbox/storage/eoswrapper/eoswrapper.go @@ -43,7 +43,7 @@ func init() { const ( eosProjectsNamespace = "/eos/project" - // We can use a regex for these, but that might have inferior performance + // We can use a regex for these, but that might have inferior performance. projectSpaceGroupsPrefix = "cernbox-project-" projectSpaceAdminGroupsSuffix = "-admins" ) @@ -121,7 +121,6 @@ func (w *wrapper) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []s } return res, nil - } func (w *wrapper) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys []string) ([]*provider.ResourceInfo, error) { @@ -188,7 +187,6 @@ func (w *wrapper) getMountID(ctx context.Context, r *provider.ResourceInfo) stri func (w *wrapper) setProjectSharingPermissions(ctx context.Context, r *provider.ResourceInfo) error { // Check if this storage provider corresponds to a project spaces instance if strings.HasPrefix(w.conf.Namespace, eosProjectsNamespace) { - // Extract project name from the path resembling /c/cernbox or /c/cernbox/minutes/.. parts := strings.SplitN(r.Path, "/", 4) if len(parts) != 4 && len(parts) != 3 { diff --git a/pkg/cbox/user/rest/rest.go b/pkg/cbox/user/rest/rest.go index 47d14d1360c..4e40c3162a3 100644 --- a/pkg/cbox/user/rest/rest.go +++ b/pkg/cbox/user/rest/rest.go @@ -260,7 +260,6 @@ func (m *manager) GetUserByClaim(ctx context.Context, claim, value string, skipF } func (m *manager) FindUsers(ctx context.Context, query string, skipFetchingGroups bool) ([]*userpb.User, error) { - // Look at namespaces filters. If the query starts with: // "a" => look into primary/secondary/service accounts // "l" => look into lightweight/federated accounts @@ -300,7 +299,7 @@ func (m *manager) FindUsers(ctx context.Context, query string, skipFetchingGroup return userSlice, nil } -// isUserAnyType returns true if the user's type is one of types list +// isUserAnyType returns true if the user's type is one of types list. func isUserAnyType(user *userpb.User, types []userpb.UserType) bool { for _, t := range types { if user.GetId().Type == t { @@ -380,5 +379,4 @@ func getUserType(userType, upn string) userpb.UserType { t = userpb.UserType_USER_TYPE_INVALID } return t - } diff --git a/pkg/cbox/utils/conversions.go b/pkg/cbox/utils/conversions.go index 8741eb517d2..caa8b98a5e3 100644 --- a/pkg/cbox/utils/conversions.go +++ b/pkg/cbox/utils/conversions.go @@ -52,7 +52,7 @@ type DBShare struct { Description string } -// FormatGrantee formats a CS3API grantee to a string +// FormatGrantee formats a CS3API grantee to a string. func FormatGrantee(g *provider.Grantee) (int, string) { var granteeType int var formattedID string @@ -69,7 +69,7 @@ func FormatGrantee(g *provider.Grantee) (int, string) { return granteeType, formattedID } -// ExtractGrantee retrieves the CS3API grantee from a formatted string +// ExtractGrantee retrieves the CS3API grantee from a formatted string. func ExtractGrantee(t int, g string) *provider.Grantee { var grantee provider.Grantee switch t { @@ -85,7 +85,7 @@ func ExtractGrantee(t int, g string) *provider.Grantee { return &grantee } -// ResourceTypeToItem maps a resource type to a string +// ResourceTypeToItem maps a resource type to a string. func ResourceTypeToItem(r provider.ResourceType) string { switch r { case provider.ResourceType_RESOURCE_TYPE_FILE: @@ -101,7 +101,7 @@ func ResourceTypeToItem(r provider.ResourceType) string { } } -// ResourceTypeToItemInt maps a resource type to an integer +// ResourceTypeToItemInt maps a resource type to an integer. func ResourceTypeToItemInt(r provider.ResourceType) int { switch r { case provider.ResourceType_RESOURCE_TYPE_CONTAINER: @@ -113,7 +113,7 @@ func ResourceTypeToItemInt(r provider.ResourceType) int { } } -// SharePermToInt maps read/write permissions to an integer +// SharePermToInt maps read/write permissions to an integer. func SharePermToInt(p *provider.ResourcePermissions) int { var perm int switch { @@ -128,7 +128,7 @@ func SharePermToInt(p *provider.ResourcePermissions) int { return perm } -// IntTosharePerm retrieves read/write permissions from an integer +// IntTosharePerm retrieves read/write permissions from an integer. func IntTosharePerm(p int, itemType string) *provider.ResourcePermissions { switch p { case 1: @@ -146,7 +146,7 @@ func IntTosharePerm(p int, itemType string) *provider.ResourcePermissions { } } -// IntToShareState retrieves the received share state from an integer +// IntToShareState retrieves the received share state from an integer. func IntToShareState(g int) collaboration.ShareState { switch g { case 0: @@ -160,12 +160,12 @@ func IntToShareState(g int) collaboration.ShareState { } } -// FormatUserID formats a CS3API user ID to a string +// FormatUserID formats a CS3API user ID to a string. func FormatUserID(u *userpb.UserId) string { return u.OpaqueId } -// ExtractUserID retrieves a CS3API user ID from a string +// ExtractUserID retrieves a CS3API user ID from a string. func ExtractUserID(u string) *userpb.UserId { t := userpb.UserType_USER_TYPE_PRIMARY if strings.HasPrefix(u, "guest:") { @@ -176,17 +176,17 @@ func ExtractUserID(u string) *userpb.UserId { return &userpb.UserId{OpaqueId: u, Type: t} } -// FormatGroupID formats a CS3API group ID to a string +// FormatGroupID formats a CS3API group ID to a string. func FormatGroupID(u *grouppb.GroupId) string { return u.OpaqueId } -// ExtractGroupID retrieves a CS3API group ID from a string +// ExtractGroupID retrieves a CS3API group ID from a string. func ExtractGroupID(u string) *grouppb.GroupId { return &grouppb.GroupId{OpaqueId: u} } -// ConvertToCS3Share converts a DBShare to a CS3API collaboration share +// ConvertToCS3Share converts a DBShare to a CS3API collaboration share. func ConvertToCS3Share(s DBShare) *collaboration.Share { ts := &typespb.Timestamp{ Seconds: uint64(s.STime), @@ -209,7 +209,7 @@ func ConvertToCS3Share(s DBShare) *collaboration.Share { } } -// ConvertToCS3ReceivedShare converts a DBShare to a CS3API collaboration received share +// ConvertToCS3ReceivedShare converts a DBShare to a CS3API collaboration received share. func ConvertToCS3ReceivedShare(s DBShare) *collaboration.ReceivedShare { return &collaboration.ReceivedShare{ Share: ConvertToCS3Share(s), @@ -217,7 +217,7 @@ func ConvertToCS3ReceivedShare(s DBShare) *collaboration.ReceivedShare { } } -// ConvertToCS3PublicShare converts a DBShare to a CS3API public share +// ConvertToCS3PublicShare converts a DBShare to a CS3API public share. func ConvertToCS3PublicShare(s DBShare) *link.PublicShare { ts := &typespb.Timestamp{ Seconds: uint64(s.STime), diff --git a/pkg/cbox/utils/tokenmanagement.go b/pkg/cbox/utils/tokenmanagement.go index f4bbe2241f8..c8101c4c922 100644 --- a/pkg/cbox/utils/tokenmanagement.go +++ b/pkg/cbox/utils/tokenmanagement.go @@ -33,14 +33,14 @@ import ( "github.com/mitchellh/mapstructure" ) -// APITokenManager stores config related to api management +// APITokenManager stores config related to api management. type APITokenManager struct { oidcToken OIDCToken conf *config client *http.Client } -// OIDCToken stores the OIDC token used to authenticate requests to the REST API service +// OIDCToken stores the OIDC token used to authenticate requests to the REST API service. type OIDCToken struct { sync.Mutex // concurrent access to apiToken and tokenExpirationTime apiToken string @@ -56,7 +56,7 @@ type config struct { Insecure bool `mapstructure:"insecure"` } -// InitAPITokenManager initializes a new APITokenManager +// InitAPITokenManager initializes a new APITokenManager. func InitAPITokenManager(conf map[string]interface{}) (*APITokenManager, error) { c := &config{} if err := mapstructure.Decode(conf, c); err != nil { @@ -90,7 +90,6 @@ func (a *APITokenManager) renewAPIToken(ctx context.Context, forceRenewal bool) } func (a *APITokenManager) getAPIToken(ctx context.Context) (string, time.Time, error) { - params := url.Values{ "grant_type": {"client_credentials"}, "audience": {a.conf.TargetAPI}, @@ -128,7 +127,7 @@ func (a *APITokenManager) getAPIToken(ctx context.Context) (string, time.Time, e return result["access_token"].(string), expirationTime, nil } -// SendAPIGetRequest makes an API GET Request to the passed URL +// SendAPIGetRequest makes an API GET Request to the passed URL. func (a *APITokenManager) SendAPIGetRequest(ctx context.Context, url string, forceRenewal bool) (map[string]interface{}, error) { err := a.renewAPIToken(ctx, forceRenewal) if err != nil { diff --git a/pkg/ctx/agentctx.go b/pkg/ctx/agentctx.go index 1d96f355afa..07338fbb38e 100644 --- a/pkg/ctx/agentctx.go +++ b/pkg/ctx/agentctx.go @@ -26,7 +26,7 @@ import ( "google.golang.org/grpc/metadata" ) -// UserAgentHeader is the header used for the user agent +// UserAgentHeader is the header used for the user agent. const ( UserAgentHeader = "x-user-agent" @@ -66,7 +66,7 @@ func ContextGetUserAgentString(ctx context.Context) (string, bool) { } // ContextGetUserAgentCategory returns the category of the user agent -// (i.e. if it is a web, mobile, desktop or grpc user agent) +// (i.e. if it is a web, mobile, desktop or grpc user agent). func ContextGetUserAgentCategory(ctx context.Context) (string, bool) { agent, ok := ContextGetUserAgent(ctx) if !ok { @@ -91,19 +91,19 @@ func isWeb(ua *ua.UserAgent) bool { ua.IsInternetExplorer() || ua.IsOpera() || ua.IsOperaMini() } -// isMobile returns true if the useragent is generated by the mobile +// isMobile returns true if the useragent is generated by the mobile. func isMobile(ua *ua.UserAgent) bool { // workaround as the library does not recognise iOS string inside the user agent isIOS := ua.IsIOS() || strings.Contains(ua.String, "iOS") return !isWeb(ua) && (ua.IsAndroid() || isIOS) } -// isDesktop returns true if the useragent is generated by a desktop application +// isDesktop returns true if the useragent is generated by a desktop application. func isDesktop(ua *ua.UserAgent) bool { return ua.Desktop && !isWeb(ua) } -// isGRPC returns true if the useragent is generated by a grpc client +// isGRPC returns true if the useragent is generated by a grpc client. func isGRPC(ua *ua.UserAgent) bool { return strings.HasPrefix(ua.Name, "grpc") } diff --git a/pkg/ctx/agentctx_test.go b/pkg/ctx/agentctx_test.go index 8cfd6b0e6ad..f3b70790869 100644 --- a/pkg/ctx/agentctx_test.go +++ b/pkg/ctx/agentctx_test.go @@ -26,7 +26,6 @@ import ( ) func TestUserAgentIsAllowed(t *testing.T) { - tests := []struct { description string userAgent string @@ -73,7 +72,6 @@ func TestUserAgentIsAllowed(t *testing.T) { if cat != tt.expected { t.Fatalf("result does not match with expected. got=%+v expected=%+v", cat, tt.expected) } - }) } } diff --git a/pkg/datatx/datatx.go b/pkg/datatx/datatx.go index 3b1d98d6b21..2671dd09bb0 100644 --- a/pkg/datatx/datatx.go +++ b/pkg/datatx/datatx.go @@ -24,7 +24,7 @@ import ( datatx "github.com/cs3org/go-cs3apis/cs3/tx/v1beta1" ) -// Manager the interface any transfer driver should implement +// Manager the interface any transfer driver should implement. type Manager interface { // StartTransfer initiates a transfer job and returns a TxInfo object including a unique transfer id, and error if any. StartTransfer(ctx context.Context, srcRemote string, srcPath string, srcToken string, destRemote string, destPath string, destToken string) (*datatx.TxInfo, error) diff --git a/pkg/datatx/manager/loader/loader.go b/pkg/datatx/manager/loader/loader.go index 28df90ed124..12d85a3d2bd 100644 --- a/pkg/datatx/manager/loader/loader.go +++ b/pkg/datatx/manager/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load datatx drivers. _ "github.com/cs3org/reva/pkg/datatx/manager/rclone" - // Add your own here + // Add your own here. ) diff --git a/pkg/datatx/manager/rclone/rclone.go b/pkg/datatx/manager/rclone/rclone.go index 6365ffa6a47..b6eb1f40354 100644 --- a/pkg/datatx/manager/rclone/rclone.go +++ b/pkg/datatx/manager/rclone/rclone.go @@ -88,7 +88,7 @@ type transferModel struct { Transfers map[string]*transfer `json:"transfers"` } -// persistency driver +// persistency driver. type pDriver struct { sync.Mutex // concurrent access to the file model *transferModel @@ -107,7 +107,7 @@ type transfer struct { Ctime string } -// txEndStatuses final statuses that cannot be changed anymore +// txEndStatuses final statuses that cannot be changed anymore. var txEndStatuses = map[string]int32{ "STATUS_INVALID": 0, "STATUS_DESTINATION_NOT_FOUND": 1, @@ -118,7 +118,7 @@ var txEndStatuses = map[string]int32{ "STATUS_TRANSFER_EXPIRED": 10, } -// New returns a new rclone driver +// New returns a new rclone driver. func New(m map[string]interface{}) (txdriver.Manager, error) { c, err := parseConfig(m) if err != nil { @@ -582,7 +582,7 @@ func (driver *rclone) startJob(ctx context.Context, transferID string, srcRemote }, nil } -// GetTransferStatus returns the status of the transfer with the specified job id +// GetTransferStatus returns the status of the transfer with the specified job id. func (driver *rclone) GetTransferStatus(ctx context.Context, transferID string) (*datatx.TxInfo, error) { transfer, err := driver.pDriver.model.getTransfer(transferID) if err != nil { @@ -600,7 +600,7 @@ func (driver *rclone) GetTransferStatus(ctx context.Context, transferID string) }, nil } -// CancelTransfer cancels the transfer with the specified transfer id +// CancelTransfer cancels the transfer with the specified transfer id. func (driver *rclone) CancelTransfer(ctx context.Context, transferID string) (*datatx.TxInfo, error) { transfer, err := driver.pDriver.model.getTransfer(transferID) if err != nil { @@ -748,7 +748,7 @@ func (driver *rclone) RetryTransfer(ctx context.Context, transferID string) (*da return driver.startJob(ctx, transferID, "", "", "", "", "", "") } -// getTransfer returns the transfer with the specified transfer ID +// getTransfer returns the transfer with the specified transfer ID. func (m *transferModel) getTransfer(transferID string) (*transfer, error) { transfer, ok := m.Transfers[transferID] if !ok { diff --git a/pkg/eosclient/eosbinary/eosbinary.go b/pkg/eosclient/eosbinary/eosbinary.go index b8155759988..a2a9aa6cd3b 100644 --- a/pkg/eosclient/eosbinary/eosbinary.go +++ b/pkg/eosclient/eosbinary/eosbinary.go @@ -153,7 +153,7 @@ func New(opt *Options) (*Client, error) { return c, nil } -// executeXRDCopy executes xrdcpy commands and returns the stdout, stderr and return code +// executeXRDCopy executes xrdcpy commands and returns the stdout, stderr and return code. func (c *Client) executeXRDCopy(ctx context.Context, cmdArgs []string) (string, string, error) { log := appctx.GetLogger(ctx) @@ -182,7 +182,6 @@ func (c *Client) executeXRDCopy(ctx context.Context, cmdArgs []string) (string, // defined for both Unix and Windows and in both cases has // an ExitStatus() method with the same signature. if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { - exitStatus = status.ExitStatus() switch exitStatus { case 0: @@ -294,7 +293,6 @@ func (c *Client) AddACL(ctx context.Context, auth, rootAuth eosclient.Authorizat _, _, err = c.executeEOS(ctx, args, rootAuth) return err - } // RemoveACL removes the acl from EOS. @@ -320,7 +318,7 @@ func (c *Client) UpdateACL(ctx context.Context, auth, rootAuth eosclient.Authori return c.AddACL(ctx, auth, rootAuth, path, position, a) } -// GetACL for a file +// GetACL for a file. func (c *Client) GetACL(ctx context.Context, auth eosclient.Authorization, path, aclType, target string) (*acl.Entry, error) { acls, err := c.ListACLs(ctx, auth, path) if err != nil { @@ -332,14 +330,12 @@ func (c *Client) GetACL(ctx context.Context, auth eosclient.Authorization, path, } } return nil, errtypes.NotFound(fmt.Sprintf("%s:%s", aclType, target)) - } // ListACLs returns the list of ACLs present under the given path. // EOS returns uids/gid for Citrine version and usernames for older versions. // For Citire we need to convert back the uid back to username. func (c *Client) ListACLs(ctx context.Context, auth eosclient.Authorization, path string) ([]*acl.Entry, error) { - parsedACLs, err := c.getACLForPath(ctx, auth, path) if err != nil { return nil, err @@ -359,7 +355,7 @@ func (c *Client) getACLForPath(ctx context.Context, auth eosclient.Authorization return finfo.SysACL, nil } -// GetFileInfoByInode returns the FileInfo by the given inode +// GetFileInfoByInode returns the FileInfo by the given inode. func (c *Client) GetFileInfoByInode(ctx context.Context, auth eosclient.Authorization, inode uint64) (*eosclient.FileInfo, error) { args := []string{"file", "info", fmt.Sprintf("inode:%d", inode), "-m"} stdout, _, err := c.executeEOS(ctx, args, auth) @@ -382,7 +378,7 @@ func (c *Client) GetFileInfoByInode(ctx context.Context, auth eosclient.Authoriz return c.mergeACLsAndAttrsForFiles(ctx, auth, info), nil } -// GetFileInfoByFXID returns the FileInfo by the given file id in hexadecimal +// GetFileInfoByFXID returns the FileInfo by the given file id in hexadecimal. func (c *Client) GetFileInfoByFXID(ctx context.Context, auth eosclient.Authorization, fxid string) (*eosclient.FileInfo, error) { args := []string{"file", "info", fmt.Sprintf("fxid:%s", fxid), "-m"} stdout, _, err := c.executeEOS(ctx, args, auth) @@ -398,7 +394,7 @@ func (c *Client) GetFileInfoByFXID(ctx context.Context, auth eosclient.Authoriza return c.mergeACLsAndAttrsForFiles(ctx, auth, info), nil } -// GetFileInfoByPath returns the FilInfo at the given path +// GetFileInfoByPath returns the FilInfo at the given path. func (c *Client) GetFileInfoByPath(ctx context.Context, auth eosclient.Authorization, path string) (*eosclient.FileInfo, error) { args := []string{"file", "info", path, "-m"} stdout, _, err := c.executeEOS(ctx, args, auth) @@ -570,9 +566,8 @@ func (c *Client) UnsetAttr(ctx context.Context, auth eosclient.Authorization, at return nil } -// GetAttr returns the attribute specified by key +// GetAttr returns the attribute specified by key. func (c *Client) GetAttr(ctx context.Context, auth eosclient.Authorization, key, path string) (*eosclient.Attribute, error) { - // As SetAttr set the attr on the version folder, we will read the attribute on it // if the resource is not a folder info, err := c.getRawFileInfoByPath(ctx, auth, path) @@ -595,7 +590,7 @@ func (c *Client) GetAttr(ctx context.Context, auth eosclient.Authorization, key, return attr, nil } -// GetAttrs returns all the attributes of a resource +// GetAttrs returns all the attributes of a resource. func (c *Client) GetAttrs(ctx context.Context, auth eosclient.Authorization, path string) ([]*eosclient.Attribute, error) { info, err := c.getRawFileInfoByPath(ctx, auth, path) if err != nil { @@ -642,7 +637,7 @@ func deserializeAttribute(attrStr string) (*eosclient.Attribute, error) { return &eosclient.Attribute{Type: t, Key: type2key[1], Val: value}, nil } -// GetQuota gets the quota of a user on the quota node defined by path +// GetQuota gets the quota of a user on the quota node defined by path. func (c *Client) GetQuota(ctx context.Context, username string, rootAuth eosclient.Authorization, path string) (*eosclient.QuotaInfo, error) { args := []string{"quota", "ls", "-u", username, "-m"} stdout, _, err := c.executeEOS(ctx, args, rootAuth) @@ -652,7 +647,7 @@ func (c *Client) GetQuota(ctx context.Context, username string, rootAuth eosclie return c.parseQuota(path, stdout) } -// SetQuota sets the quota of a user on the quota node defined by path +// SetQuota sets the quota of a user on the quota node defined by path. func (c *Client) SetQuota(ctx context.Context, rootAuth eosclient.Authorization, info *eosclient.SetQuotaInfo) error { maxBytes := fmt.Sprintf("%d", info.MaxBytes) maxFiles := fmt.Sprintf("%d", info.MaxFiles) @@ -671,28 +666,28 @@ func (c *Client) Touch(ctx context.Context, auth eosclient.Authorization, path s return err } -// Chown given path +// Chown given path. func (c *Client) Chown(ctx context.Context, auth, chownauth eosclient.Authorization, path string) error { args := []string{"chown", chownauth.Role.UID + ":" + chownauth.Role.GID, path} _, _, err := c.executeEOS(ctx, args, auth) return err } -// Chmod given path +// Chmod given path. func (c *Client) Chmod(ctx context.Context, auth eosclient.Authorization, mode, path string) error { args := []string{"chmod", mode, path} _, _, err := c.executeEOS(ctx, args, auth) return err } -// CreateDir creates a directory at the given path +// CreateDir creates a directory at the given path. func (c *Client) CreateDir(ctx context.Context, auth eosclient.Authorization, path string) error { args := []string{"mkdir", "-p", path} _, _, err := c.executeEOS(ctx, args, auth) return err } -// Remove removes the resource at the given path +// Remove removes the resource at the given path. func (c *Client) Remove(ctx context.Context, auth eosclient.Authorization, path string, noRecycle bool) error { args := []string{"rm", "-r"} if noRecycle { @@ -703,14 +698,14 @@ func (c *Client) Remove(ctx context.Context, auth eosclient.Authorization, path return err } -// Rename renames the resource referenced by oldPath to newPath +// Rename renames the resource referenced by oldPath to newPath. func (c *Client) Rename(ctx context.Context, auth eosclient.Authorization, oldPath, newPath string) error { args := []string{"file", "rename", oldPath, newPath} _, _, err := c.executeEOS(ctx, args, auth) return err } -// List the contents of the directory given by path +// List the contents of the directory given by path. func (c *Client) List(ctx context.Context, auth eosclient.Authorization, path string) ([]*eosclient.FileInfo, error) { args := []string{"find", "--fileinfo", "--maxdepth", "1", path} stdout, _, err := c.executeEOS(ctx, args, auth) @@ -720,7 +715,7 @@ func (c *Client) List(ctx context.Context, auth eosclient.Authorization, path st return c.parseFind(ctx, auth, path, stdout) } -// Read reads a file from the mgm +// Read reads a file from the mgm. func (c *Client) Read(ctx context.Context, auth eosclient.Authorization, path string) (io.ReadCloser, error) { rand := "eosread-" + uuid.New().String() localTarget := fmt.Sprintf("%s/%s", c.opt.CacheDirectory, rand) @@ -742,7 +737,7 @@ func (c *Client) Read(ctx context.Context, auth eosclient.Authorization, path st return os.Open(localTarget) } -// Write writes a stream to the mgm +// Write writes a stream to the mgm. func (c *Client) Write(ctx context.Context, auth eosclient.Authorization, path string, stream io.ReadCloser) error { fd, err := os.CreateTemp(c.opt.CacheDirectory, "eoswrite-") if err != nil { @@ -760,7 +755,7 @@ func (c *Client) Write(ctx context.Context, auth eosclient.Authorization, path s return c.WriteFile(ctx, auth, path, fd.Name()) } -// WriteFile writes an existing file to the mgm +// WriteFile writes an existing file to the mgm. func (c *Client) WriteFile(ctx context.Context, auth eosclient.Authorization, path, source string) error { xrdPath := fmt.Sprintf("%s//%s", c.opt.URL, path) args := []string{"--nopbar", "--silent", "-f", source, xrdPath} @@ -825,7 +820,7 @@ func (c *Client) ReadVersion(ctx context.Context, auth eosclient.Authorization, return c.Read(ctx, auth, versionFile) } -// GenerateToken returns a token on behalf of the resource owner to be used by lightweight accounts +// GenerateToken returns a token on behalf of the resource owner to be used by lightweight accounts. func (c *Client) GenerateToken(ctx context.Context, auth eosclient.Authorization, p string, a *acl.Entry) (string, error) { expiration := strconv.FormatInt(time.Now().Add(time.Duration(c.opt.TokenExpiry)*time.Second).Unix(), 10) args := []string{"token", "--permission", a.Permissions, "--tree", "--path", p, "--expires", expiration} @@ -889,7 +884,7 @@ func parseRecycleList(raw string) ([]*eosclient.DeletedEntry, error) { // parse entries like these: // recycle=ls recycle-bin=/eos/backup/proc/recycle/ uid=gonzalhu gid=it size=0 deletion-time=1510823151 type=recursive-dir keylength.restore-path=45 restore-path=/eos/scratch/user/g/gonzalhu/.sys.v#.app.ico/ restore-key=0000000000a35100 -// recycle=ls recycle-bin=/eos/backup/proc/recycle/ uid=gonzalhu gid=it size=381038 deletion-time=1510823151 type=file keylength.restore-path=36 restore-path=/eos/scratch/user/g/gonzalhu/app.ico restore-key=000000002544fdb3 +// recycle=ls recycle-bin=/eos/backup/proc/recycle/ uid=gonzalhu gid=it size=381038 deletion-time=1510823151 type=file keylength.restore-path=36 restore-path=/eos/scratch/user/g/gonzalhu/app.ico restore-key=000000002544fdb3. func parseRecycleEntry(raw string) (*eosclient.DeletedEntry, error) { partsBySpace := strings.FieldsFunc(raw, func(c rune) bool { return c == ' ' @@ -931,7 +926,6 @@ func getMap(partsBySpace []string) map[string]string { if len(parts) > 1 { kv[parts[0]] = parts[1] } - } return kv } @@ -983,7 +977,6 @@ func (c *Client) parseFind(ctx context.Context, auth eosclient.Authorization, di for k, v := range vf.Attrs { fi.Attrs[k] = v } - } else if err := c.CreateDir(ctx, auth, versionFolderPath); err == nil { // Create the version folder if it doesn't exist if md, err := c.getRawFileInfoByPath(ctx, auth, versionFolderPath); err == nil { fi.Inode = md.Inode @@ -1040,7 +1033,6 @@ func (c *Client) parseQuota(path, raw string) (*eosclient.QuotaInfo, error) { // TODO(labkode): better API to access extended attributes. func (c *Client) parseFileInfo(ctx context.Context, raw string, parseFavoriteKey bool) (*eosclient.FileInfo, error) { - line := raw[15:] index := strings.Index(line, " file=/") lengthString := line[0:index] @@ -1077,7 +1069,6 @@ func (c *Client) parseFileInfo(ctx context.Context, raw string, parseFavoriteKey previousXAttr = "" default: kv[partsByEqual[0]] = partsByEqual[1] - } } } @@ -1090,7 +1081,7 @@ func (c *Client) parseFileInfo(ctx context.Context, raw string, parseFavoriteKey // mapToFileInfo converts the dictionary to an usable structure. // The kv has format: -// map[sys.forced.space:default files:0 mode:42555 ino:5 sys.forced.blocksize:4k sys.forced.layout:replica uid:0 fid:5 sys.forced.blockchecksum:crc32c sys.recycle:/eos/backup/proc/recycle/ fxid:00000005 pid:1 etag:5:0.000 keylength.file:4 file:/eos treesize:1931593933849913 container:3 gid:0 mtime:1498571294.108614409 ctime:1460121992.294326762 pxid:00000001 sys.forced.checksum:adler sys.forced.nstripes:2] +// map[sys.forced.space:default files:0 mode:42555 ino:5 sys.forced.blocksize:4k sys.forced.layout:replica uid:0 fid:5 sys.forced.blockchecksum:crc32c sys.recycle:/eos/backup/proc/recycle/ fxid:00000005 pid:1 etag:5:0.000 keylength.file:4 file:/eos treesize:1931593933849913 container:3 gid:0 mtime:1498571294.108614409 ctime:1460121992.294326762 pxid:00000001 sys.forced.checksum:adler sys.forced.nstripes:2]. func (c *Client) mapToFileInfo(ctx context.Context, kv, attrs map[string]string, parseFavoriteKey bool) (*eosclient.FileInfo, error) { inode, err := strconv.ParseUint(kv["ino"], 10, 64) if err != nil { diff --git a/pkg/eosclient/eosclient.go b/pkg/eosclient/eosclient.go index c9d52d4d874..1f8ab2bd7c7 100644 --- a/pkg/eosclient/eosclient.go +++ b/pkg/eosclient/eosclient.go @@ -114,7 +114,7 @@ type QuotaInfo struct { } // SetQuotaInfo encapsulates the information needed to -// create a quota space in EOS for a user +// create a quota space in EOS for a user. type SetQuotaInfo struct { Username string UID string @@ -124,7 +124,7 @@ type SetQuotaInfo struct { MaxFiles uint64 } -// Constants for ACL position +// Constants for ACL position. const ( EndPosition uint = 0 StartPosition uint = 1 @@ -143,9 +143,9 @@ type Authorization struct { } // AttrAlreadyExistsError is the error raised when setting -// an already existing attr on a resource +// an already existing attr on a resource. const AttrAlreadyExistsError = errtypes.BadRequest("attr already exists") // AttrNotExistsError is the error raised when removing -// an attribute that does not exist +// an attribute that does not exist. const AttrNotExistsError = errtypes.BadRequest("attr not exists") diff --git a/pkg/eosclient/eosgrpc/eosgrpc.go b/pkg/eosclient/eosgrpc/eosgrpc.go index bd516d8f0cc..ea596139589 100644 --- a/pkg/eosclient/eosgrpc/eosgrpc.go +++ b/pkg/eosclient/eosgrpc/eosgrpc.go @@ -33,7 +33,6 @@ import ( "syscall" "github.com/cs3org/reva/pkg/appctx" - "github.com/cs3org/reva/pkg/eosclient" erpc "github.com/cs3org/reva/pkg/eosclient/eosgrpc/eos_grpc" "github.com/cs3org/reva/pkg/errtypes" @@ -105,7 +104,6 @@ type Options struct { } func (opt *Options) init() { - if opt.XrdcopyBinary == "" { opt.XrdcopyBinary = "/opt/eos/xrootd/bin/xrdcopy" } @@ -117,7 +115,6 @@ func (opt *Options) init() { if opt.CacheDirectory == "" { opt.CacheDirectory = os.TempDir() } - } // Client performs actions against a EOS management node (MGM) @@ -128,7 +125,7 @@ type Client struct { cl erpc.EosClient } -// Create and connect a grpc eos Client +// Create and connect a grpc eos Client. func newgrpc(ctx context.Context, opt *Options) (erpc.EosClient, error) { log := appctx.GetLogger(ctx) log.Info().Str("Setting up GRPC towards ", "'"+opt.GrpcURI+"'").Msg("") @@ -182,7 +179,7 @@ func New(opt *Options, httpOpts *HTTPOptions) (*Client, error) { } // If the error is not nil, take that -// If there is an error coming from EOS, erturn a descriptive error +// If there is an error coming from EOS, erturn a descriptive error. func (c *Client) getRespError(rsp *erpc.NSResponse, err error) error { if err != nil { return err @@ -194,7 +191,7 @@ func (c *Client) getRespError(rsp *erpc.NSResponse, err error) error { return errtypes.InternalError("Err from EOS: " + fmt.Sprintf("%#v", rsp.Error)) } -// Common code to create and initialize a NSRequest +// Common code to create and initialize a NSRequest. func (c *Client) initNSRequest(ctx context.Context, auth eosclient.Authorization) (*erpc.NSRequest, error) { // Stuff filename, uid, gid into the MDRequest type @@ -219,7 +216,7 @@ func (c *Client) initNSRequest(ctx context.Context, auth eosclient.Authorization return rq, nil } -// Common code to create and initialize a NSRequest +// Common code to create and initialize a NSRequest. func (c *Client) initMDRequest(ctx context.Context, auth eosclient.Authorization) (*erpc.MDRequest, error) { // Stuff filename, uid, gid into the MDRequest type @@ -247,7 +244,6 @@ func (c *Client) initMDRequest(ctx context.Context, auth eosclient.Authorization // AddACL adds an new acl to EOS with the given aclType. func (c *Client) AddACL(ctx context.Context, auth, rootAuth eosclient.Authorization, path string, pos uint, a *acl.Entry) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "AddACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -294,12 +290,10 @@ func (c *Client) AddACL(ctx context.Context, auth, rootAuth eosclient.Authorizat log.Debug().Str("func", "AddACL").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } // RemoveACL removes the acl from EOS. func (c *Client) RemoveACL(ctx context.Context, auth, rootAuth eosclient.Authorization, path string, a *acl.Entry) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "RemoveACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -343,7 +337,6 @@ func (c *Client) RemoveACL(ctx context.Context, auth, rootAuth eosclient.Authori log.Debug().Str("func", "RemoveACL").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } // UpdateACL updates the EOS acl. @@ -351,9 +344,8 @@ func (c *Client) UpdateACL(ctx context.Context, auth, rootAuth eosclient.Authori return c.AddACL(ctx, auth, rootAuth, path, position, a) } -// GetACL for a file +// GetACL for a file. func (c *Client) GetACL(ctx context.Context, auth eosclient.Authorization, path, aclType, target string) (*acl.Entry, error) { - log := appctx.GetLogger(ctx) log.Info().Str("func", "GetACL").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -367,7 +359,6 @@ func (c *Client) GetACL(ctx context.Context, auth eosclient.Authorization, path, } } return nil, errtypes.NotFound(fmt.Sprintf("%s:%s", aclType, target)) - } // ListACLs returns the list of ACLs present under the given path. @@ -436,7 +427,7 @@ func (c *Client) getACLForPath(ctx context.Context, auth eosclient.Authorization return aclret, err } -// GetFileInfoByInode returns the FileInfo by the given inode +// GetFileInfoByInode returns the FileInfo by the given inode. func (c *Client) GetFileInfoByInode(ctx context.Context, auth eosclient.Authorization, inode uint64) (*eosclient.FileInfo, error) { log := appctx.GetLogger(ctx) log.Info().Str("func", "GetFileInfoByInode").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Uint64("inode", inode).Msg("") @@ -489,7 +480,6 @@ func (c *Client) GetFileInfoByInode(ctx context.Context, auth eosclient.Authoriz } func (c *Client) fixupACLs(ctx context.Context, auth eosclient.Authorization, info *eosclient.FileInfo) *eosclient.FileInfo { - // Append the ACLs that are described by the xattr sys.acl entry a, err := acl.Parse(info.Attrs["sys.acl"], acl.ShortTextForm) if err == nil { @@ -559,7 +549,6 @@ func (c *Client) SetAttr(ctx context.Context, auth eosclient.Authorization, attr } return err - } // UnsetAttr unsets an extended attribute on a path. @@ -605,10 +594,9 @@ func (c *Client) UnsetAttr(ctx context.Context, auth eosclient.Authorization, at log.Error().Str("func", "UnsetAttr").Str("path", path).Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("EOS negative resp") } return err - } -// GetAttr returns the attribute specified by key +// GetAttr returns the attribute specified by key. func (c *Client) GetAttr(ctx context.Context, auth eosclient.Authorization, key, path string) (*eosclient.Attribute, error) { info, err := c.GetFileInfoByPath(ctx, auth, path) if err != nil { @@ -627,7 +615,7 @@ func (c *Client) GetAttr(ctx context.Context, auth eosclient.Authorization, key, return nil, errtypes.NotFound(fmt.Sprintf("key %s not found", key)) } -// GetAttrs returns all the attributes of a resource +// GetAttrs returns all the attributes of a resource. func (c *Client) GetAttrs(ctx context.Context, auth eosclient.Authorization, path string) ([]*eosclient.Attribute, error) { info, err := c.GetFileInfoByPath(ctx, auth, path) if err != nil { @@ -664,7 +652,7 @@ func getAttribute(key, val string) (*eosclient.Attribute, error) { return attr, nil } -// GetFileInfoByPath returns the FilInfo at the given path +// GetFileInfoByPath returns the FilInfo at the given path. func (c *Client) GetFileInfoByPath(ctx context.Context, auth eosclient.Authorization, path string) (*eosclient.FileInfo, error) { log := appctx.GetLogger(ctx) log.Info().Str("func", "GetFileInfoByPath").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -690,7 +678,7 @@ func (c *Client) GetFileInfoByPath(ctx context.Context, auth eosclient.Authoriza if err != nil { log.Error().Str("func", "GetFileInfoByPath").Err(err).Str("path", path).Str("err", err.Error()) - // FIXME: this is very very bad and poisonous for the project!!!!!!! + // FIXME: this is very bad and poisonous for the project!!!!!!! // Apparently here we have to assume that an error in Recv() means "file not found" // - "File not found is not an error", it's a legitimate result of a legitimate check // - Assuming that any error means file not found is doubly poisonous @@ -720,12 +708,12 @@ func (c *Client) GetFileInfoByPath(ctx context.Context, auth eosclient.Authoriza return c.fixupACLs(ctx, auth, info), nil } -// GetFileInfoByFXID returns the FileInfo by the given file id in hexadecimal +// GetFileInfoByFXID returns the FileInfo by the given file id in hexadecimal. func (c *Client) GetFileInfoByFXID(ctx context.Context, auth eosclient.Authorization, fxid string) (*eosclient.FileInfo, error) { return nil, errtypes.NotSupported("eosgrpc: GetFileInfoByFXID not implemented") } -// GetQuota gets the quota of a user on the quota node defined by path +// GetQuota gets the quota of a user on the quota node defined by path. func (c *Client) GetQuota(ctx context.Context, username string, rootAuth eosclient.Authorization, path string) (*eosclient.QuotaInfo, error) { log := appctx.GetLogger(ctx) log.Info().Str("func", "GetQuota").Str("rootuid,rootgid", rootAuth.Role.UID+","+rootAuth.Role.GID).Str("username", username).Str("path", path).Msg("") @@ -796,10 +784,9 @@ func (c *Client) GetQuota(ctx context.Context, username string, rootAuth eosclie } return qi, err - } -// SetQuota sets the quota of a user on the quota node defined by path +// SetQuota sets the quota of a user on the quota node defined by path. func (c *Client) SetQuota(ctx context.Context, rootAuth eosclient.Authorization, info *eosclient.SetQuotaInfo) error { { log := appctx.GetLogger(ctx) @@ -859,7 +846,6 @@ func (c *Client) SetQuota(ctx context.Context, rootAuth eosclient.Authorization, log.Debug().Str("func", "GetQuota").Str("quotanodes", fmt.Sprintf("%d", len(resp.Quota.Quotanode))).Msg("grpc response") return err - } } @@ -896,10 +882,9 @@ func (c *Client) Touch(ctx context.Context, auth eosclient.Authorization, path s log.Debug().Str("func", "Touch").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } -// Chown given path +// Chown given path. func (c *Client) Chown(ctx context.Context, auth, chownAuth eosclient.Authorization, path string) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Chown").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("chownuid,chowngid", chownAuth.Role.UID+","+chownAuth.Role.GID).Str("path", path).Msg("") @@ -941,10 +926,9 @@ func (c *Client) Chown(ctx context.Context, auth, chownAuth eosclient.Authorizat log.Debug().Str("func", "Chown").Str("path", path).Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("chownuid,chowngid", chownAuth.Role.UID+","+chownAuth.Role.GID).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } -// Chmod given path +// Chmod given path. func (c *Client) Chmod(ctx context.Context, auth eosclient.Authorization, mode, path string) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Chmod").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("mode", mode).Str("path", path).Msg("") @@ -983,10 +967,9 @@ func (c *Client) Chmod(ctx context.Context, auth eosclient.Authorization, mode, log.Debug().Str("func", "Chmod").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } -// CreateDir creates a directory at the given path +// CreateDir creates a directory at the given path. func (c *Client) CreateDir(ctx context.Context, auth eosclient.Authorization, path string) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Createdir").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -1026,7 +1009,6 @@ func (c *Client) CreateDir(ctx context.Context, auth eosclient.Authorization, pa log.Debug().Str("func", "Createdir").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } func (c *Client) rm(ctx context.Context, auth eosclient.Authorization, path string, noRecycle bool) error { @@ -1062,7 +1044,6 @@ func (c *Client) rm(ctx context.Context, auth eosclient.Authorization, path stri log.Debug().Str("func", "rm").Str("path", path).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } func (c *Client) rmdir(ctx context.Context, auth eosclient.Authorization, path string, noRecycle bool) error { @@ -1101,7 +1082,7 @@ func (c *Client) rmdir(ctx context.Context, auth eosclient.Authorization, path s return err } -// Remove removes the resource at the given path +// Remove removes the resource at the given path. func (c *Client) Remove(ctx context.Context, auth eosclient.Authorization, path string, noRecycle bool) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Remove").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -1119,7 +1100,7 @@ func (c *Client) Remove(ctx context.Context, auth eosclient.Authorization, path return c.rm(ctx, auth, path, noRecycle) } -// Rename renames the resource referenced by oldPath to newPath +// Rename renames the resource referenced by oldPath to newPath. func (c *Client) Rename(ctx context.Context, auth eosclient.Authorization, oldPath, newPath string) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Rename").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("oldPath", oldPath).Str("newPath", newPath).Msg("") @@ -1152,10 +1133,9 @@ func (c *Client) Rename(ctx context.Context, auth eosclient.Authorization, oldPa log.Debug().Str("func", "Rename").Str("oldPath", oldPath).Str("newPath", newPath).Str("resp:", fmt.Sprintf("%#v", resp)).Msg("grpc response") return err - } -// List the contents of the directory given by path +// List the contents of the directory given by path. func (c *Client) List(ctx context.Context, auth eosclient.Authorization, dpath string) ([]*eosclient.FileInfo, error) { log := appctx.GetLogger(ctx) log.Info().Str("func", "List").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("dpath", dpath).Msg("") @@ -1236,7 +1216,6 @@ func (c *Client) List(ctx context.Context, auth eosclient.Authorization, dpath s } if parent.SysACL != nil { - for _, info := range mylst { if !info.IsDir && parent != nil { if info.SysACL == nil { @@ -1250,7 +1229,6 @@ func (c *Client) List(ctx context.Context, auth eosclient.Authorization, dpath s } return mylst, nil - } // Read reads a file from the mgm and returns a handle to read it @@ -1260,7 +1238,7 @@ func (c *Client) List(ctx context.Context, auth eosclient.Authorization, dpath s // itself, e.g. strange timeouts or TCP issues may be more difficult to trace // // Let's consider this experimental for the moment, maybe I'll like to add a config -// parameter to choose between the two behaviours +// parameter to choose between the two behaviours. func (c *Client) Read(ctx context.Context, auth eosclient.Authorization, path string) (io.ReadCloser, error) { log := appctx.GetLogger(ctx) log.Info().Str("func", "Read").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -1294,7 +1272,7 @@ func (c *Client) Read(ctx context.Context, auth eosclient.Authorization, path st } // Write writes a file to the mgm -// Somehow the same considerations as Read apply +// Somehow the same considerations as Read apply. func (c *Client) Write(ctx context.Context, auth eosclient.Authorization, path string, stream io.ReadCloser) error { log := appctx.GetLogger(ctx) log.Info().Str("func", "Write").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Msg("") @@ -1332,9 +1310,8 @@ func (c *Client) Write(ctx context.Context, auth eosclient.Authorization, path s // return c.WriteFile(ctx, uid, gid, path, fd.Name()) } -// WriteFile writes an existing file to the mgm. Old xrdcp utility +// WriteFile writes an existing file to the mgm. Old xrdcp utility. func (c *Client) WriteFile(ctx context.Context, auth eosclient.Authorization, path, source string) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "WriteFile").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Str("source", source).Msg("") @@ -1342,7 +1319,6 @@ func (c *Client) WriteFile(ctx context.Context, auth eosclient.Authorization, pa cmd := exec.CommandContext(ctx, c.opt.XrdcopyBinary, "--nopbar", "--silent", "-f", source, xrdPath, fmt.Sprintf("-ODeos.ruid=%s&eos.rgid=%s", auth.Role.UID, auth.Role.GID)) _, _, err := c.execute(ctx, cmd) return err - } // ListDeletedEntries returns a list of the deleted entries. @@ -1491,7 +1467,6 @@ func (c *Client) ListVersions(ctx context.Context, auth eosclient.Authorization, // RollbackToVersion rollbacks a file to a previous version. func (c *Client) RollbackToVersion(ctx context.Context, auth eosclient.Authorization, path, version string) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "RollbackToVersion").Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", path).Str("version", version).Msg("") @@ -1524,7 +1499,6 @@ func (c *Client) RollbackToVersion(ctx context.Context, auth eosclient.Authoriza log.Info().Str("func", "RollbackToVersion").Int64("errcode", resp.GetError().Code).Str("errmsg", resp.GetError().Msg).Msg("grpc response") return err - } // ReadVersion reads the version for the given file. @@ -1536,7 +1510,7 @@ func (c *Client) ReadVersion(ctx context.Context, auth eosclient.Authorization, return c.Read(ctx, auth, versionFile) } -// GenerateToken returns a token on behalf of the resource owner to be used by lightweight accounts +// GenerateToken returns a token on behalf of the resource owner to be used by lightweight accounts. func (c *Client) GenerateToken(ctx context.Context, auth eosclient.Authorization, path string, a *acl.Entry) (string, error) { return "", errtypes.NotSupported("TODO") } @@ -1620,7 +1594,6 @@ func (c *Client) grpcMDResponseToFileInfo(st *erpc.MDResponse, namepfx string) ( fi.XS = xs log.Debug().Str("stat info - path", fi.File).Uint64("inode", fi.Inode).Uint64("uid", fi.UID).Uint64("gid", fi.GID).Str("etag", fi.ETag).Str("checksum", fi.XS.XSType+":"+fi.XS.XSSum).Msg("grpc response") - } else { fi.Inode = st.Cmd.Id fi.UID = st.Cmd.Uid @@ -1651,7 +1624,7 @@ func (c *Client) grpcMDResponseToFileInfo(st *erpc.MDResponse, namepfx string) ( return fi, nil } -// exec executes the command and returns the stdout, stderr and return code +// exec executes the command and returns the stdout, stderr and return code. func (c *Client) execute(ctx context.Context, cmd *exec.Cmd) (string, string, error) { log := appctx.GetLogger(ctx) @@ -1678,7 +1651,6 @@ func (c *Client) execute(ctx context.Context, cmd *exec.Cmd) (string, string, er // defined for both Unix and Windows and in both cases has // an ExitStatus() method with the same signature. if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { - exitStatus = status.ExitStatus() switch exitStatus { case 0: diff --git a/pkg/eosclient/eosgrpc/eoshttp.go b/pkg/eosclient/eosgrpc/eoshttp.go index 1ec18a804e8..53f85e9dae1 100644 --- a/pkg/eosclient/eosgrpc/eoshttp.go +++ b/pkg/eosclient/eosgrpc/eoshttp.go @@ -78,9 +78,8 @@ type HTTPOptions struct { ClientCAFiles string } -// Init fills the basic fields +// Init fills the basic fields. func (opt *HTTPOptions) init() { - if opt.BaseURL == "" { opt.BaseURL = "https://eos-example.org" } @@ -127,7 +126,7 @@ func (opt *HTTPOptions) init() { // EOSHTTPClient performs HTTP-based tasks (e.g. upload, download) // against a EOS management node (MGM) // using the EOS XrdHTTP interface. -// In this module we wrap eos-related behaviour, e.g. headers or r/w retries +// In this module we wrap eos-related behaviour, e.g. headers or r/w retries. type EOSHTTPClient struct { opt *HTTPOptions cl *http.Client @@ -177,7 +176,7 @@ func NewEOSHTTPClient(opt *HTTPOptions) (*EOSHTTPClient, error) { }, nil } -// Format a human readable line that describes a response +// Format a human readable line that describes a response. func rspdesc(rsp *http.Response) string { desc := "'" + fmt.Sprintf("%d", rsp.StatusCode) + "'" + ": '" + rsp.Status + "'" @@ -197,7 +196,7 @@ func rspdesc(rsp *http.Response) string { } // If the error is not nil, take that -// If there is an error coming from EOS, erturn a descriptive error +// If there is an error coming from EOS, erturn a descriptive error. func (c *EOSHTTPClient) getRespError(rsp *http.Response, err error) error { if err != nil { return err @@ -219,9 +218,8 @@ func (c *EOSHTTPClient) getRespError(rsp *http.Response, err error) error { return errtypes.InternalError("Err from EOS: " + rspdesc(rsp)) } -// From the basepath and the file path... build an url +// From the basepath and the file path... build an url. func (c *EOSHTTPClient) buildFullURL(urlpath string, auth eosclient.Authorization) (string, error) { - u, err := url.Parse(c.opt.BaseURL) if err != nil { return "", err @@ -249,9 +247,8 @@ func (c *EOSHTTPClient) buildFullURL(urlpath string, auth eosclient.Authorizatio return u.String(), nil } -// GETFile does an entire GET to download a full file. Returns a stream to read the content from +// GETFile does an entire GET to download a full file. Returns a stream to read the content from. func (c *EOSHTTPClient) GETFile(ctx context.Context, remoteuser string, auth eosclient.Authorization, urlpath string, stream io.WriteCloser) (io.ReadCloser, error) { - log := appctx.GetLogger(ctx) log.Info().Str("func", "GETFile").Str("remoteuser", remoteuser).Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", urlpath).Msg("") @@ -287,7 +284,6 @@ func (c *EOSHTTPClient) GETFile(ctx context.Context, remoteuser string, auth eos // Let's support redirections... and if we retry we have to retry at the same FST, avoid going back to the MGM if resp != nil && (resp.StatusCode == http.StatusFound || resp.StatusCode == http.StatusTemporaryRedirect) { - // io.Copy(ioutil.Discard, resp.Body) // resp.Body.Close() @@ -338,12 +334,10 @@ func (c *EOSHTTPClient) GETFile(ctx context.Context, remoteuser string, auth eos // If we have not been given a stream to write into then return our stream to read from return resp.Body, nil } - } -// PUTFile does an entire PUT to upload a full file, taking the data from a stream +// PUTFile does an entire PUT to upload a full file, taking the data from a stream. func (c *EOSHTTPClient) PUTFile(ctx context.Context, remoteuser string, auth eosclient.Authorization, urlpath string, stream io.ReadCloser, length int64) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "PUTFile").Str("remoteuser", remoteuser).Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", urlpath).Int64("length", length).Msg("") @@ -381,7 +375,6 @@ func (c *EOSHTTPClient) PUTFile(ctx context.Context, remoteuser string, auth eos // Let's support redirections... and if we retry we retry at the same FST if resp != nil && resp.StatusCode == 307 { - // io.Copy(ioutil.Discard, resp.Body) // resp.Body.Close() @@ -399,7 +392,6 @@ func (c *EOSHTTPClient) PUTFile(ctx context.Context, remoteuser string, auth eos if length >= 0 { log.Debug().Str("func", "PUTFile").Int64("Content-Length", length).Msg("setting header") req.Header.Set("Content-Length", strconv.FormatInt(length, 10)) - } if err != nil { log.Error().Str("func", "PUTFile").Str("url", loc.String()).Str("err", err.Error()).Msg("can't create redirected request") @@ -408,7 +400,6 @@ func (c *EOSHTTPClient) PUTFile(ctx context.Context, remoteuser string, auth eos if length >= 0 { log.Debug().Str("func", "PUTFile").Int64("Content-Length", length).Msg("setting header") req.Header.Set("Content-Length", strconv.FormatInt(length, 10)) - } log.Debug().Str("func", "PUTFile").Str("location", loc.String()).Msg("redirection") @@ -437,12 +428,10 @@ func (c *EOSHTTPClient) PUTFile(ctx context.Context, remoteuser string, auth eos return nil } - } -// Head performs a HEAD req. Useful to check the server +// Head performs a HEAD req. Useful to check the server. func (c *EOSHTTPClient) Head(ctx context.Context, remoteuser string, auth eosclient.Authorization, urlpath string) error { - log := appctx.GetLogger(ctx) log.Info().Str("func", "Head").Str("remoteuser", remoteuser).Str("uid,gid", auth.Role.UID+","+auth.Role.GID).Str("path", urlpath).Msg("") @@ -489,5 +478,4 @@ func (c *EOSHTTPClient) Head(ctx context.Context, remoteuser string, auth eoscli } } // return nil - } diff --git a/pkg/eosclient/utils.go b/pkg/eosclient/utils.go index 8b04ebfb99a..e0e2c834718 100644 --- a/pkg/eosclient/utils.go +++ b/pkg/eosclient/utils.go @@ -27,7 +27,7 @@ const ( UserAttr ) -// AttrStringToType converts a string to an AttrType +// AttrStringToType converts a string to an AttrType. func AttrStringToType(t string) (AttrType, error) { switch t { case "sys": diff --git a/pkg/errtypes/errtypes.go b/pkg/errtypes/errtypes.go index c897856b6fd..6bc248438bb 100644 --- a/pkg/errtypes/errtypes.go +++ b/pkg/errtypes/errtypes.go @@ -30,7 +30,7 @@ func (e NotFound) Error() string { return "error: not found: " + string(e) } // IsNotFound implements the IsNotFound interface. func (e NotFound) IsNotFound() {} -// InternalError is the error to use when we really don't know what happened. Use with care +// InternalError is the error to use when we really don't know what happened. Use with care. type InternalError string func (e InternalError) Error() string { return "internal error: " + string(e) } @@ -135,7 +135,7 @@ type IsAlreadyExists interface { } // IsInternalError is the interface to implement -// to specify that there was some internal error +// to specify that there was some internal error. type IsInternalError interface { IsInternalError() } diff --git a/pkg/events/events.go b/pkg/events/events.go index 40b461144e0..2c3f2adf676 100644 --- a/pkg/events/events.go +++ b/pkg/events/events.go @@ -29,30 +29,30 @@ var ( // MainQueueName is the name of the main queue // All events will go through here as they are forwarded to the consumer via the // group name - // TODO: "fan-out" so not all events go through the same queue? requires investigation + // TODO: "fan-out" so not all events go through the same queue? requires investigation. MainQueueName = "main-queue" - // MetadatakeyEventType is the key used for the eventtype in the metadata map of the event + // MetadatakeyEventType is the key used for the eventtype in the metadata map of the event. MetadatakeyEventType = "eventtype" ) type ( - // Unmarshaller is the interface events need to fulfill + // Unmarshaller is the interface events need to fulfill. Unmarshaller interface { Unmarshal([]byte) (interface{}, error) } - // Publisher is the interface publishers need to fulfill + // Publisher is the interface publishers need to fulfill. Publisher interface { Publish(string, interface{}, ...events.PublishOption) error } - // Consumer is the interface consumer need to fulfill + // Consumer is the interface consumer need to fulfill. Consumer interface { Consume(string, ...events.ConsumeOption) (<-chan events.Event, error) } - // Stream is the interface common to Publisher and Consumer + // Stream is the interface common to Publisher and Consumer. Stream interface { Publish(string, interface{}, ...events.PublishOption) error Consume(string, ...events.ConsumeOption) (<-chan events.Event, error) @@ -61,7 +61,7 @@ type ( // Consume returns a channel that will get all events that match the given evs // group defines the service type: One group will get exactly one copy of a event that is emitted -// NOTE: uses reflect on initialization +// NOTE: uses reflect on initialization. func Consume(s Consumer, group string, evs ...Unmarshaller) (<-chan interface{}, error) { c, err := s.Consume(MainQueueName, events.WithGroup(group)) if err != nil { @@ -98,7 +98,7 @@ func Consume(s Consumer, group string, evs ...Unmarshaller) (<-chan interface{}, } // Publish publishes the ev to the MainQueue from where it is distributed to all subscribers -// NOTE: needs to use reflect on runtime +// NOTE: needs to use reflect on runtime. func Publish(s Publisher, ev interface{}) error { evName := reflect.TypeOf(ev).String() return s.Publish(MainQueueName, ev, events.WithMetadata(map[string]string{ diff --git a/pkg/events/example/consumer/consumer.go b/pkg/events/example/consumer/consumer.go index caeaac2e161..747c638fbdb 100644 --- a/pkg/events/example/consumer/consumer.go +++ b/pkg/events/example/consumer/consumer.go @@ -26,7 +26,7 @@ import ( "github.com/cs3org/reva/pkg/events" ) -// Example consumes events from the queue +// Example consumes events from the queue. func Example(c events.Consumer) { // Step 1 - which group does the consumer belong to? // each group will get each event that is emitted, but only one member of the group will get it. @@ -56,5 +56,4 @@ func Example(c events.Consumer) { fmt.Printf("%s) Unregistered event: %+v\n", group, v) } } - } diff --git a/pkg/events/example/example.go b/pkg/events/example/example.go index 9240fc74db7..c7dd89631c4 100644 --- a/pkg/events/example/example.go +++ b/pkg/events/example/example.go @@ -29,7 +29,7 @@ import ( "github.com/cs3org/reva/pkg/events/server" ) -// Simple example of an event workflow +// Simple example of an event workflow. func main() { // start a server Server() @@ -48,10 +48,9 @@ func main() { // wait for consumer go-routine to print time.Sleep(500 * time.Millisecond) - } -// Server generates a nats server +// Server generates a nats server. func Server() { err := server.RunNatsServer() if err != nil { @@ -59,12 +58,11 @@ func Server() { } } -// Client builds a nats client +// Client builds a nats client. func Client() events.Stream { c, err := server.NewNatsStream(nats.Address("127.0.0.1:4222"), nats.ClusterID("test-cluster")) if err != nil { log.Fatal(err) } return c - } diff --git a/pkg/events/example/publisher/publisher.go b/pkg/events/example/publisher/publisher.go index ac7ccd686ac..9988196bab4 100644 --- a/pkg/events/example/publisher/publisher.go +++ b/pkg/events/example/publisher/publisher.go @@ -26,7 +26,7 @@ import ( "github.com/cs3org/reva/pkg/events" ) -// Example publishes events to the queue +// Example publishes events to the queue. func Example(p events.Publisher) { // nothing to do - just publish! err := events.Publish(p, events.ShareCreated{ @@ -40,5 +40,4 @@ func Example(p events.Publisher) { if err != nil { log.Fatal(err) } - } diff --git a/pkg/events/server/nats.go b/pkg/events/server/nats.go index a205b75ccef..b79ae6bdb8e 100644 --- a/pkg/events/server/nats.go +++ b/pkg/events/server/nats.go @@ -23,12 +23,11 @@ import ( "github.com/asim/go-micro/plugins/events/nats/v4" "github.com/cenkalti/backoff" - "go-micro.dev/v4/events" - stanServer "github.com/nats-io/nats-streaming-server/server" + "go-micro.dev/v4/events" ) -// RunNatsServer runs the nats streaming server +// RunNatsServer runs the nats streaming server. func RunNatsServer(opts ...Option) error { natsOpts := stanServer.DefaultNatsServerOptions stanOpts := stanServer.GetDefaultOptions() @@ -41,7 +40,7 @@ func RunNatsServer(opts ...Option) error { } // NewNatsStream returns a streaming client used by `Consume` and `Publish` methods -// retries exponentially to connect to a nats server +// retries exponentially to connect to a nats server. func NewNatsStream(opts ...nats.Option) (events.Stream, error) { b := backoff.NewExponentialBackOff() var stream events.Stream diff --git a/pkg/events/server/options.go b/pkg/events/server/options.go index 2cb40fa3ae8..65cb5114384 100644 --- a/pkg/events/server/options.go +++ b/pkg/events/server/options.go @@ -23,31 +23,31 @@ import ( stanServer "github.com/nats-io/nats-streaming-server/server" ) -// Option configures the nats server +// Option configures the nats server. type Option func(*natsServer.Options, *stanServer.Options) -// Host sets the host URL for the nats server +// Host sets the host URL for the nats server. func Host(url string) Option { return func(no *natsServer.Options, _ *stanServer.Options) { no.Host = url } } -// Port sets the host URL for the nats server +// Port sets the host URL for the nats server. func Port(port int) Option { return func(no *natsServer.Options, _ *stanServer.Options) { no.Port = port } } -// NatsOpts allows setting Options from nats package directly +// NatsOpts allows setting Options from nats package directly. func NatsOpts(opt func(*natsServer.Options)) Option { return func(no *natsServer.Options, _ *stanServer.Options) { opt(no) } } -// StanOpts allows setting Options from stan package directly +// StanOpts allows setting Options from stan package directly. func StanOpts(opt func(*stanServer.Options)) Option { return func(_ *natsServer.Options, so *stanServer.Options) { opt(so) diff --git a/pkg/events/types.go b/pkg/events/types.go index 3ca9dd7f802..294f0f6d981 100644 --- a/pkg/events/types.go +++ b/pkg/events/types.go @@ -27,7 +27,7 @@ import ( types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" ) -// ShareCreated is emitted when a share is created +// ShareCreated is emitted when a share is created. type ShareCreated struct { // TODO: Rename to ShareCreatedEvent? Sharer *user.UserId // split the protobuf Grantee oneof so we can use stdlib encoding/json @@ -38,7 +38,7 @@ type ShareCreated struct { // TODO: Rename to ShareCreatedEvent? CTime *types.Timestamp } -// Unmarshal to fulfill umarshaller interface +// Unmarshal to fulfill umarshaller interface. func (ShareCreated) Unmarshal(v []byte) (interface{}, error) { e := ShareCreated{} err := json.Unmarshal(v, &e) diff --git a/pkg/group/manager/ldap/ldap.go b/pkg/group/manager/ldap/ldap.go index 9b66d570f79..9b5b950807c 100644 --- a/pkg/group/manager/ldap/ldap.go +++ b/pkg/group/manager/ldap/ldap.go @@ -76,7 +76,7 @@ type attributes struct { GIDNumber string `mapstructure:"gidNumber"` } -// Default attributes (Active Directory) +// Default attributes (Active Directory). var ldapDefaults = attributes{ DN: "dn", GID: "objectGUID", // you can fall back to samaccountname but you will run into trouble when group names change. You have been warned. diff --git a/pkg/group/manager/loader/loader.go b/pkg/group/manager/loader/loader.go index 04d40f66be6..2c4b87a8c6c 100644 --- a/pkg/group/manager/loader/loader.go +++ b/pkg/group/manager/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load core group manager drivers. _ "github.com/cs3org/reva/pkg/group/manager/json" _ "github.com/cs3org/reva/pkg/group/manager/ldap" - // Add your own here + // Add your own here. ) diff --git a/pkg/mentix/connectors/connector.go b/pkg/mentix/connectors/connector.go old mode 100755 new mode 100644 index 1d9504819be..7647a774867 --- a/pkg/mentix/connectors/connector.go +++ b/pkg/mentix/connectors/connector.go @@ -21,11 +21,10 @@ package connectors import ( "fmt" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/entity" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // Connector is the interface that all connectors must implement. diff --git a/pkg/mentix/connectors/connectors.go b/pkg/mentix/connectors/connectors.go index ceae58107e9..7f2b19665bb 100644 --- a/pkg/mentix/connectors/connectors.go +++ b/pkg/mentix/connectors/connectors.go @@ -19,10 +19,9 @@ package connectors import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/entity" + "github.com/rs/zerolog" ) var ( diff --git a/pkg/mentix/connectors/gocdb.go b/pkg/mentix/connectors/gocdb.go old mode 100755 new mode 100644 index 43f71556ae3..10c7a3c0e15 --- a/pkg/mentix/connectors/gocdb.go +++ b/pkg/mentix/connectors/gocdb.go @@ -26,13 +26,12 @@ import ( "strings" "time" - "github.com/cs3org/reva/pkg/mentix/utils" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/connectors/gocdb" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/cs3org/reva/pkg/mentix/utils" "github.com/cs3org/reva/pkg/mentix/utils/network" + "github.com/rs/zerolog" ) // GOCDBConnector is used to read mesh data from a GOCDB instance. diff --git a/pkg/mentix/entity/entities.go b/pkg/mentix/entity/entities.go index cb18220f6e6..c96c5046b1f 100644 --- a/pkg/mentix/entity/entities.go +++ b/pkg/mentix/entity/entities.go @@ -22,7 +22,6 @@ import ( "fmt" "github.com/cs3org/reva/pkg/mentix/config" - "github.com/rs/zerolog" ) diff --git a/pkg/mentix/entity/entity.go b/pkg/mentix/entity/entity.go index c4f051de641..6f1c8cd62c2 100644 --- a/pkg/mentix/entity/entity.go +++ b/pkg/mentix/entity/entity.go @@ -20,7 +20,6 @@ package entity import ( "github.com/cs3org/reva/pkg/mentix/config" - "github.com/rs/zerolog" ) diff --git a/pkg/mentix/exchangers/exchanger.go b/pkg/mentix/exchangers/exchanger.go index 91def668229..3b95f0995e2 100644 --- a/pkg/mentix/exchangers/exchanger.go +++ b/pkg/mentix/exchangers/exchanger.go @@ -23,11 +23,10 @@ import ( "strings" "sync" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/entity" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // Exchanger is the base interface for importers and exporters. diff --git a/pkg/mentix/exchangers/exporters/cs3api.go b/pkg/mentix/exchangers/exporters/cs3api.go old mode 100755 new mode 100644 index 983c6610701..5dbd9093382 --- a/pkg/mentix/exchangers/exporters/cs3api.go +++ b/pkg/mentix/exchangers/exporters/cs3api.go @@ -19,10 +19,9 @@ package exporters import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers/exporters/cs3api" + "github.com/rs/zerolog" ) // CS3APIExporter implements the CS3API exporter. diff --git a/pkg/mentix/exchangers/exporters/cs3api/query.go b/pkg/mentix/exchangers/exporters/cs3api/query.go old mode 100755 new mode 100644 index 6f7154e827d..5ade015f035 --- a/pkg/mentix/exchangers/exporters/cs3api/query.go +++ b/pkg/mentix/exchangers/exporters/cs3api/query.go @@ -26,11 +26,10 @@ import ( "strings" ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" - "github.com/cs3org/reva/pkg/mentix/utils" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/cs3org/reva/pkg/mentix/utils" + "github.com/rs/zerolog" ) // HandleDefaultQuery processes a basic query. diff --git a/pkg/mentix/exchangers/exporters/exporters.go b/pkg/mentix/exchangers/exporters/exporters.go index 98d60401003..de6779113b0 100644 --- a/pkg/mentix/exchangers/exporters/exporters.go +++ b/pkg/mentix/exchangers/exporters/exporters.go @@ -19,11 +19,10 @@ package exporters import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/entity" "github.com/cs3org/reva/pkg/mentix/exchangers" + "github.com/rs/zerolog" ) // Collection represents a collection of exporters. diff --git a/pkg/mentix/exchangers/exporters/promsd.go b/pkg/mentix/exchangers/exporters/promsd.go old mode 100755 new mode 100644 index ce7eeb2dc66..cec68c70837 --- a/pkg/mentix/exchangers/exporters/promsd.go +++ b/pkg/mentix/exchangers/exporters/promsd.go @@ -27,12 +27,11 @@ import ( "path/filepath" "strings" - "github.com/cs3org/reva/pkg/mentix/utils" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers/exporters/prometheus" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/cs3org/reva/pkg/mentix/utils" + "github.com/rs/zerolog" ) type prometheusSDScrapeCreatorCallback = func(op *meshdata.Operator, site *meshdata.Site, service *meshdata.Service, endpoint *meshdata.ServiceEndpoint) *prometheus.ScrapeConfig diff --git a/pkg/mentix/exchangers/exporters/reqexporter.go b/pkg/mentix/exchangers/exporters/reqexporter.go index c7668cf8043..6e2772fe963 100644 --- a/pkg/mentix/exchangers/exporters/reqexporter.go +++ b/pkg/mentix/exchangers/exporters/reqexporter.go @@ -23,10 +23,9 @@ import ( "net/http" "net/url" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers" + "github.com/rs/zerolog" ) // BaseRequestExporter implements basic exporter functionality common to all request exporters. diff --git a/pkg/mentix/exchangers/exporters/siteloc/query.go b/pkg/mentix/exchangers/exporters/siteloc/query.go old mode 100755 new mode 100644 index 2f478d9fc9a..090e7848190 --- a/pkg/mentix/exchangers/exporters/siteloc/query.go +++ b/pkg/mentix/exchangers/exporters/siteloc/query.go @@ -24,10 +24,9 @@ import ( "net/http" "net/url" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // HandleDefaultQuery processes a basic query. diff --git a/pkg/mentix/exchangers/exporters/sitelocations.go b/pkg/mentix/exchangers/exporters/sitelocations.go old mode 100755 new mode 100644 index d3f8f1b3524..e649617b491 --- a/pkg/mentix/exchangers/exporters/sitelocations.go +++ b/pkg/mentix/exchangers/exporters/sitelocations.go @@ -19,10 +19,9 @@ package exporters import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers/exporters/siteloc" + "github.com/rs/zerolog" ) // SiteLocationsExporter implements the Site Locations exporter to use with Grafana. diff --git a/pkg/mentix/exchangers/exporters/webapi.go b/pkg/mentix/exchangers/exporters/webapi.go old mode 100755 new mode 100644 index 711166446d8..1d586c4e3eb --- a/pkg/mentix/exchangers/exporters/webapi.go +++ b/pkg/mentix/exchangers/exporters/webapi.go @@ -19,10 +19,9 @@ package exporters import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers/exporters/webapi" + "github.com/rs/zerolog" ) // WebAPIExporter implements the generic Web API exporter. diff --git a/pkg/mentix/exchangers/exporters/webapi/query.go b/pkg/mentix/exchangers/exporters/webapi/query.go old mode 100755 new mode 100644 index aa664bdff52..47e168172c5 --- a/pkg/mentix/exchangers/exporters/webapi/query.go +++ b/pkg/mentix/exchangers/exporters/webapi/query.go @@ -24,10 +24,9 @@ import ( "net/http" "net/url" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // HandleDefaultQuery processes a basic query. diff --git a/pkg/mentix/exchangers/importers/importers.go b/pkg/mentix/exchangers/importers/importers.go index da957f10002..97552b72de0 100644 --- a/pkg/mentix/exchangers/importers/importers.go +++ b/pkg/mentix/exchangers/importers/importers.go @@ -19,11 +19,10 @@ package importers import ( - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/entity" "github.com/cs3org/reva/pkg/mentix/exchangers" + "github.com/rs/zerolog" ) // Collection represents a collection of importers. diff --git a/pkg/mentix/exchangers/importers/reqimporter.go b/pkg/mentix/exchangers/importers/reqimporter.go index 4311e2ec18b..79979962a6b 100644 --- a/pkg/mentix/exchangers/importers/reqimporter.go +++ b/pkg/mentix/exchangers/importers/reqimporter.go @@ -23,11 +23,10 @@ import ( "net/http" "net/url" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/exchangers" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // BaseRequestImporter implements basic importer functionality common to all request importers. diff --git a/pkg/mentix/exchangers/reqexchanger.go b/pkg/mentix/exchangers/reqexchanger.go index 7539b4cfa9c..9881e7b5c3e 100644 --- a/pkg/mentix/exchangers/reqexchanger.go +++ b/pkg/mentix/exchangers/reqexchanger.go @@ -24,10 +24,9 @@ import ( "net/url" "strings" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // RequestExchanger is the interface implemented by exchangers that offer an HTTP endpoint. diff --git a/pkg/mentix/mentix.go b/pkg/mentix/mentix.go index 0b07e811f54..a7624643290 100644 --- a/pkg/mentix/mentix.go +++ b/pkg/mentix/mentix.go @@ -24,8 +24,6 @@ import ( "strings" "time" - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/appctx" "github.com/cs3org/reva/pkg/mentix/config" "github.com/cs3org/reva/pkg/mentix/connectors" @@ -34,6 +32,7 @@ import ( "github.com/cs3org/reva/pkg/mentix/exchangers/exporters" "github.com/cs3org/reva/pkg/mentix/exchangers/importers" "github.com/cs3org/reva/pkg/mentix/meshdata" + "github.com/rs/zerolog" ) // Mentix represents the main Mentix service object. diff --git a/pkg/mentix/meshdata/endpoints.go b/pkg/mentix/meshdata/endpoints.go index 3f259489c5e..a1da4abcdc6 100644 --- a/pkg/mentix/meshdata/endpoints.go +++ b/pkg/mentix/meshdata/endpoints.go @@ -19,18 +19,18 @@ package meshdata const ( - // EndpointRevad identifies the main Reva Daemon endpoint + // EndpointRevad identifies the main Reva Daemon endpoint. EndpointRevad = "REVAD" - // EndpointGateway identifies the Gateway endpoint + // EndpointGateway identifies the Gateway endpoint. EndpointGateway = "GATEWAY" - // EndpointMetrics identifies the Metrics endpoint + // EndpointMetrics identifies the Metrics endpoint. EndpointMetrics = "METRICS" - // EndpointWebdav identifies the Webdav endpoint + // EndpointWebdav identifies the Webdav endpoint. EndpointWebdav = "WEBDAV" - // EndpointOCM identifies the OCM endpoint + // EndpointOCM identifies the OCM endpoint. EndpointOCM = "OCM" - // EndpointMeshDir identifies the Mesh Directory endpoint + // EndpointMeshDir identifies the Mesh Directory endpoint. EndpointMeshDir = "MESHDIR" ) diff --git a/pkg/metrics/config/config.go b/pkg/metrics/config/config.go index 7cec96f6766..a77c7ffb29c 100644 --- a/pkg/metrics/config/config.go +++ b/pkg/metrics/config/config.go @@ -18,7 +18,7 @@ package config -// Config holds the config options that need to be passed down to the metrics reader(driver) +// Config holds the config options that need to be passed down to the metrics reader(driver). type Config struct { MetricsDataDriverType string `mapstructure:"metrics_data_driver_type"` MetricsDataLocation string `mapstructure:"metrics_data_location"` @@ -28,7 +28,7 @@ type Config struct { InsecureSkipVerify bool `mapstructure:"insecure_skip_verify"` } -// Init sets sane defaults +// Init sets sane defaults. func (c *Config) Init() { if c.MetricsDataDriverType == "json" { // default values diff --git a/pkg/metrics/driver/dummy/dummy.go b/pkg/metrics/driver/dummy/dummy.go index 6eb1068471d..86b146afffb 100644 --- a/pkg/metrics/driver/dummy/dummy.go +++ b/pkg/metrics/driver/dummy/dummy.go @@ -34,27 +34,27 @@ func driverName() string { return "dummy" } -// MetricsDummyDriver the MetricsDummyDriver struct +// MetricsDummyDriver the MetricsDummyDriver struct. type MetricsDummyDriver struct { } -// Configure configures this driver +// Configure configures this driver. func (d *MetricsDummyDriver) Configure(c *config.Config) error { // no configuration necessary return nil } -// GetNumUsers returns the number of site users; it's a random number +// GetNumUsers returns the number of site users; it's a random number. func (d *MetricsDummyDriver) GetNumUsers() int64 { return int64(rand.Intn(30000)) } -// GetNumGroups returns the number of site groups; it's a random number +// GetNumGroups returns the number of site groups; it's a random number. func (d *MetricsDummyDriver) GetNumGroups() int64 { return int64(rand.Intn(200)) } -// GetAmountStorage returns the amount of site storage used; it's a random amount +// GetAmountStorage returns the amount of site storage used; it's a random amount. func (d *MetricsDummyDriver) GetAmountStorage() int64 { return rand.Int63n(70000000000) } diff --git a/pkg/metrics/driver/json/json.go b/pkg/metrics/driver/json/json.go index ac4b28ce017..8c38292c1b7 100644 --- a/pkg/metrics/driver/json/json.go +++ b/pkg/metrics/driver/json/json.go @@ -23,10 +23,9 @@ import ( "errors" "os" - "github.com/cs3org/reva/pkg/metrics/driver/registry" - "github.com/cs3org/reva/pkg/logger" "github.com/cs3org/reva/pkg/metrics/config" + "github.com/cs3org/reva/pkg/metrics/driver/registry" "github.com/rs/zerolog" ) @@ -64,15 +63,15 @@ type data struct { AmountStorage int64 `json:"cs3_org_sciencemesh_site_total_amount_storage"` } -// MetricsJSONDriver the JsonDriver struct +// MetricsJSONDriver the JsonDriver struct. type MetricsJSONDriver struct { metricsDataLocation string } -// Configure configures this driver +// Configure configures this driver. func (d *MetricsJSONDriver) Configure(c *config.Config) error { if c.MetricsDataLocation == "" { - err := errors.New("Unable to initialize a metrics data driver, has the data location (metrics_data_location) been configured?") + err := errors.New("unable to initialize a metrics data driver, has the data location (metrics_data_location) been configured?") return err } @@ -81,17 +80,17 @@ func (d *MetricsJSONDriver) Configure(c *config.Config) error { return nil } -// GetNumUsers returns the number of site users +// GetNumUsers returns the number of site users. func (d *MetricsJSONDriver) GetNumUsers() int64 { return readJSON(d).NumUsers } -// GetNumGroups returns the number of site groups +// GetNumGroups returns the number of site groups. func (d *MetricsJSONDriver) GetNumGroups() int64 { return readJSON(d).NumGroups } -// GetAmountStorage returns the amount of site storage used +// GetAmountStorage returns the amount of site storage used. func (d *MetricsJSONDriver) GetAmountStorage() int64 { return readJSON(d).AmountStorage } diff --git a/pkg/metrics/driver/loader/loader.go b/pkg/metrics/driver/loader/loader.go index 82fd0ba7f68..92cf9b844fb 100644 --- a/pkg/metrics/driver/loader/loader.go +++ b/pkg/metrics/driver/loader/loader.go @@ -23,5 +23,5 @@ import ( _ "github.com/cs3org/reva/pkg/metrics/driver/dummy" _ "github.com/cs3org/reva/pkg/metrics/driver/json" _ "github.com/cs3org/reva/pkg/metrics/driver/xcloud" - // Add your own here + // Add your own here. ) diff --git a/pkg/metrics/driver/registry/registry.go b/pkg/metrics/driver/registry/registry.go index a92fde44637..55dfe977415 100644 --- a/pkg/metrics/driver/registry/registry.go +++ b/pkg/metrics/driver/registry/registry.go @@ -24,7 +24,7 @@ import ( var drivers map[string]reader.Reader // map key is driver type name -// Register register a driver +// Register register a driver. func Register(driverName string, r reader.Reader) { if drivers == nil { drivers = make(map[string]reader.Reader) @@ -32,7 +32,7 @@ func Register(driverName string, r reader.Reader) { drivers[driverName] = r } -// GetDriver returns the registered driver for the specified driver name, or nil if it is not registered +// GetDriver returns the registered driver for the specified driver name, or nil if it is not registered. func GetDriver(driverName string) reader.Reader { driver, found := drivers[driverName] if found { diff --git a/pkg/metrics/driver/xcloud/xcloud.go b/pkg/metrics/driver/xcloud/xcloud.go index 553c68b1463..bd37ebf8af0 100644 --- a/pkg/metrics/driver/xcloud/xcloud.go +++ b/pkg/metrics/driver/xcloud/xcloud.go @@ -29,12 +29,10 @@ import ( "sync" "time" - "github.com/cs3org/reva/pkg/metrics/driver/registry" - - "github.com/rs/zerolog" - "github.com/cs3org/reva/pkg/logger" "github.com/cs3org/reva/pkg/metrics/config" + "github.com/cs3org/reva/pkg/metrics/driver/registry" + "github.com/rs/zerolog" ) var log zerolog.Logger @@ -49,7 +47,7 @@ func driverName() string { return "xcloud" } -// CloudDriver is the driver to use for Sciencemesh apps +// CloudDriver is the driver to use for Sciencemesh apps. type CloudDriver struct { instance string pullInterval int @@ -102,7 +100,7 @@ func (d *CloudDriver) refresh() error { return nil } -// Configure configures this driver +// Configure configures this driver. func (d *CloudDriver) Configure(c *config.Config) error { if c.XcloudInstance == "" { err := errors.New("xcloud: missing xcloud_instance config parameter") @@ -143,35 +141,35 @@ func (d *CloudDriver) Configure(c *config.Config) error { return nil } -// GetNumUsers returns the number of site users +// GetNumUsers returns the number of site users. func (d *CloudDriver) GetNumUsers() int64 { return d.CloudData.Metrics.TotalUsers } -// GetNumGroups returns the number of site groups +// GetNumGroups returns the number of site groups. func (d *CloudDriver) GetNumGroups() int64 { return d.CloudData.Metrics.TotalGroups } -// GetAmountStorage returns the amount of site storage used +// GetAmountStorage returns the amount of site storage used. func (d *CloudDriver) GetAmountStorage() int64 { return d.CloudData.Metrics.TotalStorage } -// CloudData represents the information obtained from the sciencemesh app +// CloudData represents the information obtained from the sciencemesh app. type CloudData struct { Metrics CloudDataMetrics `json:"metrics"` Settings CloudDataSettings `json:"settings"` } -// CloudDataMetrics reprents the metrics gathered from the sciencemesh app +// CloudDataMetrics reprents the metrics gathered from the sciencemesh app. type CloudDataMetrics struct { TotalUsers int64 `json:"numusers"` TotalGroups int64 `json:"numgroups"` TotalStorage int64 `json:"numstorage"` } -// CloudDataSettings represents the metrics gathered +// CloudDataSettings represents the metrics gathered. type CloudDataSettings struct { IOPUrl string `json:"iopurl"` Sitename string `json:"sitename"` diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index ec3fd12fb1f..2311e13b591 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -27,16 +27,15 @@ import ( "os" "time" + "github.com/cs3org/reva/pkg/logger" "github.com/cs3org/reva/pkg/metrics/config" "github.com/cs3org/reva/pkg/metrics/driver/registry" "github.com/cs3org/reva/pkg/metrics/reader" - - "github.com/cs3org/reva/pkg/logger" "go.opencensus.io/stats" "go.opencensus.io/stats/view" ) -// Init intializes metrics according to the specified configuration +// Init intializes metrics according to the specified configuration. func Init(conf *config.Config) error { log := logger.New().With().Int("pid", os.Getpid()).Logger() @@ -82,7 +81,7 @@ func Init(conf *config.Config) error { return nil } -// Metrics the metrics struct +// Metrics the metrics struct. type Metrics struct { dataDriver reader.Reader // the metrics data driver is an implemention of Reader NumUsersMeasure *stats.Int64Measure @@ -101,7 +100,7 @@ func (m *Metrics) recordMetrics() error { return nil } -// recordNumUsers records the latest number of site users figure +// recordNumUsers records the latest number of site users figure. func (m *Metrics) recordNumUsers() { ctx := context.Background() stats.Record(ctx, m.NumUsersMeasure.M(m.dataDriver.GetNumUsers())) @@ -116,7 +115,7 @@ func (m *Metrics) getNumUsersView() *view.View { } } -// recordNumGroups records the latest number of site groups figure +// recordNumGroups records the latest number of site groups figure. func (m *Metrics) recordNumGroups() { ctx := context.Background() stats.Record(ctx, m.NumGroupsMeasure.M(m.dataDriver.GetNumGroups())) @@ -131,7 +130,7 @@ func (m *Metrics) getNumGroupsView() *view.View { } } -// recordAmountStorage records the latest amount storage figure +// recordAmountStorage records the latest amount storage figure. func (m *Metrics) recordAmountStorage() { ctx := context.Background() stats.Record(ctx, m.AmountStorageMeasure.M(m.dataDriver.GetAmountStorage())) diff --git a/pkg/metrics/reader/reader.go b/pkg/metrics/reader/reader.go index 88189b11d9a..3be512c30d2 100644 --- a/pkg/metrics/reader/reader.go +++ b/pkg/metrics/reader/reader.go @@ -26,7 +26,7 @@ Each metric function should return the current/latest available metrics figure r import "github.com/cs3org/reva/pkg/metrics/config" -// Reader the Reader interface +// Reader the Reader interface. type Reader interface { // Configure configures the reader according to the specified configuration diff --git a/pkg/mime/mime.go b/pkg/mime/mime.go index 50e9a3953fb..5f7a1292680 100644 --- a/pkg/mime/mime.go +++ b/pkg/mime/mime.go @@ -66,7 +66,7 @@ func Detect(isDir bool, fn string) string { return mimeType } -// GetFileExts performs the inverse resolution from mimetype to file extensions +// GetFileExts performs the inverse resolution from mimetype to file extensions. func GetFileExts(mime string) []string { var found []string // first look in our cache diff --git a/pkg/ocm/invite/manager/json/json.go b/pkg/ocm/invite/manager/json/json.go index d82c0ad6d95..03fb907ce53 100644 --- a/pkg/ocm/invite/manager/json/json.go +++ b/pkg/ocm/invite/manager/json/json.go @@ -82,7 +82,6 @@ func (c *config) init() error { // New returns a new invite manager object. func New(m map[string]interface{}) (invite.Manager, error) { - config, err := parseConfig(m) if err != nil { err = errors.Wrap(err, "error parsing config for json invite manager") @@ -122,7 +121,6 @@ func parseConfig(m map[string]interface{}) (*config, error) { } func loadOrCreate(file string) (*inviteModel, error) { - _, err := os.Stat(file) if os.IsNotExist(err) { if err := os.WriteFile(file, []byte("{}"), 0700); err != nil { @@ -177,7 +175,6 @@ func (model *inviteModel) Save() error { } func (m *manager) GenerateToken(ctx context.Context) (*invitepb.InviteToken, error) { - contexUser := ctxpkg.ContextMustGetUser(ctx) inviteToken, err := token.CreateToken(m.config.Expiration, contexUser.GetId()) if err != nil { @@ -198,7 +195,6 @@ func (m *manager) GenerateToken(ctx context.Context) (*invitepb.InviteToken, err } func (m *manager) ForwardInvite(ctx context.Context, invite *invitepb.InviteToken, originProvider *ocmprovider.ProviderInfo) error { - contextUser := ctxpkg.ContextMustGetUser(ctx) recipientProvider := contextUser.GetId().GetIdp() @@ -246,7 +242,6 @@ func (m *manager) ForwardInvite(ctx context.Context, invite *invitepb.InviteToke } func (m *manager) AcceptInvite(ctx context.Context, invite *invitepb.InviteToken, remoteUser *userpb.User) error { - m.Lock() defer m.Unlock() @@ -276,7 +271,6 @@ func (m *manager) AcceptInvite(ctx context.Context, invite *invitepb.InviteToken } func (m *manager) GetAcceptedUser(ctx context.Context, remoteUserID *userpb.UserId) (*userpb.User, error) { - userKey := ctxpkg.ContextMustGetUser(ctx).GetId().GetOpaqueId() for _, acceptedUser := range m.model.AcceptedUsers[userKey] { if (acceptedUser.Id.GetOpaqueId() == remoteUserID.OpaqueId) && (remoteUserID.Idp == "" || acceptedUser.Id.GetIdp() == remoteUserID.Idp) { diff --git a/pkg/ocm/invite/manager/loader/loader.go b/pkg/ocm/invite/manager/loader/loader.go index 4f531f96390..e7db4a424ef 100644 --- a/pkg/ocm/invite/manager/loader/loader.go +++ b/pkg/ocm/invite/manager/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load core share manager drivers. _ "github.com/cs3org/reva/pkg/ocm/invite/manager/json" _ "github.com/cs3org/reva/pkg/ocm/invite/manager/memory" - // Add your own here + // Add your own here. ) diff --git a/pkg/ocm/invite/manager/memory/memory.go b/pkg/ocm/invite/manager/memory/memory.go index f5a6ef2cb4e..034153d64b1 100644 --- a/pkg/ocm/invite/manager/memory/memory.go +++ b/pkg/ocm/invite/manager/memory/memory.go @@ -27,12 +27,11 @@ import ( "sync" "time" - ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/errtypes" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" invitepb "github.com/cs3org/go-cs3apis/cs3/ocm/invite/v1beta1" ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" + ctxpkg "github.com/cs3org/reva/pkg/ctx" + "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/ocm/invite" "github.com/cs3org/reva/pkg/ocm/invite/manager/registry" "github.com/cs3org/reva/pkg/ocm/invite/token" @@ -86,7 +85,6 @@ type config struct { } func (m *manager) GenerateToken(ctx context.Context) (*invitepb.InviteToken, error) { - ctxUser := ctxpkg.ContextMustGetUser(ctx) inviteToken, err := token.CreateToken(m.Config.Expiration, ctxUser.GetId()) if err != nil { @@ -98,7 +96,6 @@ func (m *manager) GenerateToken(ctx context.Context) (*invitepb.InviteToken, err } func (m *manager) ForwardInvite(ctx context.Context, invite *invitepb.InviteToken, originProvider *ocmprovider.ProviderInfo) error { - contextUser := ctxpkg.ContextMustGetUser(ctx) requestBody := url.Values{ "token": {invite.GetToken()}, diff --git a/pkg/ocm/invite/token/token.go b/pkg/ocm/invite/token/token.go index 9c7dd3460a6..a0b1a9b8ef6 100644 --- a/pkg/ocm/invite/token/token.go +++ b/pkg/ocm/invite/token/token.go @@ -33,7 +33,6 @@ const DefaultExpirationTime = "24h" // CreateToken creates a InviteToken object for the userID indicated by userID. func CreateToken(expiration string, userID *userpb.UserId) (*invitepb.InviteToken, error) { - // Parse time of expiration duration, err := time.ParseDuration(expiration) if err != nil { diff --git a/pkg/ocm/invite/token/token_test.go b/pkg/ocm/invite/token/token_test.go index 1938c73d825..113528de892 100644 --- a/pkg/ocm/invite/token/token_test.go +++ b/pkg/ocm/invite/token/token_test.go @@ -26,7 +26,6 @@ import ( ) func TestCreateToken(t *testing.T) { - user := userpb.User{ Id: &userpb.UserId{ Idp: "http://localhost:20080", @@ -57,7 +56,6 @@ func TestCreateToken(t *testing.T) { } func TestCreateTokenCollision(t *testing.T) { - tokens := sync.Map{} user := userpb.User{ diff --git a/pkg/ocm/provider/authorizer/loader/loader.go b/pkg/ocm/provider/authorizer/loader/loader.go index c4663ec2343..6ae86f34716 100644 --- a/pkg/ocm/provider/authorizer/loader/loader.go +++ b/pkg/ocm/provider/authorizer/loader/loader.go @@ -23,5 +23,5 @@ import ( _ "github.com/cs3org/reva/pkg/ocm/provider/authorizer/json" _ "github.com/cs3org/reva/pkg/ocm/provider/authorizer/mentix" _ "github.com/cs3org/reva/pkg/ocm/provider/authorizer/open" - // Add your own here + // Add your own here. ) diff --git a/pkg/ocm/provider/authorizer/mentix/mentix.go b/pkg/ocm/provider/authorizer/mentix/mentix.go index 3ac345ee776..e5a9b900569 100644 --- a/pkg/ocm/provider/authorizer/mentix/mentix.go +++ b/pkg/ocm/provider/authorizer/mentix/mentix.go @@ -29,12 +29,11 @@ import ( "sync" "time" - "github.com/cs3org/reva/pkg/rhttp" - ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/ocm/provider" "github.com/cs3org/reva/pkg/ocm/provider/authorizer/registry" + "github.com/cs3org/reva/pkg/rhttp" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) @@ -43,7 +42,7 @@ func init() { registry.Register("mentix", New) } -// Client is a Mentix API client +// Client is a Mentix API client. type Client struct { BaseURL string HTTPClient *http.Client diff --git a/pkg/ocm/share/manager/json/json.go b/pkg/ocm/share/manager/json/json.go index 799b576804f..129b06ba98f 100644 --- a/pkg/ocm/share/manager/json/json.go +++ b/pkg/ocm/share/manager/json/json.go @@ -35,7 +35,6 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/ocm/share" - "github.com/cs3org/reva/pkg/ocm/share/manager/registry" "github.com/cs3org/reva/pkg/ocm/share/sender" "github.com/cs3org/reva/pkg/utils" @@ -180,7 +179,7 @@ func genID() string { // Called from both grpc CreateOCMShare for outgoing // and http /ocm/shares for incoming // pi is provider info -// pm is permissions +// pm is permissions. func (m *mgr) Share(ctx context.Context, md *provider.ResourceId, g *ocm.ShareGrant, name string, pi *ocmprovider.ProviderInfo, pm string, owner *userpb.UserId, token string, st ocm.Share_ShareType) (*ocm.Share, error) { id := genID() @@ -278,7 +277,6 @@ func (m *mgr) Share(ctx context.Context, md *provider.ResourceId, g *ocm.ShareGr err = errors.Wrap(err, "error sending OCM POST") return nil, err } - } m.Lock() diff --git a/pkg/ocm/share/manager/loader/loader.go b/pkg/ocm/share/manager/loader/loader.go index 6c327b184fb..667da5aac5f 100644 --- a/pkg/ocm/share/manager/loader/loader.go +++ b/pkg/ocm/share/manager/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load core share manager drivers. _ "github.com/cs3org/reva/pkg/ocm/share/manager/json" _ "github.com/cs3org/reva/pkg/ocm/share/manager/nextcloud" - // Add your own here + // Add your own here. ) diff --git a/pkg/ocm/share/manager/nextcloud/nextcloud.go b/pkg/ocm/share/manager/nextcloud/nextcloud.go index 57ce41d7be8..8bb9216e762 100644 --- a/pkg/ocm/share/manager/nextcloud/nextcloud.go +++ b/pkg/ocm/share/manager/nextcloud/nextcloud.go @@ -29,19 +29,17 @@ import ( "time" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/utils" - ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" "github.com/cs3org/reva/pkg/appctx" + ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/ocm/share" "github.com/cs3org/reva/pkg/ocm/share/manager/registry" "github.com/cs3org/reva/pkg/ocm/share/sender" + "github.com/cs3org/reva/pkg/utils" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "google.golang.org/genproto/protobuf/field_mask" @@ -70,14 +68,14 @@ type Manager struct { endPoint string } -// ShareManagerConfig contains config for a Nextcloud-based ShareManager +// ShareManagerConfig contains config for a Nextcloud-based ShareManager. type ShareManagerConfig struct { EndPoint string `mapstructure:"endpoint" docs:";The Nextcloud backend endpoint for user check"` SharedSecret string `mapstructure:"shared_secret"` MockHTTP bool `mapstructure:"mock_http"` } -// Action describes a REST request to forward to the Nextcloud backend +// Action describes a REST request to forward to the Nextcloud backend. type Action struct { verb string argS string @@ -90,7 +88,7 @@ type GranteeAltMap struct { ID *provider.Grantee_UserId `json:"id"` } -// ShareAltMap is an alternative map to JSON-unmarshal a Share +// ShareAltMap is an alternative map to JSON-unmarshal a Share. type ShareAltMap struct { ID *ocm.ShareId `json:"id"` ResourceID *provider.ResourceId `json:"resource_id"` @@ -102,7 +100,7 @@ type ShareAltMap struct { Mtime *typespb.Timestamp `json:"mtime"` } -// ReceivedShareAltMap is an alternative map to JSON-unmarshal a ReceivedShare +// ReceivedShareAltMap is an alternative map to JSON-unmarshal a ReceivedShare. type ReceivedShareAltMap struct { Share *ShareAltMap `json:"share"` State ocm.ShareState `json:"state"` @@ -140,7 +138,7 @@ func New(m map[string]interface{}) (share.Manager, error) { return NewShareManager(c) } -// NewShareManager returns a new Nextcloud-based ShareManager +// NewShareManager returns a new Nextcloud-based ShareManager. func NewShareManager(c *ShareManagerConfig) (*Manager, error) { var client *http.Client if c.MockHTTP { @@ -164,7 +162,7 @@ func NewShareManager(c *ShareManagerConfig) (*Manager, error) { }, nil } -// SetHTTPClient sets the HTTP client +// SetHTTPClient sets the HTTP client. func (sm *Manager) SetHTTPClient(c *http.Client) { sm.client = c } @@ -216,10 +214,9 @@ func (sm *Manager) do(ctx context.Context, a Action, username string) (int, []by // Share is called from both grpc CreateOCMShare for outgoing // and http /ocm/shares for incoming // pi is provider info -// pm is permissions +// pm is permissions. func (sm *Manager) Share(ctx context.Context, md *provider.ResourceId, g *ocm.ShareGrant, name string, pi *ocmprovider.ProviderInfo, pm string, owner *userpb.UserId, token string, st ocm.Share_ShareType) (*ocm.Share, error) { - // Since both OCMCore and OCMShareProvider use the same package, we distinguish // between calls received from them on the basis of whether they provide info // about the remote provider on which the share is to be created. @@ -528,7 +525,6 @@ func (sm *Manager) ListReceivedShares(ctx context.Context) ([]*ocm.ReceivedShare } } return pointers, err - } // GetReceivedShare as defined in the ocm.share.Manager interface diff --git a/pkg/ocm/share/manager/nextcloud/nextcloud_server_mock.go b/pkg/ocm/share/manager/nextcloud/nextcloud_server_mock.go index 0daef8b70b2..4df5a231f2d 100644 --- a/pkg/ocm/share/manager/nextcloud/nextcloud_server_mock.go +++ b/pkg/ocm/share/manager/nextcloud/nextcloud_server_mock.go @@ -29,7 +29,7 @@ import ( ) // Response contains data for the Nextcloud mock server to respond -// and to switch to a new server state +// and to switch to a new server state. type Response struct { code int body string @@ -63,7 +63,7 @@ var responses = map[string]Response{ `POST /index.php/apps/sciencemesh/~marie/api/ocm/UpdateReceivedShare {"received_share":{"share":{"id":{},"resource_id":{},"permissions":{"permissions":{"add_grant":true,"create_container":true,"delete":true,"get_path":true,"get_quota":true,"initiate_file_download":true,"initiate_file_upload":true,"list_grants":true,"list_container":true,"list_file_versions":true,"list_recycle":true,"move":true,"remove_grant":true,"purge_recycle":true,"restore_file_version":true,"restore_recycle_item":true,"stat":true,"update_grant":true,"deny_grant":true}},"grantee":{"Id":{"UserId":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1}}},"owner":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1},"creator":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1},"ctime":{"seconds":1234567890},"mtime":{"seconds":1234567890}},"state":2},"field_mask":{"paths":["state"]}}`: {200, `{"share":{"id":{},"resource_id":{},"permissions":{"permissions":{"add_grant":true,"create_container":true,"delete":true,"get_path":true,"get_quota":true,"initiate_file_download":true,"initiate_file_upload":true,"list_grants":true,"list_container":true,"list_file_versions":true,"list_recycle":true,"move":true,"remove_grant":true,"purge_recycle":true,"restore_file_version":true,"restore_recycle_item":true,"stat":true,"update_grant":true,"deny_grant":true}},"grantee":{"Id":{"UserId":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1}}},"owner":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1},"creator":{"idp":"0.0.0.0:19000","opaque_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c","type":1},"ctime":{"seconds":1234567890},"mtime":{"seconds":1234567890}},"state":2}`, serverStateHome}, } -// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server +// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server. func GetNextcloudServerMock(called *[]string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf := new(strings.Builder) diff --git a/pkg/ocm/share/manager/nextcloud/nextcloud_test.go b/pkg/ocm/share/manager/nextcloud/nextcloud_test.go index 2f01928ec2b..f440982d89f 100644 --- a/pkg/ocm/share/manager/nextcloud/nextcloud_test.go +++ b/pkg/ocm/share/manager/nextcloud/nextcloud_test.go @@ -22,22 +22,18 @@ import ( "context" "os" - "google.golang.org/genproto/protobuf/field_mask" - "google.golang.org/grpc/metadata" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ocm "github.com/cs3org/go-cs3apis/cs3/sharing/ocm/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/cs3org/reva/pkg/auth/scope" ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/ocm/share/manager/nextcloud" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/genproto/protobuf/field_mask" + "google.golang.org/grpc/metadata" ) func setUpNextcloudServer() (*nextcloud.Manager, *[]string, func()) { diff --git a/pkg/ocm/share/sender/sender.go b/pkg/ocm/share/sender/sender.go index 8f53f241a47..d6ffa5711d4 100644 --- a/pkg/ocm/share/sender/sender.go +++ b/pkg/ocm/share/sender/sender.go @@ -30,7 +30,6 @@ import ( ocmprovider "github.com/cs3org/go-cs3apis/cs3/ocm/provider/v1beta1" "github.com/cs3org/reva/pkg/rhttp" - "github.com/pkg/errors" ) diff --git a/pkg/permission/manager/demo/demo.go b/pkg/permission/manager/demo/demo.go index 7bb6c107798..89e99e4b415 100644 --- a/pkg/permission/manager/demo/demo.go +++ b/pkg/permission/manager/demo/demo.go @@ -28,7 +28,7 @@ func init() { registry.Register("demo", New) } -// New returns a new demo permission manager +// New returns a new demo permission manager. func New(c map[string]interface{}) (permission.Manager, error) { return manager{}, nil } diff --git a/pkg/permission/manager/loader/loader.go b/pkg/permission/manager/loader/loader.go index 5f0bbc5774b..6b4cb6784d5 100644 --- a/pkg/permission/manager/loader/loader.go +++ b/pkg/permission/manager/loader/loader.go @@ -19,7 +19,7 @@ package loader import ( - // Load permission manager drivers + // Load permission manager drivers. _ "github.com/cs3org/reva/pkg/permission/manager/demo" - // Add your own here + // Add your own here. ) diff --git a/pkg/permission/permission.go b/pkg/permission/permission.go index e5e5c76a528..65fead417f4 100644 --- a/pkg/permission/permission.go +++ b/pkg/permission/permission.go @@ -22,7 +22,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" ) -// Manager defines the interface for the permission service driver +// Manager defines the interface for the permission service driver. type Manager interface { CheckPermission(permission string, subject string, ref *provider.Reference) bool } diff --git a/pkg/plugin/loader.go b/pkg/plugin/loader.go index 335af6275f9..657ebf22719 100644 --- a/pkg/plugin/loader.go +++ b/pkg/plugin/loader.go @@ -31,7 +31,7 @@ import ( "github.com/hashicorp/go-plugin" ) -// RevaPlugin represents the runtime plugin +// RevaPlugin represents the runtime plugin. type RevaPlugin struct { Plugin interface{} Client *plugin.Client @@ -41,7 +41,7 @@ const dirname = "/var/tmp/reva" var isAlphaNum = regexp.MustCompile(`^[A-Za-z0-9]+$`).MatchString -// Kill kills the plugin process +// Kill kills the plugin process. func (plug *RevaPlugin) Kill() { plug.Client.Kill() } @@ -82,7 +82,7 @@ func checkDirAndCompile(pluginType, driver string) (string, error) { return bin, nil } -// Load loads the plugin using the hashicorp go-plugin system +// Load loads the plugin using the hashicorp go-plugin system. func Load(pluginType, driver string) (*RevaPlugin, error) { if isAlphaNum(driver) { return nil, errtypes.NotFound(driver) diff --git a/pkg/plugin/plugin.go b/pkg/plugin/plugin.go index 47fc5b50ce8..a065681bcde 100644 --- a/pkg/plugin/plugin.go +++ b/pkg/plugin/plugin.go @@ -18,7 +18,7 @@ package plugin -// Plugin is the interface used to configure plugins +// Plugin is the interface used to configure plugins. type Plugin interface { Configure(m map[string]interface{}) error } diff --git a/pkg/plugin/registry.go b/pkg/plugin/registry.go index 43894f19210..2b90341dea9 100644 --- a/pkg/plugin/registry.go +++ b/pkg/plugin/registry.go @@ -20,10 +20,10 @@ package plugin import "github.com/hashicorp/go-plugin" -// PluginMap is a map containing all the plugins +// PluginMap is a map containing all the plugins. var PluginMap = map[string]plugin.Plugin{} -// Register registers the plugin +// Register registers the plugin. func Register(name string, plugin plugin.Plugin) { PluginMap[name] = plugin } diff --git a/pkg/preferences/loader/loader.go b/pkg/preferences/loader/loader.go index a7b4d2c46c2..ac91aae5d07 100644 --- a/pkg/preferences/loader/loader.go +++ b/pkg/preferences/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load preferences drivers. _ "github.com/cs3org/reva/pkg/preferences/memory" - // Add your own here + // Add your own here. ) diff --git a/pkg/publicshare/manager/json/json.go b/pkg/publicshare/manager/json/json.go index f0fbfb0db0d..f539886450c 100644 --- a/pkg/publicshare/manager/json/json.go +++ b/pkg/publicshare/manager/json/json.go @@ -29,9 +29,6 @@ import ( "syscall" "time" - "github.com/rs/zerolog/log" - "golang.org/x/crypto/bcrypt" - user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -43,6 +40,8 @@ import ( "github.com/cs3org/reva/pkg/utils" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" + "github.com/rs/zerolog/log" + "golang.org/x/crypto/bcrypt" ) func init() { @@ -138,7 +137,7 @@ func (m *manager) startJanitorRun() { } } -// CreatePublicShare adds a new entry to manager.shares +// CreatePublicShare adds a new entry to manager.shares. func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *provider.ResourceInfo, g *link.Grant, description string, internal bool) (*link.PublicShare, error) { id := &link.PublicShareId{ OpaqueId: utils.RandString(15), @@ -196,7 +195,7 @@ func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *pr return nil, err } - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, err } @@ -210,7 +209,7 @@ func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *pr return nil, errors.New("key already exists") } - err = m.writeDb(db) + err = m.writeDB(db) if err != nil { return nil, err } @@ -218,7 +217,7 @@ func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *pr return &s, nil } -// UpdatePublicShare updates the public share +// UpdatePublicShare updates the public share. func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link.UpdatePublicShareRequest, g *link.Grant) (*link.PublicShare, error) { log := appctx.GetLogger(ctx) share, err := m.GetPublicShare(ctx, u, req.Ref, false) @@ -269,7 +268,7 @@ func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link m.mutex.Lock() defer m.mutex.Unlock() - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, err } @@ -291,7 +290,7 @@ func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link db[share.Id.OpaqueId] = data - err = m.writeDb(db) + err = m.writeDB(db) if err != nil { return nil, err } @@ -318,7 +317,7 @@ func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.Pu m.mutex.Lock() defer m.mutex.Unlock() - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, err } @@ -347,7 +346,6 @@ func (m *manager) GetPublicShare(ctx context.Context, u *user.User, ref *link.Pu } return &ps, nil } - } return nil, errors.New("no shares found by id:" + ref.GetId().String()) } @@ -359,7 +357,7 @@ func (m *manager) ListPublicShares(ctx context.Context, u *user.User, filters [] m.mutex.Lock() defer m.mutex.Unlock() - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, err } @@ -402,7 +400,7 @@ func (m *manager) cleanupExpiredShares() { m.mutex.Lock() defer m.mutex.Unlock() - db, _ := m.readDb() + db, _ := m.readDB() for _, v := range db { d := v.(map[string]interface{})["share"] @@ -442,7 +440,7 @@ func (m *manager) revokeExpiredPublicShare(ctx context.Context, s *link.PublicSh // RevokePublicShare undocumented. func (m *manager) RevokePublicShare(ctx context.Context, u *user.User, ref *link.PublicShareReference) error { m.mutex.Lock() - db, err := m.readDb() + db, err := m.readDB() if err != nil { return err } @@ -467,11 +465,11 @@ func (m *manager) RevokePublicShare(ctx context.Context, u *user.User, ref *link m.mutex.Lock() defer m.mutex.Unlock() - return m.writeDb(db) + return m.writeDB(db) } func (m *manager) getByToken(ctx context.Context, token string) (*link.PublicShare, string, error) { - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, "", err } @@ -496,7 +494,7 @@ func (m *manager) getByToken(ctx context.Context, token string) (*link.PublicSha // GetPublicShareByToken gets a public share by its opaque token. func (m *manager) GetPublicShareByToken(ctx context.Context, token string, auth *link.PublicShareAuthentication, sign bool) (*link.PublicShare, error) { - db, err := m.readDb() + db, err := m.readDB() if err != nil { return nil, err } @@ -540,7 +538,7 @@ func (m *manager) GetPublicShareByToken(ctx context.Context, token string, auth return nil, errtypes.NotFound(fmt.Sprintf("share with token: `%v` not found", token)) } -func (m *manager) readDb() (map[string]interface{}, error) { +func (m *manager) readDB() (map[string]interface{}, error) { db := map[string]interface{}{} readBytes, err := os.ReadFile(m.file) if err != nil { @@ -552,7 +550,7 @@ func (m *manager) readDb() (map[string]interface{}, error) { return db, nil } -func (m *manager) writeDb(db map[string]interface{}) error { +func (m *manager) writeDB(db map[string]interface{}) error { dbAsJSON, err := json.Marshal(db) if err != nil { return err diff --git a/pkg/publicshare/manager/loader/loader.go b/pkg/publicshare/manager/loader/loader.go index 5101d1e109f..4b229296bbe 100644 --- a/pkg/publicshare/manager/loader/loader.go +++ b/pkg/publicshare/manager/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load core share manager drivers. _ "github.com/cs3org/reva/pkg/publicshare/manager/json" _ "github.com/cs3org/reva/pkg/publicshare/manager/memory" - // Add your own here + // Add your own here. ) diff --git a/pkg/publicshare/manager/memory/memory.go b/pkg/publicshare/manager/memory/memory.go index d298fa8efaa..6016e8cefa2 100644 --- a/pkg/publicshare/manager/memory/memory.go +++ b/pkg/publicshare/manager/memory/memory.go @@ -57,7 +57,7 @@ var ( passwordProtected bool ) -// CreatePublicShare adds a new entry to manager.shares +// CreatePublicShare adds a new entry to manager.shares. func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *provider.ResourceInfo, g *link.Grant, description string, internal bool) (*link.PublicShare, error) { id := &link.PublicShareId{ OpaqueId: randString(15), @@ -104,7 +104,7 @@ func (m *manager) CreatePublicShare(ctx context.Context, u *user.User, rInfo *pr return &s, nil } -// UpdatePublicShare updates the expiration date, permissions and Mtime +// UpdatePublicShare updates the expiration date, permissions and Mtime. func (m *manager) UpdatePublicShare(ctx context.Context, u *user.User, req *link.UpdatePublicShareRequest, g *link.Grant) (*link.PublicShare, error) { log := appctx.GetLogger(ctx) share, err := m.GetPublicShare(ctx, u, req.Ref, false) diff --git a/pkg/publicshare/publicshare.go b/pkg/publicshare/publicshare.go index a5fb0847e2a..959baa19e9c 100644 --- a/pkg/publicshare/publicshare.go +++ b/pkg/publicshare/publicshare.go @@ -118,7 +118,7 @@ func MatchesAnyFilter(share *link.PublicShare, filters []*link.ListPublicSharesR // MatchesFilters checks if the share passes the given filters. // Filters of the same type form a disjuntion, a logical OR. Filters of separate type form a conjunction, a logical AND. // Here is an example: -// (resource_id=1 OR resource_id=2) AND (grantee_type=USER OR grantee_type=GROUP) +// (resource_id=1 OR resource_id=2) AND (grantee_type=USER OR grantee_type=GROUP). func MatchesFilters(share *link.PublicShare, filters []*link.ListPublicSharesRequest_Filter) bool { grouped := GroupFiltersByType(filters) for _, f := range grouped { @@ -138,7 +138,7 @@ func GroupFiltersByType(filters []*link.ListPublicSharesRequest_Filter) map[link return grouped } -// IsExpired tests whether a public share is expired +// IsExpired tests whether a public share is expired. func IsExpired(s *link.PublicShare) bool { expiration := time.Unix(int64(s.Expiration.GetSeconds()), int64(s.Expiration.GetNanos())) return s.Expiration != nil && expiration.Before(time.Now()) diff --git a/pkg/registry/config.go b/pkg/registry/config.go index f798b65b9c9..1e7cd40564f 100644 --- a/pkg/registry/config.go +++ b/pkg/registry/config.go @@ -22,7 +22,7 @@ import ( "github.com/mitchellh/mapstructure" ) -// Config configures a registry +// Config configures a registry. type Config struct { Services map[string]map[string]*service `mapstructure:"services"` } diff --git a/pkg/registry/memory/service.go b/pkg/registry/memory/service.go index 0213b2761d1..21b29166235 100644 --- a/pkg/registry/memory/service.go +++ b/pkg/registry/memory/service.go @@ -38,7 +38,7 @@ func NewService(name string, nodes []interface{}) registry.Service { } } -// service implements the Service interface +// service implements the Service interface. type service struct { name string nodes []node diff --git a/pkg/rgrpc/rgrpc.go b/pkg/rgrpc/rgrpc.go index 05fa9521538..cba07faf83b 100644 --- a/pkg/rgrpc/rgrpc.go +++ b/pkg/rgrpc/rgrpc.go @@ -44,7 +44,7 @@ import ( // UnaryInterceptors is a map of registered unary grpc interceptors. var UnaryInterceptors = map[string]NewUnaryInterceptor{} -// StreamInterceptors is a map of registered streaming grpc interceptor +// StreamInterceptors is a map of registered streaming grpc interceptor. var StreamInterceptors = map[string]NewStreamInterceptor{} // NewUnaryInterceptor is the type that unary interceptors need to register. diff --git a/pkg/rgrpc/status/status.go b/pkg/rgrpc/status/status.go index 47da94647f3..92cb4e3258f 100644 --- a/pkg/rgrpc/status/status.go +++ b/pkg/rgrpc/status/status.go @@ -154,7 +154,7 @@ func NewConflict(ctx context.Context, err error, msg string) *rpc.Status { } } -// NewFailedPrecondition TODO +// NewFailedPrecondition TODO. func NewFailedPrecondition(ctx context.Context, err error, msg string) *rpc.Status { log := appctx.GetLogger(ctx).With().CallerWithSkipFrameCount(3).Logger() log.Error().Err(err).Msg(msg) @@ -165,7 +165,7 @@ func NewFailedPrecondition(ctx context.Context, err error, msg string) *rpc.Stat } } -// NewStatusFromErrType returns a status that corresponds to the given errtype +// NewStatusFromErrType returns a status that corresponds to the given errtype. func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Status { switch e := err.(type) { case nil: @@ -212,7 +212,7 @@ func NewErrorFromCode(code rpc.Code, pkgname string) error { return errors.New(pkgname + ": grpc failed with code " + code.String()) } -// internal function to attach the trace to a context +// internal function to attach the trace to a context. func getTrace(ctx context.Context) string { span := trace.SpanFromContext(ctx) return span.SpanContext().TraceID().String() diff --git a/pkg/rgrpc/todo/pool/pool.go b/pkg/rgrpc/todo/pool/pool.go index 3f062e5130c..9ef9cdb7ff3 100644 --- a/pkg/rgrpc/todo/pool/pool.go +++ b/pkg/rgrpc/todo/pool/pool.go @@ -59,7 +59,7 @@ func newProvider() provider { } // TODO(labkode): is concurrent access to the maps safe? -// var storageProviders = map[string]storageprovider.ProviderAPIClient{} +// var storageProviders = map[string]storageprovider.ProviderAPIClient{}. var ( storageProviders = newProvider() authProviders = newProvider() diff --git a/pkg/rhttp/client.go b/pkg/rhttp/client.go index c74c00cb790..32ae9b1a8eb 100644 --- a/pkg/rhttp/client.go +++ b/pkg/rhttp/client.go @@ -24,10 +24,9 @@ import ( "io" "net/http" - "go.opencensus.io/plugin/ochttp" - ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/pkg/errors" + "go.opencensus.io/plugin/ochttp" ) // GetHTTPClient returns an http client with open census tracing support. diff --git a/pkg/rhttp/datatx/manager/loader/loader.go b/pkg/rhttp/datatx/manager/loader/loader.go index 15a11bb5f41..60b0c935740 100644 --- a/pkg/rhttp/datatx/manager/loader/loader.go +++ b/pkg/rhttp/datatx/manager/loader/loader.go @@ -19,9 +19,9 @@ package loader import ( - // Load core data transfer protocols + // Load core data transfer protocols. _ "github.com/cs3org/reva/pkg/rhttp/datatx/manager/simple" _ "github.com/cs3org/reva/pkg/rhttp/datatx/manager/spaces" _ "github.com/cs3org/reva/pkg/rhttp/datatx/manager/tus" - // Add your own here + // Add your own here. ) diff --git a/pkg/rhttp/datatx/manager/tus/tus.go b/pkg/rhttp/datatx/manager/tus/tus.go index 3e442417abd..26dc03be8ab 100644 --- a/pkg/rhttp/datatx/manager/tus/tus.go +++ b/pkg/rhttp/datatx/manager/tus/tus.go @@ -21,14 +21,13 @@ package tus import ( "net/http" - "github.com/pkg/errors" - "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/rhttp/datatx" "github.com/cs3org/reva/pkg/rhttp/datatx/manager/registry" "github.com/cs3org/reva/pkg/rhttp/datatx/utils/download" "github.com/cs3org/reva/pkg/storage" "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" tusd "github.com/tus/tusd/pkg/handler" ) @@ -86,7 +85,6 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { } h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - method := r.Method // https://github.com/tus/tus-resumable-upload-protocol/blob/master/protocol.md#x-http-method-override if r.Header.Get("X-HTTP-Method-Override") != "" { @@ -113,7 +111,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) { } // Composable is the interface that a struct needs to implement -// to be composable, so that it can support the TUS methods +// to be composable, so that it can support the TUS methods. type composable interface { UseIn(composer *tusd.StoreComposer) } diff --git a/pkg/rhttp/datatx/utils/download/download.go b/pkg/rhttp/datatx/utils/download/download.go index 9d62531ca7b..526b4d6c6a9 100644 --- a/pkg/rhttp/datatx/utils/download/download.go +++ b/pkg/rhttp/datatx/utils/download/download.go @@ -35,7 +35,7 @@ import ( "github.com/rs/zerolog" ) -// GetOrHeadFile returns the requested file content +// GetOrHeadFile returns the requested file content. func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceID string) { ctx := r.Context() sublog := appctx.GetLogger(ctx).With().Str("svc", "datatx").Str("handler", "download").Logger() @@ -195,7 +195,6 @@ func GetOrHeadFile(w http.ResponseWriter, r *http.Request, fs storage.FS, spaceI sublog.Error().Int64("copied", c).Int64("size", sendSize).Msg("copied vs size mismatch") } } - } func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action string) { diff --git a/pkg/rhttp/datatx/utils/download/range.go b/pkg/rhttp/datatx/utils/download/range.go index 063a67981d0..7d5097f83b2 100644 --- a/pkg/rhttp/datatx/utils/download/range.go +++ b/pkg/rhttp/datatx/utils/download/range.go @@ -49,7 +49,7 @@ func (r HTTPRange) ContentRange(size int64) string { return fmt.Sprintf("bytes %d-%d/%d", r.Start, r.Start+r.Length-1, size) } -// MimeHeader creates range relevant MimeHeaders +// MimeHeader creates range relevant MimeHeaders. func (r HTTPRange) MimeHeader(contentType string, size int64) textproto.MIMEHeader { return textproto.MIMEHeader{ "Content-Range": {r.ContentRange(size)}, @@ -151,7 +151,7 @@ func RangesMIMESize(ranges []HTTPRange, contentType string, contentSize int64) ( return } -// SumRangesSize adds up the length of all ranges +// SumRangesSize adds up the length of all ranges. func SumRangesSize(ranges []HTTPRange) (size int64) { for _, ra := range ranges { size += ra.Length diff --git a/pkg/rhttp/rhttp.go b/pkg/rhttp/rhttp.go index ba852572f17..43a55f7493a 100644 --- a/pkg/rhttp/rhttp.go +++ b/pkg/rhttp/rhttp.go @@ -40,7 +40,7 @@ import ( "go.opentelemetry.io/otel/propagation" ) -// New returns a new server +// New returns a new server. func New(m interface{}, l zerolog.Logger) (*Server, error) { conf := &config{} if err := mapstructure.Decode(m, conf); err != nil { @@ -93,7 +93,7 @@ func (c *config) init() { } } -// Start starts the server +// Start starts the server. func (s *Server) Start(ln net.Listener) error { if err := s.registerServices(); err != nil { return err @@ -236,7 +236,7 @@ func getUnprotected(prefix string, unprotected []string) []string { // clean the url putting a slash (/) at the beginning if it does not have it // and removing the slashes at the end -// if the url is "/", the output is "" +// if the url is "/", the output is "". func cleanURL(url string) string { if len(url) > 0 { if url[0] != '/' { diff --git a/pkg/rhttp/router/router.go b/pkg/rhttp/router/router.go index e4bab684988..d613b8ebb80 100644 --- a/pkg/rhttp/router/router.go +++ b/pkg/rhttp/router/router.go @@ -27,7 +27,7 @@ import ( // relative components before processing. head will never contain a slash and // tail will always be a rooted path without trailing slash. // see https://blog.merovius.de/2017/06/18/how-not-to-use-an-http-router.html -// and https://gist.github.com/weatherglass/62bd8a704d4dfdc608fe5c5cb5a6980c#gistcomment-2161690 for the zero alloc code below +// and https://gist.github.com/weatherglass/62bd8a704d4dfdc608fe5c5cb5a6980c#gistcomment-2161690 for the zero alloc code below. func ShiftPath(p string) (head, tail string) { if p == "" { return "", "/" diff --git a/pkg/sdk/action/download.go b/pkg/sdk/action/download.go index 4cabeb5158d..48a616164a6 100644 --- a/pkg/sdk/action/download.go +++ b/pkg/sdk/action/download.go @@ -24,7 +24,6 @@ import ( gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - storage "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/sdk" "github.com/cs3org/reva/pkg/sdk/common/net" @@ -50,8 +49,8 @@ func (action *DownloadAction) DownloadFile(path string) ([]byte, error) { } // Download retrieves the data of the provided resource. -func (action *DownloadAction) Download(fileInfo *storage.ResourceInfo) ([]byte, error) { - if fileInfo.Type != storage.ResourceType_RESOURCE_TYPE_FILE { +func (action *DownloadAction) Download(fileInfo *provider.ResourceInfo) ([]byte, error) { + if fileInfo.Type != provider.ResourceType_RESOURCE_TYPE_FILE { return nil, fmt.Errorf("resource is not a file") } @@ -88,7 +87,7 @@ func (action *DownloadAction) Download(fileInfo *storage.ResourceInfo) ([]byte, return data, nil } -func (action *DownloadAction) initiateDownload(fileInfo *storage.ResourceInfo) (*gateway.InitiateFileDownloadResponse, error) { +func (action *DownloadAction) initiateDownload(fileInfo *provider.ResourceInfo) (*gateway.InitiateFileDownloadResponse, error) { // Initiating a download request gets us the download endpoint for the specified resource req := &provider.InitiateFileDownloadRequest{Ref: &provider.Reference{Path: fileInfo.Path}} res, err := action.session.Client().InitiateFileDownload(action.session.Context(), req) diff --git a/pkg/sdk/action/enumfiles.go b/pkg/sdk/action/enumfiles.go index 1cf55a96c9c..132d402404f 100644 --- a/pkg/sdk/action/enumfiles.go +++ b/pkg/sdk/action/enumfiles.go @@ -22,7 +22,6 @@ import ( "fmt" storage "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/cs3org/reva/pkg/sdk" "github.com/cs3org/reva/pkg/sdk/common/net" ) diff --git a/pkg/sdk/action/fileops.go b/pkg/sdk/action/fileops.go index 1e85171ccba..38ba9e9def3 100644 --- a/pkg/sdk/action/fileops.go +++ b/pkg/sdk/action/fileops.go @@ -24,8 +24,6 @@ import ( "strings" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - storage "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/cs3org/reva/pkg/sdk" "github.com/cs3org/reva/pkg/sdk/common/net" ) @@ -46,7 +44,7 @@ func (action *FileOperationsAction) GetHome() (string, error) { } // Stat queries the file information of the specified remote resource. -func (action *FileOperationsAction) Stat(path string) (*storage.ResourceInfo, error) { +func (action *FileOperationsAction) Stat(path string) (*provider.ResourceInfo, error) { ref := &provider.Reference{Path: path} req := &provider.StatRequest{Ref: ref} res, err := action.session.Client().Stat(action.session.Context(), req) diff --git a/pkg/sdk/action/upload.go b/pkg/sdk/action/upload.go index 97c3363305d..52ad4dfba6e 100644 --- a/pkg/sdk/action/upload.go +++ b/pkg/sdk/action/upload.go @@ -30,9 +30,7 @@ import ( gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - storage "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/sdk" "github.com/cs3org/reva/pkg/sdk/common" @@ -49,7 +47,7 @@ type UploadAction struct { } // UploadFile uploads the provided file to the target. -func (action *UploadAction) UploadFile(file *os.File, target string) (*storage.ResourceInfo, error) { +func (action *UploadAction) UploadFile(file *os.File, target string) (*provider.ResourceInfo, error) { fileInfo, err := file.Stat() if err != nil { return nil, fmt.Errorf("unable to stat the specified file: %v", err) @@ -59,22 +57,22 @@ func (action *UploadAction) UploadFile(file *os.File, target string) (*storage.R } // UploadFileTo uploads the provided file to the target directory, keeping the original file name. -func (action *UploadAction) UploadFileTo(file *os.File, path string) (*storage.ResourceInfo, error) { +func (action *UploadAction) UploadFileTo(file *os.File, path string) (*provider.ResourceInfo, error) { return action.UploadFile(file, p.Join(path, p.Base(file.Name()))) } // UploadBytes uploads the provided byte data to the target. -func (action *UploadAction) UploadBytes(data []byte, target string) (*storage.ResourceInfo, error) { +func (action *UploadAction) UploadBytes(data []byte, target string) (*provider.ResourceInfo, error) { return action.Upload(bytes.NewReader(data), int64(len(data)), target) } // Upload uploads data from the provided reader to the target. -func (action *UploadAction) Upload(data io.Reader, size int64, target string) (*storage.ResourceInfo, error) { +func (action *UploadAction) Upload(data io.Reader, size int64, target string) (*provider.ResourceInfo, error) { dataDesc := common.CreateDataDescriptor(p.Base(target), size) return action.upload(data, &dataDesc, target) } -func (action *UploadAction) upload(data io.Reader, dataInfo os.FileInfo, target string) (*storage.ResourceInfo, error) { +func (action *UploadAction) upload(data io.Reader, dataInfo os.FileInfo, target string) (*provider.ResourceInfo, error) { fileOpsAct := MustNewFileOperationsAction(action.session) dir := p.Dir(target) diff --git a/pkg/sdk/common/crypto/crypto.go b/pkg/sdk/common/crypto/crypto.go index 84ba0fdba4a..f28f5f7c23a 100644 --- a/pkg/sdk/common/crypto/crypto.go +++ b/pkg/sdk/common/crypto/crypto.go @@ -23,7 +23,6 @@ import ( "io" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - "github.com/cs3org/reva/internal/grpc/services/storageprovider" "github.com/cs3org/reva/pkg/crypto" ) diff --git a/pkg/sdk/common/net/tus.go b/pkg/sdk/common/net/tus.go index 0f9db857d4b..a642dccf51c 100644 --- a/pkg/sdk/common/net/tus.go +++ b/pkg/sdk/common/net/tus.go @@ -27,10 +27,9 @@ import ( "strings" "time" + "github.com/cs3org/reva/pkg/sdk/common" "github.com/eventials/go-tus" "github.com/eventials/go-tus/memorystore" - - "github.com/cs3org/reva/pkg/sdk/common" ) // TUSClient is a simple client wrapper for uploading files via TUS. diff --git a/pkg/sdk/common/net/webdav.go b/pkg/sdk/common/net/webdav.go index 2bf9e5e829f..aaf778b0610 100644 --- a/pkg/sdk/common/net/webdav.go +++ b/pkg/sdk/common/net/webdav.go @@ -24,9 +24,8 @@ import ( "strconv" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" - "github.com/studio-b12/gowebdav" - "github.com/cs3org/reva/pkg/sdk/common" + "github.com/studio-b12/gowebdav" ) const ( diff --git a/pkg/sdk/session.go b/pkg/sdk/session.go index c940114e47b..b403ace2c14 100644 --- a/pkg/sdk/session.go +++ b/pkg/sdk/session.go @@ -26,13 +26,12 @@ import ( registry "github.com/cs3org/go-cs3apis/cs3/auth/registry/v1beta1" gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + "github.com/cs3org/reva/pkg/sdk/common" + "github.com/cs3org/reva/pkg/sdk/common/net" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" - - "github.com/cs3org/reva/pkg/sdk/common" - "github.com/cs3org/reva/pkg/sdk/common/net" ) // Session stores information about a Reva session. diff --git a/pkg/share/cache/cache.go b/pkg/share/cache/cache.go index a17791630c7..2c9c3b7cc20 100644 --- a/pkg/share/cache/cache.go +++ b/pkg/share/cache/cache.go @@ -29,7 +29,7 @@ type Warmup interface { GetResourceInfos() ([]*provider.ResourceInfo, error) } -// ResourceInfoCache is the interface to implement caches for resource infos +// ResourceInfoCache is the interface to implement caches for resource infos. type ResourceInfoCache interface { Get(key string) (*provider.ResourceInfo, error) GetKeys(keys []string) ([]*provider.ResourceInfo, error) diff --git a/pkg/share/cache/loader/loader.go b/pkg/share/cache/loader/loader.go index 32a6bf133e7..50d1fcaf2be 100644 --- a/pkg/share/cache/loader/loader.go +++ b/pkg/share/cache/loader/loader.go @@ -22,5 +22,5 @@ import ( // Load share cache drivers. _ "github.com/cs3org/reva/pkg/share/cache/memory" _ "github.com/cs3org/reva/pkg/share/cache/redis" - // Add your own here + // Add your own here. ) diff --git a/pkg/share/cache/memory/memory.go b/pkg/share/cache/memory/memory.go index b0faa70b1ab..f4b1c76a060 100644 --- a/pkg/share/cache/memory/memory.go +++ b/pkg/share/cache/memory/memory.go @@ -41,7 +41,7 @@ type manager struct { cache gcache.Cache } -// New returns an implementation of a resource info cache that stores the objects in memory +// New returns an implementation of a resource info cache that stores the objects in memory. func New(m map[string]interface{}) (cache.ResourceInfoCache, error) { c := &config{} if err := mapstructure.Decode(m, c); err != nil { diff --git a/pkg/share/cache/redis/redis.go b/pkg/share/cache/redis/redis.go index e71a457f019..dfb85d3f5dd 100644 --- a/pkg/share/cache/redis/redis.go +++ b/pkg/share/cache/redis/redis.go @@ -44,7 +44,7 @@ type manager struct { redisPool *redis.Pool } -// New returns an implementation of a resource info cache that stores the objects in a redis cluster +// New returns an implementation of a resource info cache that stores the objects in a redis cluster. func New(m map[string]interface{}) (cache.ResourceInfoCache, error) { c := &config{} if err := mapstructure.Decode(m, c); err != nil { diff --git a/pkg/share/cache/warmup/cbox/cbox.go b/pkg/share/cache/warmup/cbox/cbox.go index 4a46f83574c..88e60ea1753 100644 --- a/pkg/share/cache/warmup/cbox/cbox.go +++ b/pkg/share/cache/warmup/cbox/cbox.go @@ -32,12 +32,12 @@ import ( "github.com/cs3org/reva/pkg/share/cache" "github.com/cs3org/reva/pkg/share/cache/warmup/registry" "github.com/cs3org/reva/pkg/token/manager/jwt" + + // Provides mysql drivers. + _ "github.com/go-sql-driver/mysql" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "google.golang.org/grpc/metadata" - - // Provides mysql drivers - _ "github.com/go-sql-driver/mysql" ) func init() { @@ -45,11 +45,11 @@ func init() { } type config struct { - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` EOSNamespace string `mapstructure:"namespace"` GatewaySvc string `mapstructure:"gatewaysvc"` JWTSecret string `mapstructure:"jwt_secret"` @@ -69,13 +69,13 @@ func parseConfig(m map[string]interface{}) (*config, error) { return c, nil } -// New returns an implementation of cache warmup that connects to the cbox share db and stats resources on EOS +// New returns an implementation of cache warmup that connects to the cbox share db and stats resources on EOS. func New(m map[string]interface{}) (cache.Warmup, error) { c, err := parseConfig(m) if err != nil { return nil, err } - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } @@ -151,5 +151,4 @@ func (m *manager) GetResourceInfos() ([]*provider.ResourceInfo, error) { } return infos, nil - } diff --git a/pkg/share/cache/warmup/loader/loader.go b/pkg/share/cache/warmup/loader/loader.go index e21d31aad4e..e997fb0132f 100644 --- a/pkg/share/cache/warmup/loader/loader.go +++ b/pkg/share/cache/warmup/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load share cache drivers. _ "github.com/cs3org/reva/pkg/share/cache/warmup/cbox" - // Add your own here + // Add your own here. ) diff --git a/pkg/share/manager/json/json.go b/pkg/share/manager/json/json.go index 18b88939846..0fc687c916b 100644 --- a/pkg/share/manager/json/json.go +++ b/pkg/share/manager/json/json.go @@ -32,13 +32,12 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/share" + "github.com/cs3org/reva/pkg/share/manager/registry" + "github.com/cs3org/reva/pkg/utils" "github.com/google/uuid" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "google.golang.org/genproto/protobuf/field_mask" - - "github.com/cs3org/reva/pkg/share/manager/registry" - "github.com/cs3org/reva/pkg/utils" ) func init() { diff --git a/pkg/share/manager/loader/loader.go b/pkg/share/manager/loader/loader.go index b3ebbcae29c..b53103e8435 100644 --- a/pkg/share/manager/loader/loader.go +++ b/pkg/share/manager/loader/loader.go @@ -23,5 +23,5 @@ import ( _ "github.com/cs3org/reva/pkg/share/manager/json" _ "github.com/cs3org/reva/pkg/share/manager/memory" _ "github.com/cs3org/reva/pkg/share/manager/sql" - // Add your own here + // Add your own here. ) diff --git a/pkg/share/manager/memory/memory.go b/pkg/share/manager/memory/memory.go index e292b73d722..dffcc8ec545 100644 --- a/pkg/share/manager/memory/memory.go +++ b/pkg/share/manager/memory/memory.go @@ -26,16 +26,15 @@ import ( "sync/atomic" "time" - ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/share" - "google.golang.org/genproto/protobuf/field_mask" - collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" + ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/errtypes" + "github.com/cs3org/reva/pkg/share" "github.com/cs3org/reva/pkg/share/manager/registry" "github.com/cs3org/reva/pkg/utils" + "google.golang.org/genproto/protobuf/field_mask" ) var counter uint64 diff --git a/pkg/share/manager/sql/conversions.go b/pkg/share/manager/sql/conversions.go index 3745b93fd43..04ca4097cc0 100644 --- a/pkg/share/manager/sql/conversions.go +++ b/pkg/share/manager/sql/conversions.go @@ -23,7 +23,6 @@ import ( grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - userprovider "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -54,31 +53,31 @@ type DBShare struct { State int } -// UserConverter describes an interface for converting user ids to names and back +// UserConverter describes an interface for converting user ids to names and back. type UserConverter interface { UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error) UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error) } -// GatewayUserConverter converts usernames and ids using the gateway +// GatewayUserConverter converts usernames and ids using the gateway. type GatewayUserConverter struct { gwAddr string } -// NewGatewayUserConverter returns a instance of GatewayUserConverter +// NewGatewayUserConverter returns a instance of GatewayUserConverter. func NewGatewayUserConverter(gwAddr string) *GatewayUserConverter { return &GatewayUserConverter{ gwAddr: gwAddr, } } -// UserIDToUserName converts a user ID to an username +// UserIDToUserName converts a user ID to an username. func (c *GatewayUserConverter) UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error) { gwConn, err := pool.GetGatewayServiceClient(pool.Endpoint(c.gwAddr)) if err != nil { return "", err } - getUserResponse, err := gwConn.GetUser(ctx, &userprovider.GetUserRequest{ + getUserResponse, err := gwConn.GetUser(ctx, &userpb.GetUserRequest{ UserId: userid, SkipFetchingUserGroups: true, }) @@ -91,7 +90,7 @@ func (c *GatewayUserConverter) UserIDToUserName(ctx context.Context, userid *use return getUserResponse.User.Username, nil } -// UserNameToUserID converts a username to an user ID +// UserNameToUserID converts a username to an user ID. func (c *GatewayUserConverter) UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error) { gwConn, err := pool.GetGatewayServiceClient(pool.Endpoint(c.gwAddr)) if err != nil { diff --git a/pkg/share/manager/sql/sql.go b/pkg/share/manager/sql/sql.go index 1164105637a..997d1d6492b 100644 --- a/pkg/share/manager/sql/sql.go +++ b/pkg/share/manager/sql/sql.go @@ -35,12 +35,12 @@ import ( "github.com/cs3org/reva/pkg/share" "github.com/cs3org/reva/pkg/share/manager/registry" "github.com/cs3org/reva/pkg/utils" + + // Provides mysql drivers. + _ "github.com/go-sql-driver/mysql" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" "google.golang.org/genproto/protobuf/field_mask" - - // Provides mysql drivers - _ "github.com/go-sql-driver/mysql" ) const ( @@ -55,11 +55,11 @@ func init() { type config struct { GatewayAddr string `mapstructure:"gateway_addr"` StorageMountID string `mapstructure:"storage_mount_id"` - DbUsername string `mapstructure:"db_username"` - DbPassword string `mapstructure:"db_password"` - DbHost string `mapstructure:"db_host"` - DbPort int `mapstructure:"db_port"` - DbName string `mapstructure:"db_name"` + DBUsername string `mapstructure:"db_username"` + DBPassword string `mapstructure:"db_password"` + DBHost string `mapstructure:"db_host"` + DBPort int `mapstructure:"db_port"` + DBName string `mapstructure:"db_name"` } type mgr struct { @@ -69,7 +69,7 @@ type mgr struct { userConverter UserConverter } -// NewMysql returns a new share manager connection to a mysql database +// NewMysql returns a new share manager connection to a mysql database. func NewMysql(m map[string]interface{}) (share.Manager, error) { c, err := parseConfig(m) if err != nil { @@ -77,7 +77,7 @@ func NewMysql(m map[string]interface{}) (share.Manager, error) { return nil, err } - db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName)) + db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName)) if err != nil { return nil, err } @@ -87,7 +87,7 @@ func NewMysql(m map[string]interface{}) (share.Manager, error) { return New("mysql", db, c.StorageMountID, userConverter) } -// New returns a new Cache instance connecting to the given sql.DB +// New returns a new Cache instance connecting to the given sql.DB. func New(driver string, db *sql.DB, storageMountID string, userConverter UserConverter) (share.Manager, error) { return &mgr{ driver: driver, @@ -401,7 +401,6 @@ func (m *mgr) GetReceivedShare(ctx context.Context, ref *collaboration.ShareRefe } return s, nil - } func (m *mgr) UpdateReceivedShare(ctx context.Context, share *collaboration.ReceivedShare, fieldMask *field_mask.FieldMask) (*collaboration.ReceivedShare, error) { @@ -542,7 +541,7 @@ func granteeTypeToShareType(granteeType provider.GranteeType) int { return -1 } -// translateFilters translates the filters to sql queries +// translateFilters translates the filters to sql queries. func translateFilters(filters []*collaboration.Filter) (string, []interface{}, error) { var ( filterQuery string diff --git a/pkg/share/manager/sql/sql_test.go b/pkg/share/manager/sql/sql_test.go index 35d4a92ff5a..2b1ae076a97 100644 --- a/pkg/share/manager/sql/sql_test.go +++ b/pkg/share/manager/sql/sql_test.go @@ -24,44 +24,41 @@ import ( "os" user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" ruser "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/share" sqlmanager "github.com/cs3org/reva/pkg/share/manager/sql" mocks "github.com/cs3org/reva/pkg/share/manager/sql/mocks" - "google.golang.org/protobuf/types/known/fieldmaskpb" - _ "github.com/mattn/go-sqlite3" - "github.com/stretchr/testify/mock" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/stretchr/testify/mock" + "google.golang.org/protobuf/types/known/fieldmaskpb" ) var _ = Describe("SQL manager", func() { var ( mgr share.Manager ctx context.Context - testDbFile *os.File + testDBFile *os.File - loginAs = func(user *userpb.User) { + loginAs = func(user *user.User) { ctx = ruser.ContextSetUser(context.Background(), user) } - admin = &userpb.User{ - Id: &userpb.UserId{ + admin = &user.User{ + Id: &user.UserId{ Idp: "idp", OpaqueId: "userid", - Type: userpb.UserType_USER_TYPE_PRIMARY, + Type: user.UserType_USER_TYPE_PRIMARY, }, Username: "admin", } - otherUser = &userpb.User{ - Id: &userpb.UserId{ + otherUser = &user.User{ + Id: &user.UserId{ Idp: "idp", OpaqueId: "userid", - Type: userpb.UserType_USER_TYPE_PRIMARY, + Type: user.UserType_USER_TYPE_PRIMARY, }, Username: "einstein", } @@ -74,30 +71,30 @@ var _ = Describe("SQL manager", func() { ) AfterEach(func() { - os.Remove(testDbFile.Name()) + os.Remove(testDBFile.Name()) }) BeforeEach(func() { var err error - testDbFile, err = os.CreateTemp("", "example") + testDBFile, err = os.CreateTemp("", "example") Expect(err).ToNot(HaveOccurred()) dbData, err := os.ReadFile("test.db") Expect(err).ToNot(HaveOccurred()) - _, err = testDbFile.Write(dbData) + _, err = testDBFile.Write(dbData) Expect(err).ToNot(HaveOccurred()) - err = testDbFile.Close() + err = testDBFile.Close() Expect(err).ToNot(HaveOccurred()) - sqldb, err := sql.Open("sqlite3", testDbFile.Name()) + sqldb, err := sql.Open("sqlite3", testDBFile.Name()) Expect(err).ToNot(HaveOccurred()) userConverter := &mocks.UserConverter{} userConverter.On("UserIDToUserName", mock.Anything, mock.Anything).Return("username", nil) userConverter.On("UserNameToUserID", mock.Anything, mock.Anything).Return( - func(_ context.Context, username string) *userpb.UserId { - return &userpb.UserId{ + func(_ context.Context, username string) *user.UserId { + return &user.UserId{ OpaqueId: username, } }, diff --git a/pkg/share/share.go b/pkg/share/share.go index d791353acbf..fc21e32d2e5 100644 --- a/pkg/share/share.go +++ b/pkg/share/share.go @@ -139,7 +139,7 @@ func MatchesAnyFilter(share *collaboration.Share, filters []*collaboration.Filte // MatchesFilters checks if the share passes the given filters. // Filters of the same type form a disjuntion, a logical OR. Filters of separate type form a conjunction, a logical AND. // Here is an example: -// (resource_id=1 OR resource_id=2) AND (grantee_type=USER OR grantee_type=GROUP) +// (resource_id=1 OR resource_id=2) AND (grantee_type=USER OR grantee_type=GROUP). func MatchesFilters(share *collaboration.Share, filters []*collaboration.Filter) bool { grouped := GroupFiltersByType(filters) for _, f := range grouped { diff --git a/pkg/sharedconf/sharedconf.go b/pkg/sharedconf/sharedconf.go index 784ab46ea07..5159d073bed 100644 --- a/pkg/sharedconf/sharedconf.go +++ b/pkg/sharedconf/sharedconf.go @@ -94,7 +94,7 @@ func SkipUserGroupsInToken() bool { return sharedConf.SkipUserGroupsInToken } -// GetBlockedUsers returns a list of blocked users +// GetBlockedUsers returns a list of blocked users. func GetBlockedUsers() []string { return sharedConf.BlockedUsers } diff --git a/pkg/siteacc/config/endpoints.go b/pkg/siteacc/config/endpoints.go index 94651936aac..8c9048d9eed 100644 --- a/pkg/siteacc/config/endpoints.go +++ b/pkg/siteacc/config/endpoints.go @@ -48,9 +48,9 @@ const ( EndpointLogin = "/login" // EndpointLogout is the endpoint path for (internal) user logout. EndpointLogout = "/logout" - // EndpointResetPassword is the endpoint path for resetting user passwords + // EndpointResetPassword is the endpoint path for resetting user passwords. EndpointResetPassword = "/reset-password" - // EndpointContact is the endpoint path for sending contact emails + // EndpointContact is the endpoint path for sending contact emails. EndpointContact = "/contact" // EndpointVerifyUserToken is the endpoint path for user token validation. diff --git a/pkg/siteacc/credentials/credentials.go b/pkg/siteacc/credentials/credentials.go index cb67c0685ae..d7c907e99f9 100644 --- a/pkg/siteacc/credentials/credentials.go +++ b/pkg/siteacc/credentials/credentials.go @@ -23,7 +23,7 @@ import ( "github.com/pkg/errors" ) -// Credentials stores and en-/decrypts credentials +// Credentials stores and en-/decrypts credentials. type Credentials struct { ID string `json:"id"` Secret string `json:"secret"` diff --git a/pkg/siteacc/data/account.go b/pkg/siteacc/data/account.go index cf8435a3e96..0bf808e03ff 100644 --- a/pkg/siteacc/data/account.go +++ b/pkg/siteacc/data/account.go @@ -23,9 +23,8 @@ import ( "time" "github.com/cs3org/reva/pkg/siteacc/credentials" - "github.com/pkg/errors" - "github.com/cs3org/reva/pkg/utils" + "github.com/pkg/errors" ) // Account represents a single sites account. diff --git a/pkg/siteacc/html/session.go b/pkg/siteacc/html/session.go index 5dfa59955f9..0eca4afd4dc 100644 --- a/pkg/siteacc/html/session.go +++ b/pkg/siteacc/html/session.go @@ -47,7 +47,7 @@ type Session struct { sessionCookieName string } -// SessionUser holds information about the logged in user +// SessionUser holds information about the logged in user. type SessionUser struct { Account *data.Account Operator *data.Operator diff --git a/pkg/siteacc/manager/opsmanager.go b/pkg/siteacc/manager/opsmanager.go index e0335e377ec..dbfbf16d47c 100644 --- a/pkg/siteacc/manager/opsmanager.go +++ b/pkg/siteacc/manager/opsmanager.go @@ -24,7 +24,6 @@ import ( "github.com/cs3org/reva/pkg/siteacc/config" "github.com/cs3org/reva/pkg/siteacc/data" - "github.com/pkg/errors" "github.com/rs/zerolog" ) diff --git a/pkg/smtpclient/smtpclient.go b/pkg/smtpclient/smtpclient.go index b616307e322..e35f445157d 100644 --- a/pkg/smtpclient/smtpclient.go +++ b/pkg/smtpclient/smtpclient.go @@ -64,7 +64,6 @@ func NewSMTPCredentials(c *SMTPCredentials) *SMTPCredentials { // SendMail allows sending mails using a set of client credentials. func (creds *SMTPCredentials) SendMail(recipient, subject, body string) error { - headers := map[string]string{ "From": creds.SenderMail, "To": recipient, @@ -89,7 +88,6 @@ func (creds *SMTPCredentials) SendMail(recipient, subject, body string) error { } func (creds *SMTPCredentials) sendMailAuthSMTP(recipient, subject, message string) error { - auth := smtp.PlainAuth("", creds.SenderLogin, creds.SenderPassword, creds.SMTPServer) err := smtp.SendMail( @@ -108,7 +106,6 @@ func (creds *SMTPCredentials) sendMailAuthSMTP(recipient, subject, message strin } func (creds *SMTPCredentials) sendMailSMTP(recipient, subject, message string) error { - c, err := smtp.Dial(fmt.Sprintf("%s:%d", creds.SMTPServer, creds.SMTPPort)) if err != nil { return err diff --git a/pkg/storage/favorite/loader/loader.go b/pkg/storage/favorite/loader/loader.go index 7ebcb6cbd26..91a7db3346f 100644 --- a/pkg/storage/favorite/loader/loader.go +++ b/pkg/storage/favorite/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load storage favorite drivers. _ "github.com/cs3org/reva/pkg/storage/favorite/memory" - // Add your own here + // Add your own here. ) diff --git a/pkg/storage/favorite/memory/memory_test.go b/pkg/storage/favorite/memory/memory_test.go index 263ed97ce6f..fb1ddcbce47 100644 --- a/pkg/storage/favorite/memory/memory_test.go +++ b/pkg/storage/favorite/memory/memory_test.go @@ -24,7 +24,6 @@ import ( user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - ctxpkg "github.com/cs3org/reva/pkg/ctx" ) diff --git a/pkg/storage/fs/cback/cback.go b/pkg/storage/fs/cback/cback.go index d1c6128fda6..f5a464b9e75 100644 --- a/pkg/storage/fs/cback/cback.go +++ b/pkg/storage/fs/cback/cback.go @@ -49,9 +49,8 @@ func init() { } // New returns an implementation to the storage.FS interface that talks to -// cback +// cback. func New(m map[string]interface{}) (fs storage.FS, err error) { - c := &Options{} if err = mapstructure.Decode(m, c); err != nil { return nil, errors.Wrap(err, "Error Decoding Configuration") @@ -61,7 +60,6 @@ func New(m map[string]interface{}) (fs storage.FS, err error) { // Returns the storage.FS interface return &cback{conf: c, client: httpClient}, nil - } func (fs *cback) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string) (*provider.ResourceInfo, error) { @@ -112,7 +110,6 @@ func (fs *cback) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []st } return ri, nil - } ret, err := fs.statResource(resp.ID, ssID, user.Username, searchPath, resp.Source) @@ -153,8 +150,7 @@ func (fs *cback) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []st } func (fs *cback) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys []string) ([]*provider.ResourceInfo, error) { - - var path string = ref.GetPath() + var path = ref.GetPath() var ssID, searchPath string user, inContext := ctxpkg.ContextGetUser(ctx) @@ -180,7 +176,6 @@ func (fs *cback) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys files := make([]*provider.ResourceInfo, 0, len(pathList)) for _, paths := range pathList { - setTime := v1beta1.Timestamp{ Seconds: 0, Nanos: 0, @@ -235,7 +230,6 @@ func (fs *cback) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys files := make([]*provider.ResourceInfo, 0, len(ret)) for _, j := range ret { - setTime := v1beta1.Timestamp{ Seconds: j.Mtime, Nanos: 0, @@ -268,14 +262,12 @@ func (fs *cback) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys } return files, nil - } // If match in path, therefore print the Snapshot IDs files := make([]*provider.ResourceInfo, 0, len(snapshotList)) for _, snapshot := range snapshotList { - epochTime, err := fs.timeConv(snapshot.Time) if err != nil { @@ -306,15 +298,13 @@ func (fs *cback) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys } files = append(files, &f) - } return files, nil - } func (fs *cback) Download(ctx context.Context, ref *provider.Reference) (io.ReadCloser, error) { - var path string = ref.GetPath() + var path = ref.GetPath() var ssID, searchPath string user, _ := ctxpkg.ContextGetUser(ctx) @@ -333,7 +323,6 @@ func (fs *cback) Download(ctx context.Context, ref *provider.Reference) (io.Read } if resp.Substring != "" { - ssID, searchPath = fs.pathTrimmer(snapshotList, resp) url := fs.conf.APIURL + "/backups/" + strconv.Itoa(resp.ID) + "/snapshots/" + ssID + "/" + searchPath @@ -345,7 +334,6 @@ func (fs *cback) Download(ctx context.Context, ref *provider.Reference) (io.Read } if md.Type == provider.ResourceType_RESOURCE_TYPE_FILE { - responseData, err := fs.getRequest(user.Username, url, requestType, nil) if err != nil { @@ -356,7 +344,6 @@ func (fs *cback) Download(ctx context.Context, ref *provider.Reference) (io.Read } return nil, errtypes.BadRequest("can only download files") - } return nil, errtypes.NotFound("cback: resource not found") @@ -488,10 +475,8 @@ func (fs *cback) Unlock(ctx context.Context, ref *provider.Reference, lock *prov func (fs *cback) Upload(ctx context.Context, ref *provider.Reference, r io.ReadCloser) error { return errtypes.NotSupported("Operation Not Permitted") - } func (fs *cback) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { return nil, errtypes.NotSupported("Operation Not Permitted") - } diff --git a/pkg/storage/fs/cback/options.go b/pkg/storage/fs/cback/options.go index 098905fa7bd..059f6df576d 100644 --- a/pkg/storage/fs/cback/options.go +++ b/pkg/storage/fs/cback/options.go @@ -18,7 +18,7 @@ package cback -// Options for the CBACK module +// Options for the CBACK module. type Options struct { ImpersonatorToken string `mapstructure:"token"` APIURL string `mapstructure:"api_url"` diff --git a/pkg/storage/fs/cback/utilities.go b/pkg/storage/fs/cback/utilities.go index 4be7bfe579b..850436860a6 100644 --- a/pkg/storage/fs/cback/utilities.go +++ b/pkg/storage/fs/cback/utilities.go @@ -109,7 +109,6 @@ func mapReturn(fileType string) (provider.ResourceType, error) { } func (fs *cback) getRequest(userName, url string, reqType string, body io.Reader) (io.ReadCloser, error) { - req, err := http.NewRequest(reqType, url, body) req.SetBasicAuth(userName, fs.conf.ImpersonatorToken) @@ -130,9 +129,7 @@ func (fs *cback) getRequest(userName, url string, reqType string, body io.Reader } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - switch resp.StatusCode { - case http.StatusNotFound: return nil, errtypes.NotFound("cback: resource not found") case http.StatusForbidden: @@ -145,11 +142,9 @@ func (fs *cback) getRequest(userName, url string, reqType string, body io.Reader } return resp.Body, nil - } func (fs *cback) listSnapshots(userName string, backupID int) ([]snapshotResponse, error) { - url := fs.conf.APIURL + "/backups/" + strconv.Itoa(backupID) + "/snapshots" responseData, err := fs.getRequest(userName, url, http.MethodGet, nil) @@ -172,7 +167,6 @@ func (fs *cback) listSnapshots(userName string, backupID int) ([]snapshotRespons } func (fs *cback) matchBackups(userName, pathInput string) (*backUpResponse, error) { - url := fs.conf.APIURL + "/backups/" responseData, err := fs.getRequest(userName, url, http.MethodGet, nil) @@ -228,7 +222,6 @@ func (fs *cback) matchBackups(userName, pathInput string) (*backUpResponse, erro } func (fs *cback) statResource(backupID int, snapID, userName, path, source string) (*fsReturn, error) { - url := fs.conf.APIURL + "/backups/" + strconv.Itoa(backupID) + "/snapshots/" + snapID + "/" + path + "?content=false" responseData, err := fs.getRequest(userName, url, http.MethodOptions, nil) @@ -264,7 +257,6 @@ func (fs *cback) statResource(backupID int, snapID, userName, path, source strin } func (fs *cback) fileSystem(backupID int, snapID, userName, path, source string) ([]*fsReturn, error) { - url := fs.conf.APIURL + "/backups/" + strconv.Itoa(backupID) + "/snapshots/" + snapID + "/" + path + "?content=true" responseData, err := fs.getRequest(userName, url, http.MethodOptions, nil) @@ -286,7 +278,6 @@ func (fs *cback) fileSystem(backupID int, snapID, userName, path, source string) resp := make([]*fsReturn, 0, len(responseObject)) for _, response := range responseObject { - m, err := mapReturn(response.Type) if err != nil { @@ -359,20 +350,16 @@ func (fs *cback) pathFinder(userName, path string) ([]string, error) { } return nil, errtypes.NotFound("cback: resource not found") - } func (fs *cback) pathTrimmer(snapshotList []snapshotResponse, resp *backUpResponse) (string, string) { - var ssID, searchPath string for _, snapshot := range snapshotList { - if snapshot.ID == resp.Substring { ssID = resp.Substring searchPath = resp.Source break - } else if strings.HasPrefix(resp.Substring, snapshot.ID) { searchPath = strings.TrimPrefix(resp.Substring, snapshot.ID) searchPath = resp.Source + searchPath @@ -382,7 +369,6 @@ func (fs *cback) pathTrimmer(snapshotList []snapshotResponse, resp *backUpRespon } return ssID, searchPath - } func duplicateRemoval(strSlice []string) []string { diff --git a/pkg/storage/fs/cephfs/unsupported.go b/pkg/storage/fs/cephfs/unsupported.go index a337f3f7895..9fa0a538471 100644 --- a/pkg/storage/fs/cephfs/unsupported.go +++ b/pkg/storage/fs/cephfs/unsupported.go @@ -22,10 +22,9 @@ package cephfs import ( - "github.com/pkg/errors" - "github.com/cs3org/reva/pkg/storage" "github.com/cs3org/reva/pkg/storage/fs/registry" + "github.com/pkg/errors" ) func init() { diff --git a/pkg/storage/fs/loader/loader.go b/pkg/storage/fs/loader/loader.go index e0b9f53575f..4049cb657d1 100644 --- a/pkg/storage/fs/loader/loader.go +++ b/pkg/storage/fs/loader/loader.go @@ -34,5 +34,5 @@ import ( _ "github.com/cs3org/reva/pkg/storage/fs/owncloudsql" _ "github.com/cs3org/reva/pkg/storage/fs/s3" _ "github.com/cs3org/reva/pkg/storage/fs/s3ng" - // Add your own here + // Add your own here. ) diff --git a/pkg/storage/fs/nextcloud/nextcloud.go b/pkg/storage/fs/nextcloud/nextcloud.go index 3621b468e04..c00792c46e4 100644 --- a/pkg/storage/fs/nextcloud/nextcloud.go +++ b/pkg/storage/fs/nextcloud/nextcloud.go @@ -42,7 +42,7 @@ func init() { registry.Register("nextcloud", New) } -// StorageDriverConfig is the configuration struct for a NextcloudStorageDriver +// StorageDriverConfig is the configuration struct for a NextcloudStorageDriver. type StorageDriverConfig struct { EndPoint string `mapstructure:"endpoint"` // e.g. "http://nc/apps/sciencemesh/~alice/" SharedSecret string `mapstructure:"shared_secret"` @@ -50,7 +50,7 @@ type StorageDriverConfig struct { } // StorageDriver implements the storage.FS interface -// and connects with a StorageDriver server as its backend +// and connects with a StorageDriver server as its backend. type StorageDriver struct { endPoint string sharedSecret string @@ -77,7 +77,7 @@ func New(m map[string]interface{}) (storage.FS, error) { return NewStorageDriver(conf) } -// NewStorageDriver returns a new NextcloudStorageDriver +// NewStorageDriver returns a new NextcloudStorageDriver. func NewStorageDriver(c *StorageDriverConfig) (*StorageDriver, error) { var client *http.Client if c.MockHTTP { @@ -104,7 +104,7 @@ func NewStorageDriver(c *StorageDriverConfig) (*StorageDriver, error) { }, nil } -// Action describes a REST request to forward to the Nextcloud backend +// Action describes a REST request to forward to the Nextcloud backend. type Action struct { verb string argS string @@ -119,7 +119,7 @@ func getUser(ctx context.Context) (*user.User, error) { return u, nil } -// SetHTTPClient sets the HTTP client +// SetHTTPClient sets the HTTP client. func (nc *StorageDriver) SetHTTPClient(c *http.Client) { nc.client = c } @@ -233,7 +233,7 @@ func (nc *StorageDriver) do(ctx context.Context, a Action) (int, []byte, error) return resp.StatusCode, body, nil } -// GetHome as defined in the storage.FS interface +// GetHome as defined in the storage.FS interface. func (nc *StorageDriver) GetHome(ctx context.Context) (string, error) { log := appctx.GetLogger(ctx) log.Info().Msg("GetHome") @@ -242,7 +242,7 @@ func (nc *StorageDriver) GetHome(ctx context.Context) (string, error) { return string(respBody), err } -// CreateHome as defined in the storage.FS interface +// CreateHome as defined in the storage.FS interface. func (nc *StorageDriver) CreateHome(ctx context.Context) error { log := appctx.GetLogger(ctx) log.Info().Msg("CreateHome") @@ -251,7 +251,7 @@ func (nc *StorageDriver) CreateHome(ctx context.Context) error { return err } -// CreateDir as defined in the storage.FS interface +// CreateDir as defined in the storage.FS interface. func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) error { bodyStr, err := json.Marshal(ref) if err != nil { @@ -264,12 +264,12 @@ func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) return err } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } -// Delete as defined in the storage.FS interface +// Delete as defined in the storage.FS interface. func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) error { bodyStr, err := json.Marshal(ref) if err != nil { @@ -282,7 +282,7 @@ func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) er return err } -// Move as defined in the storage.FS interface +// Move as defined in the storage.FS interface. func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Reference) error { type paramsObj struct { OldRef *provider.Reference `json:"oldRef"` @@ -300,7 +300,7 @@ func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Refe return err } -// GetMD as defined in the storage.FS interface +// GetMD as defined in the storage.FS interface. func (nc *StorageDriver) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string) (*provider.ResourceInfo, error) { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -330,7 +330,7 @@ func (nc *StorageDriver) GetMD(ctx context.Context, ref *provider.Reference, mdK return &respObj, nil } -// ListFolder as defined in the storage.FS interface +// ListFolder as defined in the storage.FS interface. func (nc *StorageDriver) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys []string) ([]*provider.ResourceInfo, error) { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -366,7 +366,7 @@ func (nc *StorageDriver) ListFolder(ctx context.Context, ref *provider.Reference return pointers, err } -// InitiateUpload as defined in the storage.FS interface +// InitiateUpload as defined in the storage.FS interface. func (nc *StorageDriver) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -394,17 +394,17 @@ func (nc *StorageDriver) InitiateUpload(ctx context.Context, ref *provider.Refer return respMap, err } -// Upload as defined in the storage.FS interface +// Upload as defined in the storage.FS interface. func (nc *StorageDriver) Upload(ctx context.Context, ref *provider.Reference, r io.ReadCloser) error { return nc.doUpload(ctx, ref.Path, r) } -// Download as defined in the storage.FS interface +// Download as defined in the storage.FS interface. func (nc *StorageDriver) Download(ctx context.Context, ref *provider.Reference) (io.ReadCloser, error) { return nc.doDownload(ctx, ref.Path) } -// ListRevisions as defined in the storage.FS interface +// ListRevisions as defined in the storage.FS interface. func (nc *StorageDriver) ListRevisions(ctx context.Context, ref *provider.Reference) ([]*provider.FileVersion, error) { bodyStr, _ := json.Marshal(ref) log := appctx.GetLogger(ctx) @@ -427,7 +427,7 @@ func (nc *StorageDriver) ListRevisions(ctx context.Context, ref *provider.Refere return revs, err } -// DownloadRevision as defined in the storage.FS interface +// DownloadRevision as defined in the storage.FS interface. func (nc *StorageDriver) DownloadRevision(ctx context.Context, ref *provider.Reference, key string) (io.ReadCloser, error) { log := appctx.GetLogger(ctx) log.Info().Msgf("DownloadRevision %s %s", ref.Path, key) @@ -436,7 +436,7 @@ func (nc *StorageDriver) DownloadRevision(ctx context.Context, ref *provider.Ref return readCloser, err } -// RestoreRevision as defined in the storage.FS interface +// RestoreRevision as defined in the storage.FS interface. func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -454,7 +454,7 @@ func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Refe return err } -// ListRecycle as defined in the storage.FS interface +// ListRecycle as defined in the storage.FS interface. func (nc *StorageDriver) ListRecycle(ctx context.Context, basePath, key string, relativePath string) ([]*provider.RecycleItem, error) { log := appctx.GetLogger(ctx) log.Info().Msg("ListRecycle") @@ -485,7 +485,7 @@ func (nc *StorageDriver) ListRecycle(ctx context.Context, basePath, key string, return items, err } -// RestoreRecycleItem as defined in the storage.FS interface +// RestoreRecycleItem as defined in the storage.FS interface. func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, basePath, key, relativePath string, restoreRef *provider.Reference) error { type paramsObj struct { Key string `json:"key"` @@ -507,7 +507,7 @@ func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, basePath, key, return err } -// PurgeRecycleItem as defined in the storage.FS interface +// PurgeRecycleItem as defined in the storage.FS interface. func (nc *StorageDriver) PurgeRecycleItem(ctx context.Context, basePath, key, relativePath string) error { type paramsObj struct { Key string `json:"key"` @@ -525,7 +525,7 @@ func (nc *StorageDriver) PurgeRecycleItem(ctx context.Context, basePath, key, re return err } -// EmptyRecycle as defined in the storage.FS interface +// EmptyRecycle as defined in the storage.FS interface. func (nc *StorageDriver) EmptyRecycle(ctx context.Context) error { log := appctx.GetLogger(ctx) log.Info().Msg("EmptyRecycle") @@ -534,14 +534,14 @@ func (nc *StorageDriver) EmptyRecycle(ctx context.Context) error { return err } -// GetPathByID as defined in the storage.FS interface +// GetPathByID as defined in the storage.FS interface. func (nc *StorageDriver) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { bodyStr, _ := json.Marshal(id) _, respBody, err := nc.do(ctx, Action{"GetPathByID", string(bodyStr)}) return string(respBody), err } -// AddGrant as defined in the storage.FS interface +// AddGrant as defined in the storage.FS interface. func (nc *StorageDriver) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -559,7 +559,7 @@ func (nc *StorageDriver) AddGrant(ctx context.Context, ref *provider.Reference, return err } -// DenyGrant as defined in the storage.FS interface +// DenyGrant as defined in the storage.FS interface. func (nc *StorageDriver) DenyGrant(ctx context.Context, ref *provider.Reference, g *provider.Grantee) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -577,7 +577,7 @@ func (nc *StorageDriver) DenyGrant(ctx context.Context, ref *provider.Reference, return err } -// RemoveGrant as defined in the storage.FS interface +// RemoveGrant as defined in the storage.FS interface. func (nc *StorageDriver) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -595,7 +595,7 @@ func (nc *StorageDriver) RemoveGrant(ctx context.Context, ref *provider.Referenc return err } -// UpdateGrant as defined in the storage.FS interface +// UpdateGrant as defined in the storage.FS interface. func (nc *StorageDriver) UpdateGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -613,7 +613,7 @@ func (nc *StorageDriver) UpdateGrant(ctx context.Context, ref *provider.Referenc return err } -// ListGrants as defined in the storage.FS interface +// ListGrants as defined in the storage.FS interface. func (nc *StorageDriver) ListGrants(ctx context.Context, ref *provider.Reference) ([]*provider.Grant, error) { bodyStr, _ := json.Marshal(ref) log := appctx.GetLogger(ctx) @@ -691,7 +691,7 @@ func (nc *StorageDriver) ListGrants(ctx context.Context, ref *provider.Reference return grants, err } -// GetQuota as defined in the storage.FS interface +// GetQuota as defined in the storage.FS interface. func (nc *StorageDriver) GetQuota(ctx context.Context, ref *provider.Reference) (uint64, uint64, error) { log := appctx.GetLogger(ctx) log.Info().Msg("GetQuota") @@ -709,7 +709,7 @@ func (nc *StorageDriver) GetQuota(ctx context.Context, ref *provider.Reference) return uint64(respMap["totalBytes"].(float64)), uint64(respMap["usedBytes"].(float64)), err } -// CreateReference as defined in the storage.FS interface +// CreateReference as defined in the storage.FS interface. func (nc *StorageDriver) CreateReference(ctx context.Context, path string, targetURI *url.URL) error { type paramsObj struct { Path string `json:"path"` @@ -725,7 +725,7 @@ func (nc *StorageDriver) CreateReference(ctx context.Context, path string, targe return err } -// Shutdown as defined in the storage.FS interface +// Shutdown as defined in the storage.FS interface. func (nc *StorageDriver) Shutdown(ctx context.Context) error { log := appctx.GetLogger(ctx) log.Info().Msg("Shutdown") @@ -734,7 +734,7 @@ func (nc *StorageDriver) Shutdown(ctx context.Context) error { return err } -// SetArbitraryMetadata as defined in the storage.FS interface +// SetArbitraryMetadata as defined in the storage.FS interface. func (nc *StorageDriver) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -752,7 +752,7 @@ func (nc *StorageDriver) SetArbitraryMetadata(ctx context.Context, ref *provider return err } -// UnsetArbitraryMetadata as defined in the storage.FS interface +// UnsetArbitraryMetadata as defined in the storage.FS interface. func (nc *StorageDriver) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) error { type paramsObj struct { Ref *provider.Reference `json:"ref"` @@ -770,27 +770,27 @@ func (nc *StorageDriver) UnsetArbitraryMetadata(ctx context.Context, ref *provid return err } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (nc *StorageDriver) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (nc *StorageDriver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (nc *StorageDriver) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (nc *StorageDriver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// ListStorageSpaces as defined in the storage.FS interface +// ListStorageSpaces as defined in the storage.FS interface. func (nc *StorageDriver) ListStorageSpaces(ctx context.Context, f []*provider.ListStorageSpacesRequest_Filter) ([]*provider.StorageSpace, error) { bodyStr, _ := json.Marshal(f) _, respBody, err := nc.do(ctx, Action{"ListStorageSpaces", string(bodyStr)}) @@ -811,7 +811,7 @@ func (nc *StorageDriver) ListStorageSpaces(ctx context.Context, f []*provider.Li return spaces, err } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (nc *StorageDriver) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { bodyStr, _ := json.Marshal(req) _, respBody, err := nc.do(ctx, Action{"CreateStorageSpace", string(bodyStr)}) @@ -826,7 +826,7 @@ func (nc *StorageDriver) CreateStorageSpace(ctx context.Context, req *provider.C return &respObj, nil } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (nc *StorageDriver) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { bodyStr, _ := json.Marshal(req) _, respBody, err := nc.do(ctx, Action{"UpdateStorageSpace", string(bodyStr)}) diff --git a/pkg/storage/fs/nextcloud/nextcloud_server_mock.go b/pkg/storage/fs/nextcloud/nextcloud_server_mock.go index 675a1e92f02..f0e633e695f 100644 --- a/pkg/storage/fs/nextcloud/nextcloud_server_mock.go +++ b/pkg/storage/fs/nextcloud/nextcloud_server_mock.go @@ -29,7 +29,7 @@ import ( ) // Response contains data for the Nextcloud mock server to respond -// and to switch to a new server state +// and to switch to a new server state. type Response struct { code int body string @@ -171,7 +171,7 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~tester/api/storage/CreateStorageSpace {"opaque":{"map":{"bar":{"value":"c2FtYQ=="},"foo":{"value":"c2FtYQ=="}}},"owner":{"id":{"idp":"some-idp","opaque_id":"some-opaque-user-id","type":1}},"type":"home","name":"My Storage Space","quota":{"quota_max_bytes":456,"quota_max_files":123}}`: {200, `{"storage_space":{"opaque":{"map":{"bar":{"value":"c2FtYQ=="},"foo":{"value":"c2FtYQ=="}}},"id":{"opaque_id":"some-opaque-storage-space-id"},"owner":{"id":{"idp":"some-idp","opaque_id":"some-opaque-user-id","type":1}},"root":{"storage_id":"some-storage-ud","opaque_id":"some-opaque-root-id"},"name":"My Storage Space","quota":{"quota_max_bytes":456,"quota_max_files":123},"space_type":"home","mtime":{"seconds":1234567890}}}`, serverStateEmpty}, } -// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server +// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server. func GetNextcloudServerMock(called *[]string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf := new(strings.Builder) diff --git a/pkg/storage/fs/nextcloud/nextcloud_test.go b/pkg/storage/fs/nextcloud/nextcloud_test.go index aa0e0a451d0..24867e38b8f 100644 --- a/pkg/storage/fs/nextcloud/nextcloud_test.go +++ b/pkg/storage/fs/nextcloud/nextcloud_test.go @@ -20,15 +20,12 @@ package nextcloud_test import ( "context" - - // "fmt" + // "fmt". "io" "net/url" "os" "strings" - "google.golang.org/grpc/metadata" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" @@ -36,9 +33,9 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/storage/fs/nextcloud" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/grpc/metadata" ) func setUpNextcloudServer() (*nextcloud.StorageDriver, *[]string, func()) { diff --git a/pkg/storage/fs/ocis/blobstore/blobstore.go b/pkg/storage/fs/ocis/blobstore/blobstore.go index aab9f88ca48..26e00f30a04 100644 --- a/pkg/storage/fs/ocis/blobstore/blobstore.go +++ b/pkg/storage/fs/ocis/blobstore/blobstore.go @@ -27,12 +27,12 @@ import ( "github.com/pkg/errors" ) -// Blobstore provides an interface to an filesystem based blobstore +// Blobstore provides an interface to an filesystem based blobstore. type Blobstore struct { root string } -// New returns a new Blobstore +// New returns a new Blobstore. func New(root string) (*Blobstore, error) { err := os.MkdirAll(root, 0700) if err != nil { @@ -44,7 +44,7 @@ func New(root string) (*Blobstore, error) { }, nil } -// Upload stores some data in the blobstore under the given key +// Upload stores some data in the blobstore under the given key. func (bs *Blobstore) Upload(key string, data io.Reader) error { f, err := os.OpenFile(bs.path(key), os.O_CREATE|os.O_WRONLY, 0700) if err != nil { @@ -60,7 +60,7 @@ func (bs *Blobstore) Upload(key string, data io.Reader) error { return w.Flush() } -// Download retrieves a blob from the blobstore for reading +// Download retrieves a blob from the blobstore for reading. func (bs *Blobstore) Download(key string) (io.ReadCloser, error) { file, err := os.Open(bs.path(key)) if err != nil { @@ -69,7 +69,7 @@ func (bs *Blobstore) Download(key string) (io.ReadCloser, error) { return file, nil } -// Delete deletes a blob from the blobstore +// Delete deletes a blob from the blobstore. func (bs *Blobstore) Delete(key string) error { err := os.Remove(bs.path(key)) if err != nil { diff --git a/pkg/storage/fs/ocis/blobstore/blobstore_test.go b/pkg/storage/fs/ocis/blobstore/blobstore_test.go index 4d875575c55..fe7947152d3 100644 --- a/pkg/storage/fs/ocis/blobstore/blobstore_test.go +++ b/pkg/storage/fs/ocis/blobstore/blobstore_test.go @@ -26,7 +26,6 @@ import ( "github.com/cs3org/reva/pkg/storage/fs/ocis/blobstore" "github.com/cs3org/reva/tests/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/fs/ocis/ocis_test.go b/pkg/storage/fs/ocis/ocis_test.go index e2f4e32efcf..785b2cd1214 100644 --- a/pkg/storage/fs/ocis/ocis_test.go +++ b/pkg/storage/fs/ocis/ocis_test.go @@ -23,7 +23,6 @@ import ( "github.com/cs3org/reva/pkg/storage/fs/ocis" "github.com/cs3org/reva/tests/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/fs/owncloud/owncloud.go b/pkg/storage/fs/owncloud/owncloud.go index 000c78e990d..69d7ccd88f9 100644 --- a/pkg/storage/fs/owncloud/owncloud.go +++ b/pkg/storage/fs/owncloud/owncloud.go @@ -62,13 +62,13 @@ const ( // A non root user can only manipulate the user. namespace, which is what // we will use to store ownCloud specific metadata. To prevent name // collisions with other apps We are going to introduce a sub namespace - // "user.oc." + // "user.oc.". ocPrefix string = "user.oc." - // idAttribute is the name of the filesystem extended attribute that is used to store the uuid in + // idAttribute is the name of the filesystem extended attribute that is used to store the uuid in. idAttribute string = ocPrefix + "id" - // SharePrefix is the prefix for sharing related extended attributes + // SharePrefix is the prefix for sharing related extended attributes. sharePrefix string = ocPrefix + "grant." // grants are similar to acls, but they are not propagated down the tree when being changed trashOriginPrefix string = ocPrefix + "o" mdPrefix string = ocPrefix + "md." // arbitrary metadata @@ -219,7 +219,7 @@ func (fs *ocfs) Shutdown(ctx context.Context) error { return fs.pool.Close() } -// scan files and add uuid to path mapping to kv store +// scan files and add uuid to path mapping to kv store. func (fs *ocfs) scanFiles(ctx context.Context, conn redis.Conn) { if fs.c.Scan { fs.c.Scan = false // TODO ... in progress use mutex ? @@ -258,7 +258,7 @@ func (fs *ocfs) scanFiles(ctx context.Context, conn redis.Conn) { // owncloud stores files in the files subfolder // the incoming path starts with /, so we need to insert the files subfolder into the path // and prefix the data directory -// TODO the path handed to a storage provider should not contain the username +// TODO the path handed to a storage provider should not contain the username. func (fs *ocfs) toInternalPath(ctx context.Context, sp string) (ip string) { if fs.c.EnableHome { u := ctxpkg.ContextMustGetUser(ctx) @@ -294,7 +294,6 @@ func (fs *ocfs) toInternalPath(ctx context.Context, sp string) (ip string) { // parts = "", "foo/bar.txt" ip = filepath.Join(fs.c.DataDirectory, layout, "files", segments[1]) } - } return } @@ -339,7 +338,7 @@ func (fs *ocfs) toInternalShadowPath(ctx context.Context, sp string) (internal s // ownloud stores versions in the files_versions subfolder // the incoming path starts with /, so we need to insert the files subfolder into the path // and prefix the data directory -// TODO the path handed to a storage provider should not contain the username +// TODO the path handed to a storage provider should not contain the username. func (fs *ocfs) getVersionsPath(ctx context.Context, ip string) string { // ip = /path/to/data//files/foo/bar.txt // remove data dir @@ -368,10 +367,9 @@ func (fs *ocfs) getVersionsPath(ctx context.Context, ip string) string { default: return "" // TODO Must not happen? } - } -// owncloud stores trashed items in the files_trashbin subfolder of a users home +// owncloud stores trashed items in the files_trashbin subfolder of a users home. func (fs *ocfs) getRecyclePath(ctx context.Context) (string, error) { u, ok := ctxpkg.ContextGetUser(ctx) if !ok { @@ -461,7 +459,7 @@ func (fs *ocfs) toStorageShadowPath(ctx context.Context, ip string) (sp string) return } -// TODO the owner needs to come from a different place +// TODO the owner needs to come from a different place. func (fs *ocfs) getOwner(ip string) string { ip = strings.TrimPrefix(ip, fs.c.DataDirectory) parts := strings.SplitN(ip, "/", 3) @@ -471,7 +469,7 @@ func (fs *ocfs) getOwner(ip string) string { return "" } -// TODO cache user lookup +// TODO cache user lookup. func (fs *ocfs) getUser(ctx context.Context, usernameOrID string) (id *userpb.User, err error) { u := ctxpkg.ContextMustGetUser(ctx) // check if username matches and id is set @@ -528,7 +526,7 @@ func (fs *ocfs) getUser(ctx context.Context, usernameOrID string) (id *userpb.Us return res.User, nil } -// permissionSet returns the permission set for the current user +// permissionSet returns the permission set for the current user. func (fs *ocfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions { if owner == nil { return &provider.ResourcePermissions{ @@ -705,7 +703,7 @@ func getResourceType(isDir bool) provider.ResourceType { return provider.ResourceType_RESOURCE_TYPE_FILE } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *ocfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { return nil, fmt.Errorf("unimplemented: CreateStorageSpace") } @@ -775,7 +773,7 @@ func (fs *ocfs) getPath(ctx context.Context, id *provider.ResourceId) (string, e return ip, nil } -// GetPathByID returns the storage relative path for the file id, without the internal namespace +// GetPathByID returns the storage relative path for the file id, without the internal namespace. func (fs *ocfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { ip, err := fs.getPath(ctx, id) if err != nil { @@ -799,7 +797,6 @@ func (fs *ocfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (strin // resolve takes in a request path or request id and converts it to an internal path. func (fs *ocfs) resolve(ctx context.Context, ref *provider.Reference) (string, error) { - // if storage id is set look up that if ref.ResourceId != nil { ip, err := fs.getPath(ctx, ref.ResourceId) @@ -811,7 +808,6 @@ func (fs *ocfs) resolve(ctx context.Context, ref *provider.Reference) (string, e // use a path return fs.toInternalPath(ctx, ref.Path), nil - } func (fs *ocfs) DenyGrant(ctx context.Context, ref *provider.Reference, g *provider.Grantee) error { @@ -844,7 +840,7 @@ func (fs *ocfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provid return fs.propagate(ctx, ip) } -// extractACEsFromAttrs reads ACEs in the list of attrs from the file +// extractACEsFromAttrs reads ACEs in the list of attrs from the file. func extractACEsFromAttrs(ctx context.Context, ip string, attrs []string) (entries []*ace.ACE) { log := appctx.GetLogger(ctx) entries = []*ace.ACE{} @@ -874,9 +870,8 @@ func extractACEsFromAttrs(ctx context.Context, ip string, attrs []string) (entri // We could also add default acls that can only the admin can set, eg for a read only storage? // Someone needs to write to provide the content that should be read only, so this would likely be an acl for a group anyway. // We need the storage relative path so we can calculate the permissions -// for the node based on all acls in the tree up to the root +// for the node based on all acls in the tree up to the root. func (fs *ocfs) readPermissions(ctx context.Context, ip string) (p *provider.ResourcePermissions, err error) { - u, ok := ctxpkg.ContextGetUser(ctx) if !ok { appctx.GetLogger(ctx).Debug().Str("ipath", ip).Msg("no user in context, returning default permissions") @@ -908,7 +903,6 @@ func (fs *ocfs) readPermissions(ctx context.Context, ip string) (p *provider.Res var e *ace.ACE // for all segments, starting at the leaf for np != rp { - var attrs []string if attrs, err = xattr.List(np); err != nil { appctx.GetLogger(ctx).Error().Err(err).Str("ipath", np).Msg("error listing attributes") @@ -1005,7 +999,7 @@ func (fs *ocfs) readACE(ctx context.Context, ip string, principal string) (e *ac return } -// additive merging of permissions only +// additive merging of permissions only. func addPermissions(p1 *provider.ResourcePermissions, p2 *provider.ResourcePermissions) { p1.AddGrant = p1.AddGrant || p2.AddGrant p1.CreateContainer = p1.CreateContainer || p2.CreateContainer @@ -1066,7 +1060,6 @@ func (fs *ocfs) ListGrants(ctx context.Context, ref *provider.Reference) (grants } func (fs *ocfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) { - var ip string if ip, err = fs.resolve(ctx, ref); err != nil { return errors.Wrap(err, "ocfs: error resolving reference") @@ -1149,7 +1142,7 @@ func (fs *ocfs) CreateHome(ctx context.Context) error { return nil } -// If home is enabled, the relative home is always the empty string +// If home is enabled, the relative home is always the empty string. func (fs *ocfs) GetHome(ctx context.Context) (string, error) { if !fs.c.EnableHome { return "", errtypes.NotSupported("ocfs: get home not supported") @@ -1158,7 +1151,6 @@ func (fs *ocfs) GetHome(ctx context.Context) (string, error) { } func (fs *ocfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { - ip, err := fs.resolve(ctx, ref) if err != nil { return err @@ -1186,7 +1178,7 @@ func (fs *ocfs) CreateDir(ctx context.Context, ref *provider.Reference) (err err return fs.propagate(ctx, ip) } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *ocfs) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } @@ -1473,22 +1465,22 @@ func (fs *ocfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Refere } } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *ocfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *ocfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *ocfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *ocfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } @@ -1769,7 +1761,6 @@ func (fs *ocfs) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys } func (fs *ocfs) listWithNominalHome(ctx context.Context, ip string, mdKeys []string) ([]*provider.ResourceInfo, error) { - // If a user wants to list a folder shared with him the path will already // be wrapped with the files directory path of the share owner. // In that case we don't want to wrap the path again. @@ -2043,7 +2034,6 @@ func (fs *ocfs) ListRevisions(ctx context.Context, ref *provider.Reference) ([]* if rev != nil { revisions = append(revisions, rev) } - } return revisions, nil } @@ -2256,7 +2246,6 @@ func (fs *ocfs) ListRecycle(ctx context.Context, basePath, key, relativePath str if ri != nil { items = append(items, ri) } - } return items, nil } @@ -2306,7 +2295,7 @@ func (fs *ocfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListSt return nil, errtypes.NotSupported("list storage spaces") } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *ocfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { return nil, errtypes.NotSupported("update storage space") } diff --git a/pkg/storage/fs/owncloud/owncloud_unix.go b/pkg/storage/fs/owncloud/owncloud_unix.go old mode 100755 new mode 100644 index 61cc65433df..a858431f37e --- a/pkg/storage/fs/owncloud/owncloud_unix.go +++ b/pkg/storage/fs/owncloud/owncloud_unix.go @@ -41,7 +41,7 @@ import ( // - inode (if available), // - device (if available) and // - size. -// errors are logged, but an etag will still be returned +// errors are logged, but an etag will still be returned. func calcEtag(ctx context.Context, fi os.FileInfo) string { log := appctx.GetLogger(ctx) h := md5.New() diff --git a/pkg/storage/fs/owncloud/upload.go b/pkg/storage/fs/owncloud/upload.go index dccc170aa78..f0ac63187e6 100644 --- a/pkg/storage/fs/owncloud/upload.go +++ b/pkg/storage/fs/owncloud/upload.go @@ -92,7 +92,7 @@ func (fs *ocfs) Upload(ctx context.Context, ref *provider.Reference, r io.ReadCl } // InitiateUpload returns upload ids corresponding to different protocols it supports -// TODO read optional content for small files in this request +// TODO read optional content for small files in this request. func (fs *ocfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { ip, err := fs.resolve(ctx, ref) if err != nil { @@ -146,7 +146,6 @@ func (fs *ocfs) UseIn(composer *tusd.StoreComposer) { // - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload func (fs *ocfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - log := appctx.GetLogger(ctx) log.Debug().Interface("info", info).Msg("ocfs: NewUpload") @@ -241,7 +240,7 @@ func (fs *ocfs) getUploadPath(ctx context.Context, uploadID string) (string, err return filepath.Join(fs.c.DataDirectory, layout, "uploads", uploadID), nil } -// GetUpload returns the Upload for the given upload id +// GetUpload returns the Upload for the given upload id. func (fs *ocfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { infoPath := filepath.Join(fs.c.UploadInfoDir, filepath.Join("/", id+".info")) @@ -305,12 +304,12 @@ type fileUpload struct { ctx context.Context } -// GetInfo returns the FileInfo +// GetInfo returns the FileInfo. func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { return upload.info, nil } -// WriteChunk writes the stream from the reader to the given offset of the upload +// WriteChunk writes the stream from the reader to the given offset of the upload. func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { @@ -336,7 +335,7 @@ func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.R return n, err } -// GetReader returns an io.Reader for the upload +// GetReader returns an io.Reader for the upload. func (upload *fileUpload) GetReader(ctx context.Context) (io.Reader, error) { return os.Open(upload.binPath) } @@ -350,7 +349,7 @@ func (upload *fileUpload) writeInfo() error { return os.WriteFile(upload.infoPath, data, defaultFilePerm) } -// FinishUpload finishes an upload and moves the file to the internal destination +// FinishUpload finishes an upload and moves the file to the internal destination. func (upload *fileUpload) FinishUpload(ctx context.Context) error { log := appctx.GetLogger(upload.ctx) @@ -453,12 +452,12 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) error { // - the storage needs to implement AsTerminatableUpload // - the upload needs to implement Terminate -// AsTerminatableUpload returns a TerminatableUpload +// AsTerminatableUpload returns a TerminatableUpload. func (fs *ocfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { return upload.(*fileUpload) } -// Terminate terminates the upload +// Terminate terminates the upload. func (upload *fileUpload) Terminate(ctx context.Context) error { if err := os.Remove(upload.infoPath); err != nil { if !os.IsNotExist(err) { @@ -477,12 +476,12 @@ func (upload *fileUpload) Terminate(ctx context.Context) error { // - the storage needs to implement AsLengthDeclarableUpload // - the upload needs to implement DeclareLength -// AsLengthDeclarableUpload returns a LengthDeclarableUpload +// AsLengthDeclarableUpload returns a LengthDeclarableUpload. func (fs *ocfs) AsLengthDeclarableUpload(upload tusd.Upload) tusd.LengthDeclarableUpload { return upload.(*fileUpload) } -// DeclareLength updates the upload length information +// DeclareLength updates the upload length information. func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error { upload.info.Size = length upload.info.SizeIsDeferred = false @@ -493,12 +492,12 @@ func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error // - the storage needs to implement AsConcatableUpload // - the upload needs to implement ConcatUploads -// AsConcatableUpload returns a ConcatableUpload +// AsConcatableUpload returns a ConcatableUpload. func (fs *ocfs) AsConcatableUpload(upload tusd.Upload) tusd.ConcatableUpload { return upload.(*fileUpload) } -// ConcatUploads concatenates multiple uploads +// ConcatUploads concatenates multiple uploads. func (upload *fileUpload) ConcatUploads(ctx context.Context, uploads []tusd.Upload) (err error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { diff --git a/pkg/storage/fs/owncloudsql/filecache/filecache.go b/pkg/storage/fs/owncloudsql/filecache/filecache.go index 7e0c58a1d88..ce757101788 100644 --- a/pkg/storage/fs/owncloudsql/filecache/filecache.go +++ b/pkg/storage/fs/owncloudsql/filecache/filecache.go @@ -31,18 +31,17 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" conversions "github.com/cs3org/reva/internal/http/services/owncloud/ocs/conversions" - "github.com/pkg/errors" "github.com/rs/zerolog/log" ) -// Cache represents a oc10-style file cache +// Cache represents a oc10-style file cache. type Cache struct { driver string db *sql.DB } -// NewMysql returns a new Cache instance connecting to a MySQL database +// NewMysql returns a new Cache instance connecting to a MySQL database. func NewMysql(dsn string) (*Cache, error) { sqldb, err := sql.Open("mysql", dsn) if err != nil { @@ -60,7 +59,7 @@ func NewMysql(dsn string) (*Cache, error) { return New("mysql", sqldb) } -// New returns a new Cache instance connecting to the given sql.DB +// New returns a new Cache instance connecting to the given sql.DB. func New(driver string, sqldb *sql.DB) (*Cache, error) { return &Cache{ driver: driver, @@ -68,7 +67,7 @@ func New(driver string, sqldb *sql.DB) (*Cache, error) { }, nil } -// GetNumericStorageID returns the database id for the given storage +// GetNumericStorageID returns the database id for the given storage. func (c *Cache) GetNumericStorageID(id string) (int, error) { row := c.db.QueryRow("SELECT numeric_id FROM oc_storages WHERE id = ?", id) var nid int @@ -80,7 +79,7 @@ func (c *Cache) GetNumericStorageID(id string) (int, error) { } } -// CreateStorage creates a new storage and returns its numeric id +// CreateStorage creates a new storage and returns its numeric id. func (c *Cache) CreateStorage(id string) (int, error) { tx, err := c.db.Begin() if err != nil { @@ -121,7 +120,7 @@ func (c *Cache) CreateStorage(id string) (int, error) { return int(insertedID), err } -// GetStorageOwner returns the username of the owner of the given storage +// GetStorageOwner returns the username of the owner of the given storage. func (c *Cache) GetStorageOwner(numericID interface{}) (string, error) { numericID, err := toIntID(numericID) if err != nil { @@ -137,7 +136,7 @@ func (c *Cache) GetStorageOwner(numericID interface{}) (string, error) { } } -// GetStorageOwnerByFileID returns the username of the owner of the given entry +// GetStorageOwnerByFileID returns the username of the owner of the given entry. func (c *Cache) GetStorageOwnerByFileID(numericID interface{}) (string, error) { numericID, err := toIntID(numericID) if err != nil { @@ -153,7 +152,7 @@ func (c *Cache) GetStorageOwnerByFileID(numericID interface{}) (string, error) { } } -// File represents an entry of the file cache +// File represents an entry of the file cache. type File struct { ID int Storage int @@ -173,7 +172,7 @@ type File struct { Checksum string } -// TrashItem represents a trash item of the file cache +// TrashItem represents a trash item of the file cache. type TrashItem struct { ID int Name string @@ -182,7 +181,7 @@ type TrashItem struct { Timestamp int } -// Scannable describes the interface providing a Scan method +// Scannable describes the interface providing a Scan method. type Scannable interface { Scan(...interface{}) error } @@ -216,7 +215,7 @@ func (c *Cache) rowToFile(row Scannable) (*File, error) { }, nil } -// Get returns the cache entry for the specified storage/path +// Get returns the cache entry for the specified storage/path. func (c *Cache) Get(s interface{}, p string) (*File, error) { storageID, err := toIntID(s) if err != nil { @@ -237,7 +236,7 @@ func (c *Cache) Get(s interface{}, p string) (*File, error) { return c.rowToFile(row) } -// Path returns the path for the specified entry +// Path returns the path for the specified entry. func (c *Cache) Path(id interface{}) (string, error) { id, err := toIntID(id) if err != nil { @@ -253,7 +252,7 @@ func (c *Cache) Path(id interface{}) (string, error) { return path, nil } -// List returns the list of entries below the given path +// List returns the list of entries below the given path. func (c *Cache) List(storage interface{}, p string) ([]*File, error) { storageID, err := toIntID(storage) if err != nil { @@ -287,7 +286,7 @@ func (c *Cache) List(storage interface{}, p string) ([]*File, error) { return entries, nil } -// Permissions returns the permissions for the specified storage/path +// Permissions returns the permissions for the specified storage/path. func (c *Cache) Permissions(storage interface{}, p string) (*provider.ResourcePermissions, error) { entry, err := c.Get(storage, p) if err != nil { @@ -302,7 +301,7 @@ func (c *Cache) Permissions(storage interface{}, p string) (*provider.ResourcePe return conversions.RoleFromOCSPermissions(perms).CS3ResourcePermissions(), nil } -// InsertOrUpdate creates or updates a cache entry +// InsertOrUpdate creates or updates a cache entry. func (c *Cache) InsertOrUpdate(storage interface{}, data map[string]interface{}, allowEmptyParent bool) (int, error) { tx, err := c.db.Begin() if err != nil { @@ -436,7 +435,7 @@ func (c *Cache) doInsertOrUpdate(tx *sql.Tx, storage interface{}, data map[strin return int(id), nil } -// Copy creates a copy of the specified entry at the target path +// Copy creates a copy of the specified entry at the target path. func (c *Cache) Copy(storage interface{}, sourcePath, targetPath string) (int, error) { storageID, err := toIntID(storage) if err != nil { @@ -469,7 +468,7 @@ func (c *Cache) Copy(storage interface{}, sourcePath, targetPath string) (int, e return c.InsertOrUpdate(storage, data, false) } -// Move moves the specified entry to the target path +// Move moves the specified entry to the target path. func (c *Cache) Move(storage interface{}, sourcePath, targetPath string) error { storageID, err := toIntID(storage) if err != nil { @@ -531,7 +530,7 @@ func (c *Cache) Move(storage interface{}, sourcePath, targetPath string) error { return tx.Commit() } -// Purge removes the specified storage/path from the cache without putting it into the trash +// Purge removes the specified storage/path from the cache without putting it into the trash. func (c *Cache) Purge(storage interface{}, path string) error { storageID, err := toIntID(storage) if err != nil { @@ -543,7 +542,7 @@ func (c *Cache) Purge(storage interface{}, path string) error { return err } -// Delete removes the specified storage/path from the cache +// Delete removes the specified storage/path from the cache. func (c *Cache) Delete(storage interface{}, user, path, trashPath string) error { err := c.Move(storage, path, trashPath) if err != nil { @@ -572,7 +571,7 @@ func (c *Cache) Delete(storage interface{}, user, path, trashPath string) error return nil } -// GetRecycleItem returns the specified recycle item +// GetRecycleItem returns the specified recycle item. func (c *Cache) GetRecycleItem(user, path string, timestamp int) (*TrashItem, error) { row := c.db.QueryRow("SELECT auto_id, id, location FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp) var autoID int @@ -591,7 +590,7 @@ func (c *Cache) GetRecycleItem(user, path string, timestamp int) (*TrashItem, er }, nil } -// EmptyRecycle clears the recycle bin for the given user +// EmptyRecycle clears the recycle bin for the given user. func (c *Cache) EmptyRecycle(user string) error { _, err := c.db.Exec("DELETE FROM oc_files_trash WHERE user = ?", user) if err != nil { @@ -607,13 +606,13 @@ func (c *Cache) EmptyRecycle(user string) error { return err } -// DeleteRecycleItem deletes the specified item from the trash +// DeleteRecycleItem deletes the specified item from the trash. func (c *Cache) DeleteRecycleItem(user, path string, timestamp int) error { _, err := c.db.Exec("DELETE FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp) return err } -// PurgeRecycleItem deletes the specified item from the filecache and the trash +// PurgeRecycleItem deletes the specified item from the filecache and the trash. func (c *Cache) PurgeRecycleItem(user, path string, timestamp int, isVersionFile bool) error { row := c.db.QueryRow("SELECT auto_id, location FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp) var autoID int @@ -645,7 +644,7 @@ func (c *Cache) PurgeRecycleItem(user, path string, timestamp int, isVersionFile return err } -// SetEtag set a new etag for the specified item +// SetEtag set a new etag for the specified item. func (c *Cache) SetEtag(storage interface{}, path, etag string) error { storageID, err := toIntID(storage) if err != nil { diff --git a/pkg/storage/fs/owncloudsql/filecache/filecache_test.go b/pkg/storage/fs/owncloudsql/filecache/filecache_test.go index 4323fe10748..9c282bfb0e0 100644 --- a/pkg/storage/fs/owncloudsql/filecache/filecache_test.go +++ b/pkg/storage/fs/owncloudsql/filecache/filecache_test.go @@ -23,10 +23,8 @@ import ( "os" "strconv" - _ "github.com/mattn/go-sqlite3" - "github.com/cs3org/reva/pkg/storage/fs/owncloudsql/filecache" - + _ "github.com/mattn/go-sqlite3" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -34,24 +32,24 @@ import ( var _ = Describe("Filecache", func() { var ( cache *filecache.Cache - testDbFile *os.File + testDBFile *os.File sqldb *sql.DB ) BeforeEach(func() { var err error - testDbFile, err = os.CreateTemp("", "example") + testDBFile, err = os.CreateTemp("", "example") Expect(err).ToNot(HaveOccurred()) dbData, err := os.ReadFile("test.db") Expect(err).ToNot(HaveOccurred()) - _, err = testDbFile.Write(dbData) + _, err = testDBFile.Write(dbData) Expect(err).ToNot(HaveOccurred()) - err = testDbFile.Close() + err = testDBFile.Close() Expect(err).ToNot(HaveOccurred()) - sqldb, err = sql.Open("sqlite3", testDbFile.Name()) + sqldb, err = sql.Open("sqlite3", testDBFile.Name()) Expect(err).ToNot(HaveOccurred()) cache, err = filecache.New("sqlite3", sqldb) @@ -59,7 +57,7 @@ var _ = Describe("Filecache", func() { }) AfterEach(func() { - os.Remove(testDbFile.Name()) + os.Remove(testDBFile.Name()) }) Describe("GetNumericStorageID", func() { diff --git a/pkg/storage/fs/owncloudsql/owncloudsql.go b/pkg/storage/fs/owncloudsql/owncloudsql.go index ed4d9fc9d78..579669946de 100644 --- a/pkg/storage/fs/owncloudsql/owncloudsql.go +++ b/pkg/storage/fs/owncloudsql/owncloudsql.go @@ -66,7 +66,7 @@ const ( // A non root user can only manipulate the user. namespace, which is what // we will use to store ownCloud specific metadata. To prevent name // collisions with other apps We are going to introduce a sub namespace - // "user.oc." + // "user.oc.". ocPrefix string = "user.oc." mdPrefix string = ocPrefix + "md." // arbitrary metadata @@ -113,11 +113,11 @@ type config struct { UserLayout string `mapstructure:"user_layout"` EnableHome bool `mapstructure:"enable_home"` UserProviderEndpoint string `mapstructure:"userprovidersvc"` - DbUsername string `mapstructure:"dbusername"` - DbPassword string `mapstructure:"dbpassword"` - DbHost string `mapstructure:"dbhost"` - DbPort int `mapstructure:"dbport"` - DbName string `mapstructure:"dbname"` + DBUsername string `mapstructure:"dbusername"` + DBPassword string `mapstructure:"dbpassword"` + DBHost string `mapstructure:"dbhost"` + DBPort int `mapstructure:"dbport"` + DBName string `mapstructure:"dbname"` } func parseConfig(m map[string]interface{}) (*config, error) { @@ -176,7 +176,7 @@ func New(m map[string]interface{}) (storage.FS, error) { Msg("could not create uploadinfo dir") } - dbSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName) + dbSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DBUsername, c.DBPassword, c.DBHost, c.DBPort, c.DBName) filecache, err := filecache.NewMysql(dbSource) if err != nil { return nil, err @@ -202,7 +202,7 @@ func (fs *owncloudsqlfs) Shutdown(ctx context.Context) error { // owncloudsql stores files in the files subfolder // the incoming path starts with /, so we need to insert the files subfolder into the path // and prefix the data directory -// TODO the path handed to a storage provider should not contain the username +// TODO the path handed to a storage provider should not contain the username. func (fs *owncloudsqlfs) toInternalPath(ctx context.Context, sp string) (ip string) { if fs.c.EnableHome { u := ctxpkg.ContextMustGetUser(ctx) @@ -236,7 +236,6 @@ func (fs *owncloudsqlfs) toInternalPath(ctx context.Context, sp string) (ip stri // parts = "", "foo/bar.txt" ip = filepath.Join(fs.c.DataDirectory, layout, "files", segments[1]) } - } return } @@ -244,7 +243,7 @@ func (fs *owncloudsqlfs) toInternalPath(ctx context.Context, sp string) (ip stri // owncloudsql stores versions in the files_versions subfolder // the incoming path starts with /, so we need to insert the files subfolder into the path // and prefix the data directory -// TODO the path handed to a storage provider should not contain the username +// TODO the path handed to a storage provider should not contain the username. func (fs *owncloudsqlfs) getVersionsPath(ctx context.Context, ip string) string { // ip = /path/to/data//files/foo/bar.txt // remove data dir @@ -273,10 +272,9 @@ func (fs *owncloudsqlfs) getVersionsPath(ctx context.Context, ip string) string default: return "" // TODO Must not happen? } - } -// owncloudsql stores trashed items in the files_trashbin subfolder of a users home +// owncloudsql stores trashed items in the files_trashbin subfolder of a users home. func (fs *owncloudsqlfs) getRecyclePath(ctx context.Context) (string, error) { u, ok := ctxpkg.ContextGetUser(ctx) if !ok { @@ -346,7 +344,7 @@ func (fs *owncloudsqlfs) toStoragePath(ctx context.Context, ip string) (sp strin return } -// TODO the owner needs to come from a different place +// TODO the owner needs to come from a different place. func (fs *owncloudsqlfs) getOwner(ip string) string { ip = strings.TrimPrefix(ip, fs.c.DataDirectory) parts := strings.SplitN(ip, "/", 3) @@ -356,7 +354,7 @@ func (fs *owncloudsqlfs) getOwner(ip string) string { return "" } -// TODO cache user lookup +// TODO cache user lookup. func (fs *owncloudsqlfs) getUser(ctx context.Context, usernameOrID string) (id *userpb.User, err error) { u := ctxpkg.ContextMustGetUser(ctx) // check if username matches and id is set @@ -413,7 +411,7 @@ func (fs *owncloudsqlfs) getUser(ctx context.Context, usernameOrID string) (id * return res.User, nil } -// permissionSet returns the permission set for the current user +// permissionSet returns the permission set for the current user. func (fs *owncloudsqlfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions { if owner == nil { return &provider.ResourcePermissions{ @@ -489,7 +487,7 @@ func (fs *owncloudsqlfs) getUserStorage(user string) (int, error) { return id, err } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *owncloudsqlfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { return nil, fmt.Errorf("unimplemented: CreateStorageSpace") } @@ -542,7 +540,7 @@ func (fs *owncloudsqlfs) convertToResourceInfo(ctx context.Context, entry *filec return ri, nil } -// GetPathByID returns the storage relative path for the file id, without the internal namespace +// GetPathByID returns the storage relative path for the file id, without the internal namespace. func (fs *owncloudsqlfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { ip, err := fs.filecache.Path(id.OpaqueId) if err != nil { @@ -566,7 +564,6 @@ func (fs *owncloudsqlfs) GetPathByID(ctx context.Context, id *provider.ResourceI // resolve takes in a request path or request id and converts it to an internal path. func (fs *owncloudsqlfs) resolve(ctx context.Context, ref *provider.Reference) (string, error) { - if ref.GetResourceId() != nil { p, err := fs.filecache.Path(ref.GetResourceId().OpaqueId) if err != nil { @@ -699,7 +696,7 @@ func (fs *owncloudsqlfs) createHomeForUser(ctx context.Context, user string) err return nil } -// If home is enabled, the relative home is always the empty string +// If home is enabled, the relative home is always the empty string. func (fs *owncloudsqlfs) GetHome(ctx context.Context) (string, error) { if !fs.c.EnableHome { return "", errtypes.NotSupported("owncloudsql: get home not supported") @@ -708,7 +705,6 @@ func (fs *owncloudsqlfs) GetHome(ctx context.Context) (string, error) { } func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { - ip, err := fs.resolve(ctx, ref) if err != nil { return err @@ -766,7 +762,7 @@ func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) return fs.propagate(ctx, filepath.Dir(ip)) } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } @@ -1024,22 +1020,22 @@ func (fs *owncloudsqlfs) UnsetArbitraryMetadata(ctx context.Context, ref *provid } } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *owncloudsqlfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *owncloudsqlfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *owncloudsqlfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } @@ -1296,7 +1292,6 @@ func (fs *owncloudsqlfs) ListFolder(ctx context.Context, ref *provider.Reference } func (fs *owncloudsqlfs) listWithNominalHome(ctx context.Context, ip string, mdKeys []string) ([]*provider.ResourceInfo, error) { - // If a user wants to list a folder shared with him the path will already // be wrapped with the files directory path of the share owner. // In that case we don't want to wrap the path again. @@ -1769,7 +1764,6 @@ func (fs *owncloudsqlfs) ListRecycle(ctx context.Context, basePath, key, relativ if ri != nil { items = append(items, ri) } - } return items, nil } @@ -1966,7 +1960,7 @@ func (fs *owncloudsqlfs) ListStorageSpaces(ctx context.Context, filter []*provid return nil, errtypes.NotSupported("list storage spaces") } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *owncloudsqlfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { return nil, errtypes.NotSupported("update storage space") } diff --git a/pkg/storage/fs/owncloudsql/owncloudsql_unix.go b/pkg/storage/fs/owncloudsql/owncloudsql_unix.go old mode 100755 new mode 100644 index 95ef01cab2b..b2edab0177c --- a/pkg/storage/fs/owncloudsql/owncloudsql_unix.go +++ b/pkg/storage/fs/owncloudsql/owncloudsql_unix.go @@ -41,7 +41,7 @@ import ( // - inode (if available), // - device (if available) and // - size. -// errors are logged, but an etag will still be returned +// errors are logged, but an etag will still be returned. func calcEtag(ctx context.Context, fi os.FileInfo) string { log := appctx.GetLogger(ctx) h := md5.New() diff --git a/pkg/storage/fs/owncloudsql/upload.go b/pkg/storage/fs/owncloudsql/upload.go index 3ed523afc2a..d829eac5af1 100644 --- a/pkg/storage/fs/owncloudsql/upload.go +++ b/pkg/storage/fs/owncloudsql/upload.go @@ -88,7 +88,7 @@ func (fs *owncloudsqlfs) Upload(ctx context.Context, ref *provider.Reference, r } // InitiateUpload returns upload ids corresponding to different protocols it supports -// TODO read optional content for small files in this request +// TODO read optional content for small files in this request. func (fs *owncloudsqlfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { ip, err := fs.resolve(ctx, ref) if err != nil { @@ -142,7 +142,6 @@ func (fs *owncloudsqlfs) UseIn(composer *tusd.StoreComposer) { // - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload func (fs *owncloudsqlfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - log := appctx.GetLogger(ctx) log.Debug().Interface("info", info).Msg("owncloudsql: NewUpload") @@ -243,7 +242,7 @@ func (fs *owncloudsqlfs) getUploadPath(ctx context.Context, uploadID string) (st return filepath.Join(fs.c.DataDirectory, layout, "uploads", uploadID), nil } -// GetUpload returns the Upload for the given upload id +// GetUpload returns the Upload for the given upload id. func (fs *owncloudsqlfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { infoPath := filepath.Join(fs.c.UploadInfoDir, id+".info") @@ -310,12 +309,12 @@ type fileUpload struct { ctx context.Context } -// GetInfo returns the FileInfo +// GetInfo returns the FileInfo. func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { return upload.info, nil } -// WriteChunk writes the stream from the reader to the given offset of the upload +// WriteChunk writes the stream from the reader to the given offset of the upload. func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { @@ -341,7 +340,7 @@ func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.R return n, err } -// GetReader returns an io.Reader for the upload +// GetReader returns an io.Reader for the upload. func (upload *fileUpload) GetReader(ctx context.Context) (io.Reader, error) { return os.Open(upload.binPath) } @@ -356,9 +355,8 @@ func (upload *fileUpload) writeInfo() error { return os.WriteFile(upload.infoPath, data, defaultFilePerm) } -// FinishUpload finishes an upload and moves the file to the internal destination +// FinishUpload finishes an upload and moves the file to the internal destination. func (upload *fileUpload) FinishUpload(ctx context.Context) error { - ip := upload.info.Storage["InternalDestination"] // if destination exists @@ -424,12 +422,12 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) error { // - the storage needs to implement AsTerminatableUpload // - the upload needs to implement Terminate -// AsTerminatableUpload returns a TerminatableUpload +// AsTerminatableUpload returns a TerminatableUpload. func (fs *owncloudsqlfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { return upload.(*fileUpload) } -// Terminate terminates the upload +// Terminate terminates the upload. func (upload *fileUpload) Terminate(ctx context.Context) error { if err := os.Remove(upload.infoPath); err != nil { if !os.IsNotExist(err) { @@ -448,12 +446,12 @@ func (upload *fileUpload) Terminate(ctx context.Context) error { // - the storage needs to implement AsLengthDeclarableUpload // - the upload needs to implement DeclareLength -// AsLengthDeclarableUpload returns a LengthDeclarableUpload +// AsLengthDeclarableUpload returns a LengthDeclarableUpload. func (fs *owncloudsqlfs) AsLengthDeclarableUpload(upload tusd.Upload) tusd.LengthDeclarableUpload { return upload.(*fileUpload) } -// DeclareLength updates the upload length information +// DeclareLength updates the upload length information. func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error { upload.info.Size = length upload.info.SizeIsDeferred = false @@ -464,12 +462,12 @@ func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error // - the storage needs to implement AsConcatableUpload // - the upload needs to implement ConcatUploads -// AsConcatableUpload returns a ConcatableUpload +// AsConcatableUpload returns a ConcatableUpload. func (fs *owncloudsqlfs) AsConcatableUpload(upload tusd.Upload) tusd.ConcatableUpload { return upload.(*fileUpload) } -// ConcatUploads concatenates multiple uploads +// ConcatUploads concatenates multiple uploads. func (upload *fileUpload) ConcatUploads(ctx context.Context, uploads []tusd.Upload) (err error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { diff --git a/pkg/storage/fs/s3/s3.go b/pkg/storage/fs/s3/s3.go index 32a90fe4283..2a90367688e 100644 --- a/pkg/storage/fs/s3/s3.go +++ b/pkg/storage/fs/s3/s3.go @@ -142,7 +142,7 @@ type s3FS struct { config *config } -// permissionSet returns the permission set for the current user +// permissionSet returns the permission set for the current user. func (fs *s3FS) permissionSet(ctx context.Context) *provider.ResourcePermissions { // TODO fix permissions for share recipients by traversing reading acls up to the root? cache acls for the parent node and reuse it return &provider.ResourcePermissions{ @@ -243,7 +243,7 @@ func (fs *s3FS) normalizeCommonPrefix(ctx context.Context, p *s3.CommonPrefix) * // GetPathByID returns the path pointed by the file id // In this implementation the file id is that path of the file without the first slash -// thus the file id always points to the filename +// thus the file id always points to the filename. func (fs *s3FS) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { return path.Join("/", strings.TrimPrefix(id.OpaqueId, "fileid-")), nil } @@ -280,22 +280,22 @@ func (fs *s3FS) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Refere return errtypes.NotSupported("s3: operation not supported") } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *s3FS) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *s3FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *s3FS) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *s3FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } @@ -346,7 +346,7 @@ func (fs *s3FS) CreateDir(ctx context.Context, ref *provider.Reference) error { return nil } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *s3FS) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } @@ -408,13 +408,12 @@ func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) error { return nil } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *s3FS) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { return nil, fmt.Errorf("unimplemented: CreateStorageSpace") } func (fs *s3FS) moveObject(ctx context.Context, oldKey string, newKey string) error { - // Copy // TODO double check CopyObject can deal with >5GB files. // Docs say we need to use multipart upload: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html @@ -706,7 +705,7 @@ func (fs *s3FS) ListStorageSpaces(ctx context.Context, filter []*provider.ListSt return nil, errtypes.NotSupported("list storage spaces") } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *s3FS) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { return nil, errtypes.NotSupported("update storage space") } diff --git a/pkg/storage/fs/s3/upload.go b/pkg/storage/fs/s3/upload.go index aa63eead0f7..a38908290e6 100644 --- a/pkg/storage/fs/s3/upload.go +++ b/pkg/storage/fs/s3/upload.go @@ -25,7 +25,7 @@ import ( "github.com/cs3org/reva/pkg/errtypes" ) -// InitiateUpload returns upload ids corresponding to different protocols it supports +// InitiateUpload returns upload ids corresponding to different protocols it supports. func (fs *s3FS) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { return nil, errtypes.NotSupported("op not supported") } diff --git a/pkg/storage/fs/s3ng/blobstore/blobstore.go b/pkg/storage/fs/s3ng/blobstore/blobstore.go index 0599d48f350..a90079502be 100644 --- a/pkg/storage/fs/s3ng/blobstore/blobstore.go +++ b/pkg/storage/fs/s3ng/blobstore/blobstore.go @@ -29,14 +29,14 @@ import ( "github.com/pkg/errors" ) -// Blobstore provides an interface to an s3 compatible blobstore +// Blobstore provides an interface to an s3 compatible blobstore. type Blobstore struct { client *minio.Client bucket string } -// New returns a new Blobstore +// New returns a new Blobstore. func New(endpoint, region, bucket, accessKey, secretKey string) (*Blobstore, error) { u, err := url.Parse(endpoint) if err != nil { @@ -59,7 +59,7 @@ func New(endpoint, region, bucket, accessKey, secretKey string) (*Blobstore, err }, nil } -// Upload stores some data in the blobstore under the given key +// Upload stores some data in the blobstore under the given key. func (bs *Blobstore) Upload(key string, reader io.Reader) error { size := int64(-1) if file, ok := reader.(*os.File); ok { @@ -78,7 +78,7 @@ func (bs *Blobstore) Upload(key string, reader io.Reader) error { return nil } -// Download retrieves a blob from the blobstore for reading +// Download retrieves a blob from the blobstore for reading. func (bs *Blobstore) Download(key string) (io.ReadCloser, error) { reader, err := bs.client.GetObject(context.Background(), bs.bucket, key, minio.GetObjectOptions{}) if err != nil { @@ -87,7 +87,7 @@ func (bs *Blobstore) Download(key string) (io.ReadCloser, error) { return reader, nil } -// Delete deletes a blob from the blobstore +// Delete deletes a blob from the blobstore. func (bs *Blobstore) Delete(key string) error { err := bs.client.RemoveObject(context.Background(), bs.bucket, key, minio.RemoveObjectOptions{}) if err != nil { diff --git a/pkg/storage/fs/s3ng/option.go b/pkg/storage/fs/s3ng/option.go index 877a7d71891..942994ccc1c 100644 --- a/pkg/storage/fs/s3ng/option.go +++ b/pkg/storage/fs/s3ng/option.go @@ -45,7 +45,7 @@ type Options struct { S3SecretKey string `mapstructure:"s3.secret_key"` } -// S3ConfigComplete return true if all required s3 fields are set +// S3ConfigComplete return true if all required s3 fields are set. func (o *Options) S3ConfigComplete() bool { return o.S3Endpoint != "" && o.S3Region != "" && diff --git a/pkg/storage/fs/s3ng/option_test.go b/pkg/storage/fs/s3ng/option_test.go index 05e0cac43bf..da48a1a2ebf 100644 --- a/pkg/storage/fs/s3ng/option_test.go +++ b/pkg/storage/fs/s3ng/option_test.go @@ -19,10 +19,8 @@ package s3ng_test import ( - "github.com/mitchellh/mapstructure" - "github.com/cs3org/reva/pkg/storage/fs/s3ng" - + "github.com/mitchellh/mapstructure" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/fs/s3ng/s3ng.go b/pkg/storage/fs/s3ng/s3ng.go index 30bc250ff70..919cab7b50d 100644 --- a/pkg/storage/fs/s3ng/s3ng.go +++ b/pkg/storage/fs/s3ng/s3ng.go @@ -40,7 +40,7 @@ func New(m map[string]interface{}) (storage.FS, error) { } if !o.S3ConfigComplete() { - return nil, fmt.Errorf("S3 configuration incomplete") + return nil, fmt.Errorf("s3 configuration incomplete") } bs, err := blobstore.New(o.S3Endpoint, o.S3Region, o.S3Bucket, o.S3AccessKey, o.S3SecretKey) diff --git a/pkg/storage/fs/s3ng/s3ng_test.go b/pkg/storage/fs/s3ng/s3ng_test.go index 697006f8bb2..8caec3c707e 100644 --- a/pkg/storage/fs/s3ng/s3ng_test.go +++ b/pkg/storage/fs/s3ng/s3ng_test.go @@ -23,7 +23,6 @@ import ( "github.com/cs3org/reva/pkg/storage/fs/s3ng" "github.com/cs3org/reva/tests/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -59,7 +58,7 @@ var _ = Describe("S3ng", func() { Describe("New", func() { It("fails on missing s3 configuration", func() { _, err := s3ng.New(map[string]interface{}{}) - Expect(err).To(MatchError("S3 configuration incomplete")) + Expect(err).To(MatchError("s3 configuration incomplete")) }) It("works with complete configuration", func() { diff --git a/pkg/storage/migrate/metadata.go b/pkg/storage/migrate/metadata.go index fe56b438ef1..32a89180adb 100644 --- a/pkg/storage/migrate/metadata.go +++ b/pkg/storage/migrate/metadata.go @@ -33,7 +33,7 @@ import ( storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" ) -// metaData representation in the import data +// metaData representation in the import data. type metaData struct { Type string `json:"type"` Path string `json:"path"` @@ -43,9 +43,8 @@ type metaData struct { } // ImportMetadata from a files.jsonl file in exportPath. The files must already be present on the storage -// Will set etag and mtime +// Will set etag and mtime. func ImportMetadata(ctx context.Context, client gateway.GatewayAPIClient, exportPath string, ns string) error { - filesJSONL, err := os.Open(path.Join(exportPath, "files.jsonl")) if err != nil { return err @@ -92,7 +91,6 @@ func ImportMetadata(ctx context.Context, client gateway.GatewayAPIClient, export } else { log.Print("no etag or mtime for : " + fileData.Path) } - } return nil } diff --git a/pkg/storage/migrate/shares.go b/pkg/storage/migrate/shares.go index 74207059bd6..146f3e4f49d 100644 --- a/pkg/storage/migrate/shares.go +++ b/pkg/storage/migrate/shares.go @@ -33,7 +33,7 @@ import ( provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" ) -// share representation in the import metadata +// share representation in the import metadata. type share struct { Path string `json:"path"` ShareType string `json:"shareType"` @@ -48,9 +48,8 @@ type share struct { Token string `json:"token"` } -// ImportShares from a shares.jsonl file in exportPath. The files must already be present on the storage +// ImportShares from a shares.jsonl file in exportPath. The files must already be present on the storage. func ImportShares(ctx context.Context, client gateway.GatewayAPIClient, exportPath string, ns string) error { - sharesJSONL, err := os.Open(path.Join(exportPath, "shares.jsonl")) if err != nil { return err @@ -104,14 +103,14 @@ func shareReq(info *provider.ResourceInfo, share *share) *collaboration.CreateSh } } -// Maps oc10 permissions to roles +// Maps oc10 permissions to roles. var ocPermToRole = map[int]string{ 1: "viewer", 15: "co-owner", 31: "editor", } -// Create resource permission-set from ownCloud permissions int +// Create resource permission-set from ownCloud permissions int. func convertPermissions(ocPermissions int) *provider.ResourcePermissions { perms := &provider.ResourcePermissions{} switch ocPermToRole[ocPermissions] { diff --git a/pkg/storage/registry/loader/loader.go b/pkg/storage/registry/loader/loader.go index 0921739a783..95c63d52ec4 100644 --- a/pkg/storage/registry/loader/loader.go +++ b/pkg/storage/registry/loader/loader.go @@ -21,5 +21,5 @@ package loader import ( // Load core storage broker drivers. _ "github.com/cs3org/reva/pkg/storage/registry/static" - // Add your own here + // Add your own here. ) diff --git a/pkg/storage/registry/static/static.go b/pkg/storage/registry/static/static.go index fc0d2f99c73..a236d909473 100644 --- a/pkg/storage/registry/static/static.go +++ b/pkg/storage/registry/static/static.go @@ -124,7 +124,7 @@ func (b *reg) ListProviders(ctx context.Context) ([]*registrypb.ProviderInfo, er return providers, nil } -// returns the the root path of the first provider in the list. +// returns the root path of the first provider in the list. func (b *reg) GetHome(ctx context.Context) (*registrypb.ProviderInfo, error) { // Assume that HomeProvider is not a regexp if r, ok := b.c.Rules[b.c.HomeProvider]; ok { @@ -173,7 +173,6 @@ func (b *reg) FindProviders(ctx context.Context, ref *provider.Reference) ([]*re fn := path.Clean(ref.GetPath()) if fn != "" { for prefix, rule := range b.c.Rules { - addr := getProviderAddr(ctx, rule) r, err := regexp.Compile("^" + prefix) if err != nil { diff --git a/pkg/storage/registry/static/static_test.go b/pkg/storage/registry/static/static_test.go index d5331dadf97..3e3bbcb244e 100644 --- a/pkg/storage/registry/static/static_test.go +++ b/pkg/storage/registry/static/static_test.go @@ -26,7 +26,6 @@ import ( registrypb "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1" ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/storage/registry/static" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index ebec63a004e..971a52bd81e 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -68,14 +68,14 @@ type FS interface { } // Registry is the interface that storage registries implement -// for discovering storage providers +// for discovering storage providers. type Registry interface { FindProviders(ctx context.Context, ref *provider.Reference) ([]*registry.ProviderInfo, error) ListProviders(ctx context.Context) ([]*registry.ProviderInfo, error) GetHome(ctx context.Context) (*registry.ProviderInfo, error) } -// PathWrapper is the interface to implement for path transformations +// PathWrapper is the interface to implement for path transformations. type PathWrapper interface { Unwrap(ctx context.Context, rp string) (string, error) Wrap(ctx context.Context, rp string) (string, error) diff --git a/pkg/storage/utils/ace/ace.go b/pkg/storage/utils/ace/ace.go index 6db1434ccf3..0617bc71883 100644 --- a/pkg/storage/utils/ace/ace.go +++ b/pkg/storage/utils/ace/ace.go @@ -127,7 +127,7 @@ type ACE struct { label string // l } -// FromGrant creates an ACE from a CS3 grant +// FromGrant creates an ACE from a CS3 grant. func FromGrant(g *provider.Grant) *ACE { e := &ACE{ _type: "A", @@ -143,12 +143,12 @@ func FromGrant(g *provider.Grant) *ACE { return e } -// Principal returns the principal of the ACE, eg. `u:` or `g:` +// Principal returns the principal of the ACE, eg. `u:` or `g:`. func (e *ACE) Principal() string { return e.principal } -// Marshal renders a principal and byte[] that can be used to persist the ACE as an extended attribute +// Marshal renders a principal and byte[] that can be used to persist the ACE as an extended attribute. func (e *ACE) Marshal() (string, []byte) { // first byte will be replaced after converting to byte array val := fmt.Sprintf("_t=%s:f=%s:p=%s", e._type, e.flags, e.permissions) @@ -157,7 +157,7 @@ func (e *ACE) Marshal() (string, []byte) { return e.principal, b } -// Unmarshal parses a principal string and byte[] into an ACE +// Unmarshal parses a principal string and byte[] into an ACE. func Unmarshal(principal string, v []byte) (e *ACE, err error) { // first byte indicates type of value switch v[0] { @@ -182,7 +182,7 @@ func Unmarshal(principal string, v []byte) (e *ACE, err error) { return } -// Grant returns a CS3 grant +// Grant returns a CS3 grant. func (e *ACE) Grant() *provider.Grant { g := &provider.Grant{ Grantee: &provider.Grantee{ @@ -199,7 +199,7 @@ func (e *ACE) Grant() *provider.Grant { return g } -// granteeType returns the CS3 grantee type +// granteeType returns the CS3 grantee type. func (e *ACE) granteeType() provider.GranteeType { if strings.Contains(e.flags, "g") { return provider.GranteeType_GRANTEE_TYPE_GROUP @@ -207,7 +207,7 @@ func (e *ACE) granteeType() provider.GranteeType { return provider.GranteeType_GRANTEE_TYPE_USER } -// grantPermissionSet returns the set of CS3 resource permissions representing the ACE +// grantPermissionSet returns the set of CS3 resource permissions representing the ACE. func (e *ACE) grantPermissionSet() *provider.ResourcePermissions { p := &provider.ResourcePermissions{} // r diff --git a/pkg/storage/utils/ace/ace_test.go b/pkg/storage/utils/ace/ace_test.go index 724cbe1c876..45a689c09ce 100644 --- a/pkg/storage/utils/ace/ace_test.go +++ b/pkg/storage/utils/ace/ace_test.go @@ -25,7 +25,6 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/storage/utils/ace" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/utils/acl/acl.go b/pkg/storage/utils/acl/acl.go index e678aeb8dea..811b559ba0a 100644 --- a/pkg/storage/utils/acl/acl.go +++ b/pkg/storage/utils/acl/acl.go @@ -40,15 +40,15 @@ const ( // ShortTextForm is a sequence of ACL entries separated by commas, and is used for input. ShortTextForm = "," - // TypeUser indicates the qualifier identifies a user + // TypeUser indicates the qualifier identifies a user. TypeUser = "u" - // TypeLightweight indicates the qualifier identifies a lightweight user + // TypeLightweight indicates the qualifier identifies a lightweight user. TypeLightweight = "lw" - // TypeGroup indicates the qualifier identifies a group + // TypeGroup indicates the qualifier identifies a group. TypeGroup = "egroup" ) -// Parse parses an acl string with the given delimiter (LongTextForm or ShortTextForm) +// Parse parses an acl string with the given delimiter (LongTextForm or ShortTextForm). func Parse(acls string, delimiter string) (*ACLs, error) { tokens := strings.Split(acls, delimiter) entries := []*Entry{} @@ -77,7 +77,7 @@ func isComment(line string) bool { return strings.HasPrefix(line, "#") } -// Serialize always serializes to short text form +// Serialize always serializes to short text form. func (m *ACLs) Serialize() string { sysACL := []string{} for _, e := range m.Entries { @@ -86,7 +86,7 @@ func (m *ACLs) Serialize() string { return strings.Join(sysACL, ShortTextForm) } -// DeleteEntry removes an entry uniquely identified by acl type and qualifier +// DeleteEntry removes an entry uniquely identified by acl type and qualifier. func (m *ACLs) DeleteEntry(aclType string, qualifier string) { for i, e := range m.Entries { if e.Qualifier == qualifier && e.Type == aclType { @@ -96,7 +96,7 @@ func (m *ACLs) DeleteEntry(aclType string, qualifier string) { } } -// SetEntry replaces the permissions of an entry with the given set +// SetEntry replaces the permissions of an entry with the given set. func (m *ACLs) SetEntry(aclType string, qualifier string, permissions string) error { if aclType == "" || permissions == "" { return errInvalidACL @@ -111,7 +111,7 @@ func (m *ACLs) SetEntry(aclType string, qualifier string, permissions string) er return nil } -// The Entry of an ACL is represented as three colon separated fields: +// The Entry of an ACL is represented as three colon separated fields:. type Entry struct { // an ACL entry tag type: user, group, mask or other. comments start with # Type string @@ -121,7 +121,7 @@ type Entry struct { Permissions string } -// ParseEntry parses a single ACL +// ParseEntry parses a single ACL. func ParseEntry(singleSysACL string) (*Entry, error) { tokens := strings.Split(singleSysACL, ":") switch len(tokens) { @@ -146,7 +146,7 @@ func ParseEntry(singleSysACL string) (*Entry, error) { return nil, errInvalidACL } -// ParseLWEntry parses a single lightweight ACL +// ParseLWEntry parses a single lightweight ACL. func ParseLWEntry(singleSysACL string) (*Entry, error) { if !strings.HasPrefix(singleSysACL, TypeLightweight+":") { return nil, errInvalidACL @@ -164,7 +164,7 @@ func ParseLWEntry(singleSysACL string) (*Entry, error) { }, nil } -// CitrineSerialize serializes an ACL entry for citrine EOS ACLs +// CitrineSerialize serializes an ACL entry for citrine EOS ACLs. func (a *Entry) CitrineSerialize() string { return fmt.Sprintf("%s:%s=%s", a.Type, a.Qualifier, a.Permissions) } diff --git a/pkg/storage/utils/chunking/chunking.go b/pkg/storage/utils/chunking/chunking.go index 7c3afc217a2..57458c85882 100644 --- a/pkg/storage/utils/chunking/chunking.go +++ b/pkg/storage/utils/chunking/chunking.go @@ -28,13 +28,13 @@ import ( "strings" ) -// IsChunked checks if a given path refers to a chunk or not +// IsChunked checks if a given path refers to a chunk or not. func IsChunked(fn string) (bool, error) { // FIXME: also need to check whether the OC-Chunked header is set return regexp.MatchString(`-chunking-\w+-[0-9]+-[0-9]+$`, fn) } -// ChunkBLOBInfo stores info about a particular chunk +// ChunkBLOBInfo stores info about a particular chunk. type ChunkBLOBInfo struct { Path string TransferID string @@ -43,7 +43,7 @@ type ChunkBLOBInfo struct { } // Not using the resource path in the chunk folder name allows uploading to -// the same folder after a move without having to restart the chunk upload +// the same folder after a move without having to restart the chunk upload. func (c *ChunkBLOBInfo) uploadID() string { return fmt.Sprintf("chunking-%s-%d", c.TransferID, c.TotalChunks) } @@ -186,7 +186,6 @@ func (c *ChunkHandler) saveChunk(path string, r io.ReadCloser) (bool, string, er // we will end up with hundreds of open file descriptors if err = chunk.Close(); err != nil { return false, "", err - } } diff --git a/pkg/storage/utils/decomposedfs/decomposedfs.go b/pkg/storage/utils/decomposedfs/decomposedfs.go index 427a429a74a..0490804e3cd 100644 --- a/pkg/storage/utils/decomposedfs/decomposedfs.go +++ b/pkg/storage/utils/decomposedfs/decomposedfs.go @@ -53,13 +53,13 @@ import ( "github.com/pkg/xattr" ) -// PermissionsChecker defines an interface for checking permissions on a Node +// PermissionsChecker defines an interface for checking permissions on a Node. type PermissionsChecker interface { AssemblePermissions(ctx context.Context, n *node.Node) (ap provider.ResourcePermissions, err error) HasPermission(ctx context.Context, n *node.Node, check func(*provider.ResourcePermissions) bool) (can bool, err error) } -// Tree is used to manage a tree hierarchy +// Tree is used to manage a tree hierarchy. type Tree interface { Setup(owner *userpb.UserId, propagateToRoot bool) error @@ -80,7 +80,7 @@ type Tree interface { Propagate(ctx context.Context, node *node.Node) (err error) } -// Decomposedfs provides the base for decomposed filesystem implementations +// Decomposedfs provides the base for decomposed filesystem implementations. type Decomposedfs struct { lu *Lookup tp Tree @@ -89,7 +89,7 @@ type Decomposedfs struct { chunkHandler *chunking.ChunkHandler } -// NewDefault returns an instance with default components +// NewDefault returns an instance with default components. func NewDefault(m map[string]interface{}, bs tree.Blobstore) (storage.FS, error) { o, err := options.New(m) if err != nil { @@ -107,7 +107,7 @@ func NewDefault(m map[string]interface{}, bs tree.Blobstore) (storage.FS, error) return New(o, lu, p, tp) } -// when enable home is false we want propagation to root if tree size or mtime accounting is enabled +// when enable home is false we want propagation to root if tree size or mtime accounting is enabled. func enablePropagationForRoot(o *options.Options) bool { return (!o.EnableHome && (o.TreeSizeAccounting || o.TreeTimeAccounting)) } @@ -135,7 +135,7 @@ func New(o *options.Options, lu *Lookup, p PermissionsChecker, tp Tree) (storage }, nil } -// Shutdown shuts down the storage +// Shutdown shuts down the storage. func (fs *Decomposedfs) Shutdown(ctx context.Context) error { return nil } @@ -198,7 +198,7 @@ func (fs *Decomposedfs) GetQuota(ctx context.Context, ref *provider.Reference) ( return total, ri.Size, nil } -// CreateHome creates a new home node for the given user +// CreateHome creates a new home node for the given user. func (fs *Decomposedfs) CreateHome(ctx context.Context) (err error) { if !fs.o.EnableHome || fs.o.UserLayout == "" { return errtypes.NotSupported("Decomposedfs: CreateHome() home supported disabled") @@ -259,7 +259,7 @@ func isAlreadyExists(err error) bool { } // GetHome is called to look up the home path for a user -// It is NOT supposed to return the internal path but the external path +// It is NOT supposed to return the internal path but the external path. func (fs *Decomposedfs) GetHome(ctx context.Context) (string, error) { if !fs.o.EnableHome || fs.o.UserLayout == "" { return "", errtypes.NotSupported("Decomposedfs: GetHome() home supported disabled") @@ -269,7 +269,7 @@ func (fs *Decomposedfs) GetHome(ctx context.Context) (string, error) { return filepath.Join(fs.o.Root, layout), nil // TODO use a namespace? } -// GetPathByID returns the fn pointed by the file id, without the internal namespace +// GetPathByID returns the fn pointed by the file id, without the internal namespace. func (fs *Decomposedfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (string, error) { node, err := fs.lu.NodeFromID(ctx, id) if err != nil { @@ -279,7 +279,7 @@ func (fs *Decomposedfs) GetPathByID(ctx context.Context, id *provider.ResourceId return fs.lu.Path(ctx, node) } -// CreateDir creates the specified directory +// CreateDir creates the specified directory. func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) { name := path.Base(ref.Path) if name == "" || name == "." || name == "/" { @@ -299,7 +299,7 @@ func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) } pn, err := n.Parent() if err != nil { - return errors.Wrap(err, "Decomposedfs: error getting parent "+n.ParentID) + return errors.Wrap(err, "decomposedfs: error getting parent "+n.ParentID) } ok, err := fs.p.HasPermission(ctx, pn, func(rp *provider.ResourcePermissions) bool { return rp.CreateContainer @@ -324,7 +324,7 @@ func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) return } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } @@ -335,7 +335,6 @@ func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference) // To mimic the eos end owncloud driver we only allow references as children of the "/Shares" folder // TODO when home support is enabled should the "/Shares" folder still be listed? func (fs *Decomposedfs) CreateReference(ctx context.Context, p string, targetURI *url.URL) (err error) { - p = strings.Trim(p, "/") parts := strings.Split(p, "/") @@ -377,7 +376,7 @@ func (fs *Decomposedfs) CreateReference(ctx context.Context, p string, targetURI return nil } -// Move moves a resource from one reference to another +// Move moves a resource from one reference to another. func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (err error) { var oldNode, newNode *node.Node if oldNode, err = fs.lu.NodeFromResource(ctx, oldRef); err != nil { @@ -410,7 +409,7 @@ func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Refer return fs.tp.Move(ctx, oldNode, newNode) } -// GetMD returns the metadata for the specified resource +// GetMD returns the metadata for the specified resource. func (fs *Decomposedfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string) (ri *provider.ResourceInfo, err error) { var node *node.Node if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -433,7 +432,7 @@ func (fs *Decomposedfs) GetMD(ctx context.Context, ref *provider.Reference, mdKe return node.AsResourceInfo(ctx, &rp, mdKeys, utils.IsRelativeReference(ref)) } -// ListFolder returns a list of resources in the specified folder +// ListFolder returns a list of resources in the specified folder. func (fs *Decomposedfs) ListFolder(ctx context.Context, ref *provider.Reference, mdKeys []string) (finfos []*provider.ResourceInfo, err error) { var n *node.Node if n, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -474,7 +473,7 @@ func (fs *Decomposedfs) ListFolder(ctx context.Context, ref *provider.Reference, return } -// Delete deletes the specified resource +// Delete deletes the specified resource. func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (err error) { var node *node.Node if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -498,11 +497,11 @@ func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (er return fs.tp.Delete(ctx, node) } -// Download returns a reader to the specified resource +// Download returns a reader to the specified resource. func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference) (io.ReadCloser, error) { node, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error resolving ref") + return nil, errors.Wrap(err, "decomposedfs: error resolving ref") } if !node.Exists { @@ -522,27 +521,27 @@ func (fs *Decomposedfs) Download(ctx context.Context, ref *provider.Reference) ( reader, err := fs.tp.ReadBlob(node.BlobID) if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error download blob '"+node.ID+"'") + return nil, errors.Wrap(err, "decomposedfs: error download blob '"+node.ID+"'") } return reader, nil } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *Decomposedfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *Decomposedfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } diff --git a/pkg/storage/utils/decomposedfs/decomposedfs_test.go b/pkg/storage/utils/decomposedfs/decomposedfs_test.go index 0fa7d535c3e..59887c4a3b8 100644 --- a/pkg/storage/utils/decomposedfs/decomposedfs_test.go +++ b/pkg/storage/utils/decomposedfs/decomposedfs_test.go @@ -19,15 +19,13 @@ package decomposedfs_test import ( - "github.com/stretchr/testify/mock" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs" helpers "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/testhelpers" treemocks "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree/mocks" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/stretchr/testify/mock" ) var _ = Describe("Decomposed", func() { diff --git a/pkg/storage/utils/decomposedfs/grants.go b/pkg/storage/utils/decomposedfs/grants.go index 2bcc900bd05..350b0a902fb 100644 --- a/pkg/storage/utils/decomposedfs/grants.go +++ b/pkg/storage/utils/decomposedfs/grants.go @@ -40,7 +40,7 @@ func (fs *Decomposedfs) DenyGrant(ctx context.Context, ref *provider.Reference, return errtypes.NotSupported("decomposedfs: not supported") } -// AddGrant adds a grant to a resource +// AddGrant adds a grant to a resource. func (fs *Decomposedfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) { log := appctx.GetLogger(ctx) log.Debug().Interface("ref", ref).Interface("grant", g).Msg("AddGrant()") @@ -82,7 +82,7 @@ func (fs *Decomposedfs) AddGrant(ctx context.Context, ref *provider.Reference, g return fs.tp.Propagate(ctx, node) } -// ListGrants lists the grants on the specified resource +// ListGrants lists the grants on the specified resource. func (fs *Decomposedfs) ListGrants(ctx context.Context, ref *provider.Reference) (grants []*provider.Grant, err error) { var node *node.Node if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -123,7 +123,7 @@ func (fs *Decomposedfs) ListGrants(ctx context.Context, ref *provider.Reference) return grants, nil } -// RemoveGrant removes a grant from resource +// RemoveGrant removes a grant from resource. func (fs *Decomposedfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) (err error) { var node *node.Node if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -159,13 +159,13 @@ func (fs *Decomposedfs) RemoveGrant(ctx context.Context, ref *provider.Reference return fs.tp.Propagate(ctx, node) } -// UpdateGrant updates a grant on a resource +// UpdateGrant updates a grant on a resource. func (fs *Decomposedfs) UpdateGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { // TODO remove AddGrant or UpdateGrant grant from CS3 api, redundant? tracked in https://github.com/cs3org/cs3apis/issues/92 return fs.AddGrant(ctx, ref, g) } -// extractACEsFromAttrs reads ACEs in the list of attrs from the node +// extractACEsFromAttrs reads ACEs in the list of attrs from the node. func extractACEsFromAttrs(ctx context.Context, fsfn string, attrs []string) (entries []*ace.ACE) { log := appctx.GetLogger(ctx) entries = []*ace.ACE{} diff --git a/pkg/storage/utils/decomposedfs/lookup.go b/pkg/storage/utils/decomposedfs/lookup.go index 975a5b4c624..836816ce59c 100644 --- a/pkg/storage/utils/decomposedfs/lookup.go +++ b/pkg/storage/utils/decomposedfs/lookup.go @@ -35,12 +35,12 @@ import ( "github.com/pkg/xattr" ) -// Lookup implements transformations from filepath to node and back +// Lookup implements transformations from filepath to node and back. type Lookup struct { Options *options.Options } -// NodeFromResource takes in a request path or request id and converts it to a Node +// NodeFromResource takes in a request path or request id and converts it to a Node. func (lu *Lookup) NodeFromResource(ctx context.Context, ref *provider.Reference) (*node.Node, error) { if ref.ResourceId != nil { // check if a storage space reference is used @@ -73,7 +73,7 @@ func (lu *Lookup) NodeFromResource(ctx context.Context, ref *provider.Reference) return nil, fmt.Errorf("invalid reference %+v. at least resource_id or path must be set", ref) } -// NodeFromPath converts a filename into a Node +// NodeFromPath converts a filename into a Node. func (lu *Lookup) NodeFromPath(ctx context.Context, fn string, followReferences bool) (*node.Node, error) { log := appctx.GetLogger(ctx) log.Debug().Interface("fn", fn).Msg("NodeFromPath()") @@ -102,7 +102,7 @@ func (lu *Lookup) NodeFromPath(ctx context.Context, fn string, followReferences return n, nil } -// NodeFromID returns the internal path for the id +// NodeFromID returns the internal path for the id. func (lu *Lookup) NodeFromID(ctx context.Context, id *provider.ResourceId) (n *node.Node, err error) { if id == nil || id.OpaqueId == "" { return nil, fmt.Errorf("invalid resource id %+v", id) @@ -115,7 +115,7 @@ func (lu *Lookup) NodeFromID(ctx context.Context, id *provider.ResourceId) (n *n return n, n.FindStorageSpaceRoot() } -// Path returns the path for node +// Path returns the path for node. func (lu *Lookup) Path(ctx context.Context, n *node.Node) (p string, err error) { var root *node.Node if root, err = lu.HomeOrRootNode(ctx); err != nil { @@ -136,14 +136,14 @@ func (lu *Lookup) Path(ctx context.Context, n *node.Node) (p string, err error) return } -// RootNode returns the root node of the storage +// RootNode returns the root node of the storage. func (lu *Lookup) RootNode(ctx context.Context) (*node.Node, error) { n := node.New("root", "", "", 0, "", nil, lu) n.Exists = true return n, nil } -// HomeNode returns the home node of a user +// HomeNode returns the home node of a user. func (lu *Lookup) HomeNode(ctx context.Context) (node *node.Node, err error) { if !lu.Options.EnableHome { return nil, errtypes.NotSupported("Decomposedfs: home supported disabled") @@ -198,7 +198,7 @@ func (lu *Lookup) WalkPath(ctx context.Context, r *node.Node, p string, followRe } // HomeOrRootNode returns the users home node when home support is enabled. -// it returns the storages root node otherwise +// it returns the storages root node otherwise. func (lu *Lookup) HomeOrRootNode(ctx context.Context) (node *node.Node, err error) { if lu.Options.EnableHome { return lu.HomeNode(ctx) @@ -206,12 +206,12 @@ func (lu *Lookup) HomeOrRootNode(ctx context.Context) (node *node.Node, err erro return lu.RootNode(ctx) } -// InternalRoot returns the internal storage root directory +// InternalRoot returns the internal storage root directory. func (lu *Lookup) InternalRoot() string { return lu.Options.Root } -// InternalPath returns the internal path for a given ID +// InternalPath returns the internal path for a given ID. func (lu *Lookup) InternalPath(id string) string { return filepath.Join(lu.Options.Root, "nodes", id) } @@ -221,7 +221,7 @@ func (lu *Lookup) mustGetUserLayout(ctx context.Context) string { return templates.WithUser(u, lu.Options.UserLayout) } -// ShareFolder returns the internal storage root directory +// ShareFolder returns the internal storage root directory. func (lu *Lookup) ShareFolder() string { return lu.Options.ShareFolder } diff --git a/pkg/storage/utils/decomposedfs/metadata.go b/pkg/storage/utils/decomposedfs/metadata.go index 3324c052927..bce11e447a8 100644 --- a/pkg/storage/utils/decomposedfs/metadata.go +++ b/pkg/storage/utils/decomposedfs/metadata.go @@ -34,11 +34,11 @@ import ( "github.com/pkg/xattr" ) -// SetArbitraryMetadata sets the metadata on a resource +// SetArbitraryMetadata sets the metadata on a resource. func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) (err error) { n, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") + return errors.Wrap(err, "decomposedfs: error resolving ref") } sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() @@ -105,7 +105,7 @@ func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider. for k, v := range md.Metadata { attrName := xattrs.MetadataPrefix + k if err = xattr.Set(nodePath, attrName, []byte(v)); err != nil { - errs = append(errs, errors.Wrap(err, "Decomposedfs: could not set metadata attribute "+attrName+" to "+k)) + errs = append(errs, errors.Wrap(err, "decomposedfs: could not set metadata attribute "+attrName+" to "+k)) } } @@ -122,11 +122,11 @@ func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider. } } -// UnsetArbitraryMetadata unsets the metadata on the given resource +// UnsetArbitraryMetadata unsets the metadata on the given resource. func (fs *Decomposedfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) (err error) { n, err := fs.lu.NodeFromResource(ctx, ref) if err != nil { - return errors.Wrap(err, "Decomposedfs: error resolving ref") + return errors.Wrap(err, "decomposedfs: error resolving ref") } sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() diff --git a/pkg/storage/utils/decomposedfs/node/node.go b/pkg/storage/utils/decomposedfs/node/node.go index d8f867497f8..68bd5f043eb 100644 --- a/pkg/storage/utils/decomposedfs/node/node.go +++ b/pkg/storage/utils/decomposedfs/node/node.go @@ -33,10 +33,6 @@ import ( "syscall" "time" - "github.com/google/uuid" - "github.com/pkg/errors" - "github.com/pkg/xattr" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1" @@ -48,9 +44,12 @@ import ( "github.com/cs3org/reva/pkg/storage/utils/ace" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/xattrs" "github.com/cs3org/reva/pkg/utils" + "github.com/google/uuid" + "github.com/pkg/errors" + "github.com/pkg/xattr" ) -// Define keys and values used in the node metadata +// Define keys and values used in the node metadata. const ( FavoriteKey = "http://owncloud.org/ns/favorite" ShareTypesKey = "http://owncloud.org/ns/share-types" @@ -63,7 +62,7 @@ const ( QuotaUnlimited = "-3" ) -// Node represents a node in the tree and provides methods to get a Parent or Child instance +// Node represents a node in the tree and provides methods to get a Parent or Child instance. type Node struct { ParentID string ID string @@ -77,7 +76,7 @@ type Node struct { lu PathLookup } -// PathLookup defines the interface for the lookup component +// PathLookup defines the interface for the lookup component. type PathLookup interface { RootNode(ctx context.Context) (node *Node, err error) HomeOrRootNode(ctx context.Context) (node *Node, err error) @@ -88,7 +87,7 @@ type PathLookup interface { ShareFolder() string } -// New returns a new instance of Node +// New returns a new instance of Node. func New(id, parentID, name string, blobsize int64, blobID string, owner *userpb.UserId, lu PathLookup) *Node { if blobID == "" { blobID = uuid.New().String() @@ -104,18 +103,18 @@ func New(id, parentID, name string, blobsize int64, blobID string, owner *userpb } } -// ChangeOwner sets the owner of n to newOwner +// ChangeOwner sets the owner of n to newOwner. func (n *Node) ChangeOwner(new *userpb.UserId) (err error) { nodePath := n.InternalPath() n.owner = new if err = xattr.Set(nodePath, xattrs.OwnerIDAttr, []byte(new.OpaqueId)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not reset owner id attribute") + return errors.Wrap(err, "decomposedfs: could not reset owner id attribute") } if err = xattr.Set(nodePath, xattrs.OwnerIDPAttr, []byte(new.Idp)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not reset owner idp attribute") + return errors.Wrap(err, "decomposedfs: could not reset owner idp attribute") } if err = xattr.Set(nodePath, xattrs.OwnerTypeAttr, []byte(utils.UserTypeToString(new.Type))); err != nil { - return errors.Wrap(err, "Decomposedfs: could not reset owner idp attribute") + return errors.Wrap(err, "decomposedfs: could not reset owner idp attribute") } return @@ -126,51 +125,51 @@ func (n *Node) ChangeOwner(new *userpb.UserId) (err error) { func (n *Node) SetMetadata(key string, val string) (err error) { nodePath := n.InternalPath() if err := xattr.Set(nodePath, key, []byte(val)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set parentid attribute") + return errors.Wrap(err, "decomposedfs: could not set parentid attribute") } return nil } -// WriteMetadata writes the Node metadata to disk +// WriteMetadata writes the Node metadata to disk. func (n *Node) WriteMetadata(owner *userpb.UserId) (err error) { nodePath := n.InternalPath() if err = xattr.Set(nodePath, xattrs.ParentidAttr, []byte(n.ParentID)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set parentid attribute") + return errors.Wrap(err, "decomposedfs: could not set parentid attribute") } if err = xattr.Set(nodePath, xattrs.NameAttr, []byte(n.Name)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") + return errors.Wrap(err, "decomposedfs: could not set name attribute") } if err = xattr.Set(nodePath, xattrs.BlobIDAttr, []byte(n.BlobID)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set blobid attribute") + return errors.Wrap(err, "decomposedfs: could not set blobid attribute") } if err = xattr.Set(nodePath, xattrs.BlobsizeAttr, []byte(fmt.Sprintf("%d", n.Blobsize))); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set blobsize attribute") + return errors.Wrap(err, "decomposedfs: could not set blobsize attribute") } if owner == nil { if err = xattr.Set(nodePath, xattrs.OwnerIDAttr, []byte("")); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set empty owner id attribute") + return errors.Wrap(err, "decomposedfs: could not set empty owner id attribute") } if err = xattr.Set(nodePath, xattrs.OwnerIDPAttr, []byte("")); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set empty owner idp attribute") + return errors.Wrap(err, "decomposedfs: could not set empty owner idp attribute") } if err = xattr.Set(nodePath, xattrs.OwnerTypeAttr, []byte("")); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set empty owner type attribute") + return errors.Wrap(err, "decomposedfs: could not set empty owner type attribute") } } else { if err = xattr.Set(nodePath, xattrs.OwnerIDAttr, []byte(owner.OpaqueId)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set owner id attribute") + return errors.Wrap(err, "decomposedfs: could not set owner id attribute") } if err = xattr.Set(nodePath, xattrs.OwnerIDPAttr, []byte(owner.Idp)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set owner idp attribute") + return errors.Wrap(err, "decomposedfs: could not set owner idp attribute") } if err = xattr.Set(nodePath, xattrs.OwnerTypeAttr, []byte(utils.UserTypeToString(owner.Type))); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set owner idp attribute") + return errors.Wrap(err, "decomposedfs: could not set owner idp attribute") } } return } -// ReadNode creates a new instance from an id and checks if it exists +// ReadNode creates a new instance from an id and checks if it exists. func ReadNode(ctx context.Context, lu PathLookup, id string) (n *Node, err error) { n = &Node{ lu: lu, @@ -229,7 +228,7 @@ func ReadNode(ctx context.Context, lu PathLookup, id string) (n *Node, err error return } -// The os error is buried inside the fs.PathError error +// The os error is buried inside the fs.PathError error. func isNotDir(err error) bool { if perr, ok := err.(*fs.PathError); ok { if serr, ok2 := perr.Err.(syscall.Errno); ok2 { @@ -239,7 +238,7 @@ func isNotDir(err error) bool { return false } -// Child returns the child node with the given name +// Child returns the child node with the given name. func (n *Node) Child(ctx context.Context, name string) (*Node, error) { link, err := os.Readlink(filepath.Join(n.InternalPath(), filepath.Join("/", name))) if err != nil { @@ -253,7 +252,7 @@ func (n *Node) Child(ctx context.Context, name string) (*Node, error) { return c, nil // if the file does not exist we return a node that has Exists = false } - return nil, errors.Wrap(err, "Decomposedfs: Wrap: readlink error") + return nil, errors.Wrap(err, "decomposedfs: Wrap: readlink error") } var c *Node @@ -264,16 +263,16 @@ func (n *Node) Child(ctx context.Context, name string) (*Node, error) { } c.SpaceRoot = n.SpaceRoot } else { - return nil, fmt.Errorf("Decomposedfs: expected '../ prefix, got' %+v", link) + return nil, fmt.Errorf("decomposedfs: expected '../ prefix, got' %+v", link) } return c, nil } -// Parent returns the parent node +// Parent returns the parent node. func (n *Node) Parent() (p *Node, err error) { if n.ParentID == "" { - return nil, fmt.Errorf("Decomposedfs: root has no parent") + return nil, fmt.Errorf("decomposedfs: root has no parent") } p = &Node{ lu: n.lu, @@ -305,7 +304,7 @@ func (n *Node) Parent() (p *Node, err error) { } // Owner returns the cached owner id or reads it from the extended attributes -// TODO can be private as only the AsResourceInfo uses it +// TODO can be private as only the AsResourceInfo uses it. func (n *Node) Owner() (*userpb.UserId, error) { if n.owner != nil { return n.owner, nil @@ -360,7 +359,7 @@ func (n *Node) Owner() (*userpb.UserId, error) { } // PermissionSet returns the permission set for the current user -// the parent nodes are not taken into account +// the parent nodes are not taken into account. func (n *Node) PermissionSet(ctx context.Context) provider.ResourcePermissions { u, ok := ctxpkg.ContextGetUser(ctx) if !ok { @@ -377,17 +376,17 @@ func (n *Node) PermissionSet(ctx context.Context) provider.ResourcePermissions { return NoPermissions() } -// InternalPath returns the internal path of the Node +// InternalPath returns the internal path of the Node. func (n *Node) InternalPath() string { return n.lu.InternalPath(n.ID) } -// CalculateEtag returns a hash of fileid + tmtime (or mtime) +// CalculateEtag returns a hash of fileid + tmtime (or mtime). func CalculateEtag(nodeID string, tmTime time.Time) (string, error) { return calculateEtag(nodeID, tmTime) } -// calculateEtag returns a hash of fileid + tmtime (or mtime) +// calculateEtag returns a hash of fileid + tmtime (or mtime). func calculateEtag(nodeID string, tmTime time.Time) (string, error) { h := md5.New() if _, err := io.WriteString(h, nodeID); err != nil { @@ -403,7 +402,7 @@ func calculateEtag(nodeID string, tmTime time.Time) (string, error) { return fmt.Sprintf(`"%x"`, h.Sum(nil)), nil } -// SetMtime sets the mtime and atime of a node +// SetMtime sets the mtime and atime of a node. func (n *Node) SetMtime(ctx context.Context, mtime string) error { sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() if mt, err := parseMTime(mtime); err == nil { @@ -424,7 +423,7 @@ func (n *Node) SetMtime(ctx context.Context, mtime string) error { return nil } -// SetEtag sets the temporary etag of a node if it differs from the current etag +// SetEtag sets the temporary etag of a node if it differs from the current etag. func (n *Node) SetEtag(ctx context.Context, val string) (err error) { sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() nodePath := n.lu.InternalPath(n.ID) @@ -470,7 +469,7 @@ func (n *Node) SetEtag(ctx context.Context, val string) (err error) { // 4. group = g:: // 5. app? = a:: for apps? // obviously this only is secure when the u/s/g/a namespaces are not accessible by users in the filesystem -// public tags can be mapped to extended attributes +// public tags can be mapped to extended attributes. func (n *Node) SetFavorite(uid *userpb.UserId, val string) error { nodePath := n.lu.InternalPath(n.ID) // the favorite flag is specific to the user, so we need to incorporate the userid @@ -478,7 +477,7 @@ func (n *Node) SetFavorite(uid *userpb.UserId, val string) error { return xattr.Set(nodePath, fa, []byte(val)) } -// AsResourceInfo return the node as CS3 ResourceInfo +// AsResourceInfo return the node as CS3 ResourceInfo. func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissions, mdKeys []string, returnBasename bool) (ri *provider.ResourceInfo, err error) { sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() @@ -653,7 +652,6 @@ func (n *Node) AsResourceInfo(ctx context.Context, rp *provider.ResourcePermissi Msg("error retrieving xattr metadata") } } - } } ri.ArbitraryMetadata = &provider.ArbitraryMetadata{ @@ -706,7 +704,7 @@ func readChecksumIntoOpaque(ctx context.Context, nodePath, algo string, ri *prov } } -// quota is always stored on the root node +// quota is always stored on the root node. func readQuotaIntoOpaque(ctx context.Context, nodePath string, ri *provider.ResourceInfo) { v, err := xattr.Get(nodePath, xattrs.QuotaAttr) switch { @@ -738,7 +736,7 @@ func readQuotaIntoOpaque(ctx context.Context, nodePath string, ri *provider.Reso } } -// HasPropagation checks if the propagation attribute exists and is set to "1" +// HasPropagation checks if the propagation attribute exists and is set to "1". func (n *Node) HasPropagation() (propagation bool) { if b, err := xattr.Get(n.lu.InternalPath(n.ID), xattrs.PropagationAttr); err == nil { return string(b) == "1" @@ -746,7 +744,7 @@ func (n *Node) HasPropagation() (propagation bool) { return false } -// GetTMTime reads the tmtime from the extended attributes +// GetTMTime reads the tmtime from the extended attributes. func (n *Node) GetTMTime() (tmTime time.Time, err error) { var b []byte if b, err = xattr.Get(n.lu.InternalPath(n.ID), xattrs.TreeMTimeAttr); err != nil { @@ -755,12 +753,12 @@ func (n *Node) GetTMTime() (tmTime time.Time, err error) { return time.Parse(time.RFC3339Nano, string(b)) } -// SetTMTime writes the tmtime to the extended attributes +// SetTMTime writes the tmtime to the extended attributes. func (n *Node) SetTMTime(t time.Time) (err error) { return xattr.Set(n.lu.InternalPath(n.ID), xattrs.TreeMTimeAttr, []byte(t.UTC().Format(time.RFC3339Nano))) } -// GetTreeSize reads the treesize from the extended attributes +// GetTreeSize reads the treesize from the extended attributes. func (n *Node) GetTreeSize() (treesize uint64, err error) { var b []byte if b, err = xattr.Get(n.InternalPath(), xattrs.TreesizeAttr); err != nil { @@ -769,17 +767,17 @@ func (n *Node) GetTreeSize() (treesize uint64, err error) { return strconv.ParseUint(string(b), 10, 64) } -// SetTreeSize writes the treesize to the extended attributes +// SetTreeSize writes the treesize to the extended attributes. func (n *Node) SetTreeSize(ts uint64) (err error) { return xattr.Set(n.InternalPath(), xattrs.TreesizeAttr, []byte(strconv.FormatUint(ts, 10))) } -// SetChecksum writes the checksum with the given checksum type to the extended attributes +// SetChecksum writes the checksum with the given checksum type to the extended attributes. func (n *Node) SetChecksum(csType string, h hash.Hash) (err error) { return xattr.Set(n.lu.InternalPath(n.ID), xattrs.ChecksumPrefix+csType, h.Sum(nil)) } -// UnsetTempEtag removes the temporary etag attribute +// UnsetTempEtag removes the temporary etag attribute. func (n *Node) UnsetTempEtag() (err error) { if err = xattr.Remove(n.lu.InternalPath(n.ID), xattrs.TmpEtagAttr); err != nil { if e, ok := err.(*xattr.Error); ok && (e.Err.Error() == "no data available" || @@ -791,7 +789,7 @@ func (n *Node) UnsetTempEtag() (err error) { return err } -// ReadUserPermissions will assemble the permissions for the current user on the given node without parent nodes +// ReadUserPermissions will assemble the permissions for the current user on the given node without parent nodes. func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap provider.ResourcePermissions, err error) { // check if the current user is the owner o, err := n.Owner() @@ -872,7 +870,7 @@ func (n *Node) ReadUserPermissions(ctx context.Context, u *userpb.User) (ap prov // ListGrantees lists the grantees of the current node // We don't want to wast time and memory by creating grantee objects. -// The function will return a list of opaque strings that can be used to make a ReadGrant call +// The function will return a list of opaque strings that can be used to make a ReadGrant call. func (n *Node) ListGrantees(ctx context.Context) (grantees []string, err error) { var attrs []string if attrs, err = xattr.List(n.InternalPath()); err != nil { @@ -887,7 +885,7 @@ func (n *Node) ListGrantees(ctx context.Context) (grantees []string, err error) return } -// ReadGrant reads a CS3 grant +// ReadGrant reads a CS3 grant. func (n *Node) ReadGrant(ctx context.Context, grantee string) (g *provider.Grant, err error) { var b []byte if b, err = xattr.Get(n.InternalPath(), grantee); err != nil { @@ -900,7 +898,7 @@ func (n *Node) ReadGrant(ctx context.Context, grantee string) (g *provider.Grant return e.Grant(), nil } -// ReadBlobSizeAttr reads the blobsize from the xattrs +// ReadBlobSizeAttr reads the blobsize from the xattrs. func ReadBlobSizeAttr(path string) (int64, error) { attrBytes, err := xattr.Get(path, xattrs.BlobsizeAttr) if err != nil { @@ -940,7 +938,7 @@ func parseMTime(v string) (t time.Time, err error) { } // FindStorageSpaceRoot calls n.Parent() and climbs the tree -// until it finds the space root node and adds it to the node +// until it finds the space root node and adds it to the node. func (n *Node) FindStorageSpaceRoot() error { var err error // remember the node we ask for and use parent to climb the tree @@ -957,7 +955,7 @@ func (n *Node) FindStorageSpaceRoot() error { return nil } -// IsSpaceRoot checks if the node is a space root +// IsSpaceRoot checks if the node is a space root. func IsSpaceRoot(r *Node) bool { path := r.InternalPath() if spaceNameBytes, err := xattr.Get(path, xattrs.SpaceNameAttr); err == nil { @@ -968,7 +966,7 @@ func IsSpaceRoot(r *Node) bool { return false } -// CheckQuota checks if both disk space and available quota are sufficient +// CheckQuota checks if both disk space and available quota are sufficient. var CheckQuota = func(spaceRoot *Node, fileSize uint64) (quotaSufficient bool, err error) { used, _ := spaceRoot.GetTreeSize() if !enoughDiskSpace(spaceRoot.InternalPath(), fileSize) { diff --git a/pkg/storage/utils/decomposedfs/node/node_test.go b/pkg/storage/utils/decomposedfs/node/node_test.go index aa8926018fe..8ed73b839bb 100644 --- a/pkg/storage/utils/decomposedfs/node/node_test.go +++ b/pkg/storage/utils/decomposedfs/node/node_test.go @@ -24,7 +24,6 @@ import ( userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/node" helpers "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/testhelpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/utils/decomposedfs/node/node_unix.go b/pkg/storage/utils/decomposedfs/node/node_unix.go index 05edf021584..9b73ff2c7bd 100644 --- a/pkg/storage/utils/decomposedfs/node/node_unix.go +++ b/pkg/storage/utils/decomposedfs/node/node_unix.go @@ -23,7 +23,7 @@ package node import "syscall" -// GetAvailableSize stats the filesystem and return the available bytes +// GetAvailableSize stats the filesystem and return the available bytes. func GetAvailableSize(path string) (uint64, error) { stat := syscall.Statfs_t{} err := syscall.Statfs(path, &stat) diff --git a/pkg/storage/utils/decomposedfs/node/permissions.go b/pkg/storage/utils/decomposedfs/node/permissions.go index eca4daea444..7ca86867479 100644 --- a/pkg/storage/utils/decomposedfs/node/permissions.go +++ b/pkg/storage/utils/decomposedfs/node/permissions.go @@ -33,19 +33,19 @@ import ( "github.com/pkg/xattr" ) -// NoPermissions represents an empty set of permissions +// NoPermissions represents an empty set of permissions. func NoPermissions() provider.ResourcePermissions { return provider.ResourcePermissions{} } -// NoOwnerPermissions defines permissions for nodes that don't have an owner set, eg the root node +// NoOwnerPermissions defines permissions for nodes that don't have an owner set, eg the root node. func NoOwnerPermissions() provider.ResourcePermissions { return provider.ResourcePermissions{ Stat: true, } } -// ShareFolderPermissions defines permissions for the shared jail +// ShareFolderPermissions defines permissions for the shared jail. func ShareFolderPermissions() provider.ResourcePermissions { return provider.ResourcePermissions{ // read permissions @@ -58,7 +58,7 @@ func ShareFolderPermissions() provider.ResourcePermissions { } } -// OwnerPermissions defines permissions for nodes owned by the user +// OwnerPermissions defines permissions for nodes owned by the user. func OwnerPermissions() provider.ResourcePermissions { return provider.ResourcePermissions{ // all permissions @@ -83,19 +83,19 @@ func OwnerPermissions() provider.ResourcePermissions { } } -// Permissions implements permission checks +// Permissions implements permission checks. type Permissions struct { lu PathLookup } -// NewPermissions returns a new Permissions instance +// NewPermissions returns a new Permissions instance. func NewPermissions(lu PathLookup) *Permissions { return &Permissions{ lu: lu, } } -// AssemblePermissions will assemble the permissions for the current user on the given node, taking into account all parent nodes +// AssemblePermissions will assemble the permissions for the current user on the given node, taking into account all parent nodes. func (p *Permissions) AssemblePermissions(ctx context.Context, n *Node) (ap provider.ResourcePermissions, err error) { u, ok := ctxpkg.ContextGetUser(ctx) if !ok { @@ -148,7 +148,7 @@ func (p *Permissions) AssemblePermissions(ctx context.Context, n *Node) (ap prov // continue with next segment } if cn, err = cn.Parent(); err != nil { - return ap, errors.Wrap(err, "Decomposedfs: error getting parent "+cn.ParentID) + return ap, errors.Wrap(err, "decomposedfs: error getting parent "+cn.ParentID) } } @@ -179,9 +179,8 @@ func AddPermissions(l *provider.ResourcePermissions, r *provider.ResourcePermiss l.UpdateGrant = l.UpdateGrant || r.UpdateGrant } -// HasPermission call check() for every node up to the root until check returns true +// HasPermission call check() for every node up to the root until check returns true. func (p *Permissions) HasPermission(ctx context.Context, n *Node, check func(*provider.ResourcePermissions) bool) (can bool, err error) { - var u *userv1beta1.User var perms *provider.ResourcePermissions if u, perms = p.getUserAndPermissions(ctx, n); perms != nil { @@ -206,7 +205,6 @@ func (p *Permissions) HasPermission(ctx context.Context, n *Node, check func(*pr var g *provider.Grant // for all segments, starting at the leaf for cn.ID != rn.ID { - var grantees []string if grantees, err = cn.ListGrantees(ctx); err != nil { appctx.GetLogger(ctx).Error().Err(err).Interface("node", cn).Msg("error listing grantees") @@ -249,7 +247,7 @@ func (p *Permissions) HasPermission(ctx context.Context, n *Node, check func(*pr } if cn, err = cn.Parent(); err != nil { - return false, errors.Wrap(err, "Decomposedfs: error getting parent "+cn.ParentID) + return false, errors.Wrap(err, "decomposedfs: error getting parent "+cn.ParentID) } } diff --git a/pkg/storage/utils/decomposedfs/options/options.go b/pkg/storage/utils/decomposedfs/options/options.go index 892b185a22f..ab5eb0c81e8 100644 --- a/pkg/storage/utils/decomposedfs/options/options.go +++ b/pkg/storage/utils/decomposedfs/options/options.go @@ -57,7 +57,7 @@ type Options struct { GatewayAddr string `mapstructure:"gateway_addr"` } -// New returns a new Options instance for the given configuration +// New returns a new Options instance for the given configuration. func New(m map[string]interface{}) (*Options, error) { o := &Options{} if err := mapstructure.Decode(m, o); err != nil { diff --git a/pkg/storage/utils/decomposedfs/options/options_test.go b/pkg/storage/utils/decomposedfs/options/options_test.go index a74825c2b65..b3ed3461811 100644 --- a/pkg/storage/utils/decomposedfs/options/options_test.go +++ b/pkg/storage/utils/decomposedfs/options/options_test.go @@ -20,7 +20,6 @@ package options_test import ( "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/options" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) diff --git a/pkg/storage/utils/decomposedfs/recycle.go b/pkg/storage/utils/decomposedfs/recycle.go index 341974c9e0d..35e816f9d5a 100644 --- a/pkg/storage/utils/decomposedfs/recycle.go +++ b/pkg/storage/utils/decomposedfs/recycle.go @@ -45,7 +45,7 @@ import ( // TODO For an efficient listing of deleted nodes the ocis storages trash folder should have // contain a directory with symlinks to trash files for every userid/"root" -// ListRecycle returns the list of available recycle items +// ListRecycle returns the list of available recycle items. func (fs *Decomposedfs) ListRecycle(ctx context.Context, basePath, key, relativePath string) ([]*provider.RecycleItem, error) { log := appctx.GetLogger(ctx) @@ -257,7 +257,7 @@ func (fs *Decomposedfs) listTrashRoot(ctx context.Context) ([]*provider.RecycleI return items, nil } -// RestoreRecycleItem restores the specified item +// RestoreRecycleItem restores the specified item. func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, basePath, key, relativePath string, restoreRef *provider.Reference) error { if restoreRef == nil { restoreRef = &provider.Reference{} @@ -292,7 +292,7 @@ func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, basePath, key, r return restoreFunc() } -// PurgeRecycleItem purges the specified item +// PurgeRecycleItem purges the specified item. func (fs *Decomposedfs) PurgeRecycleItem(ctx context.Context, basePath, key, relativePath string) error { rn, purgeFunc, err := fs.tp.PurgeRecycleItemFunc(ctx, key, relativePath) if err != nil { @@ -314,7 +314,7 @@ func (fs *Decomposedfs) PurgeRecycleItem(ctx context.Context, basePath, key, rel return purgeFunc() } -// EmptyRecycle empties the trash +// EmptyRecycle empties the trash. func (fs *Decomposedfs) EmptyRecycle(ctx context.Context) error { u, ok := ctxpkg.ContextGetUser(ctx) // TODO what permission should we check? we could check the root node of the user? or the owner permissions on his home root node? diff --git a/pkg/storage/utils/decomposedfs/revisions.go b/pkg/storage/utils/decomposedfs/revisions.go index 09a0d59c5f2..7117e72fa4b 100644 --- a/pkg/storage/utils/decomposedfs/revisions.go +++ b/pkg/storage/utils/decomposedfs/revisions.go @@ -41,7 +41,7 @@ import ( // We can add a background process to move old revisions to a slower storage // and replace the revision file with a symbolic link in the future, if necessary. -// ListRevisions lists the revisions of the given resource +// ListRevisions lists the revisions of the given resource. func (fs *Decomposedfs) ListRevisions(ctx context.Context, ref *provider.Reference) (revisions []*provider.FileVersion, err error) { var n *node.Node if n, err = fs.lu.NodeFromResource(ctx, ref); err != nil { @@ -89,7 +89,7 @@ func (fs *Decomposedfs) ListRevisions(ctx context.Context, ref *provider.Referen return } -// DownloadRevision returns a reader for the specified revision +// DownloadRevision returns a reader for the specified revision. func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (io.ReadCloser, error) { log := appctx.GetLogger(ctx) @@ -129,12 +129,12 @@ func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Refe if os.IsNotExist(err) { return nil, errtypes.NotFound(contentPath) } - return nil, errors.Wrap(err, "Decomposedfs: error opening revision "+revisionKey) + return nil, errors.Wrap(err, "decomposedfs: error opening revision "+revisionKey) } return r, nil } -// RestoreRevision restores the specified revision of the resource +// RestoreRevision restores the specified revision of the resource. func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (err error) { log := appctx.GetLogger(ctx) diff --git a/pkg/storage/utils/decomposedfs/spaces.go b/pkg/storage/utils/decomposedfs/spaces.go index 4bbc05a2fcb..6944904ef04 100644 --- a/pkg/storage/utils/decomposedfs/spaces.go +++ b/pkg/storage/utils/decomposedfs/spaces.go @@ -49,7 +49,7 @@ const ( spaceIDAny = "*" ) -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { // spaces will be located by default in the root of the storage. r, err := fs.lu.RootNode(ctx) @@ -157,7 +157,7 @@ func (fs *Decomposedfs) CreateStorageSpace(ctx context.Context, req *provider.Cr // ListStorageSpaces returns a list of StorageSpaces. // The list can be filtered by space type or space id. // Spaces are persisted with symlinks in /spaces// pointing to ../../nodes/, the root node of the space -// The spaceid is a concatenation of storageid + "!" + nodeid +// The spaceid is a concatenation of storageid + "!" + nodeid. func (fs *Decomposedfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter) ([]*provider.StorageSpace, error) { // TODO check filters @@ -260,10 +260,9 @@ func (fs *Decomposedfs) ListStorageSpaces(ctx context.Context, filter []*provide } return spaces, nil - } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { space := req.StorageSpace diff --git a/pkg/storage/utils/decomposedfs/testhelpers/helpers.go b/pkg/storage/utils/decomposedfs/testhelpers/helpers.go index 2128a75f05a..1cac037cacb 100644 --- a/pkg/storage/utils/decomposedfs/testhelpers/helpers.go +++ b/pkg/storage/utils/decomposedfs/testhelpers/helpers.go @@ -23,11 +23,6 @@ import ( "os" "path/filepath" - "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/xattrs" - "github.com/google/uuid" - "github.com/pkg/xattr" - "github.com/stretchr/testify/mock" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" ruser "github.com/cs3org/reva/pkg/ctx" @@ -38,10 +33,14 @@ import ( "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/options" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree" treemocks "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree/mocks" + "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/xattrs" "github.com/cs3org/reva/tests/helpers" + "github.com/google/uuid" + "github.com/pkg/xattr" + "github.com/stretchr/testify/mock" ) -// TestEnv represents a test environment for unit tests +// TestEnv represents a test environment for unit tests. type TestEnv struct { Root string Fs storage.FS @@ -160,12 +159,12 @@ func NewTestEnv() (*TestEnv, error) { return env, nil } -// Cleanup removes all files from disk +// Cleanup removes all files from disk. func (t *TestEnv) Cleanup() { os.RemoveAll(t.Root) } -// CreateTestDir create a directory and returns a corresponding Node +// CreateTestDir create a directory and returns a corresponding Node. func (t *TestEnv) CreateTestDir(name string) (*node.Node, error) { err := t.Fs.CreateDir(t.Ctx, &providerv1beta1.Reference{Path: name}) if err != nil { @@ -179,7 +178,7 @@ func (t *TestEnv) CreateTestDir(name string) (*node.Node, error) { return n, nil } -// CreateTestFile creates a new file and its metadata and returns a corresponding Node +// CreateTestFile creates a new file and its metadata and returns a corresponding Node. func (t *TestEnv) CreateTestFile(name, blobID string, blobSize int64, parentID string) (*node.Node, error) { // Create file in dir1 file := node.New( diff --git a/pkg/storage/utils/decomposedfs/tree/tree.go b/pkg/storage/utils/decomposedfs/tree/tree.go index 9984480b0e2..0ba6d30d919 100644 --- a/pkg/storage/utils/decomposedfs/tree/tree.go +++ b/pkg/storage/utils/decomposedfs/tree/tree.go @@ -50,14 +50,14 @@ const ( spaceTypeShare = "share" ) -// Blobstore defines an interface for storing blobs in a blobstore +// Blobstore defines an interface for storing blobs in a blobstore. type Blobstore interface { Upload(key string, reader io.Reader) error Download(key string) (io.ReadCloser, error) Delete(key string) error } -// PathLookup defines the interface for the lookup component +// PathLookup defines the interface for the lookup component. type PathLookup interface { NodeFromPath(ctx context.Context, fn string, followReferences bool) (*node.Node, error) NodeFromID(ctx context.Context, id *provider.ResourceId) (n *node.Node, err error) @@ -70,7 +70,7 @@ type PathLookup interface { ShareFolder() string } -// Tree manages a hierarchical tree +// Tree manages a hierarchical tree. type Tree struct { lookup PathLookup blobstore Blobstore @@ -80,10 +80,10 @@ type Tree struct { treeTimeAccounting bool } -// PermissionCheckFunc defined a function used to check resource permissions +// PermissionCheckFunc defined a function used to check resource permissions. type PermissionCheckFunc func(rp *provider.ResourcePermissions) bool -// New returns a new instance of Tree +// New returns a new instance of Tree. func New(root string, tta bool, tsa bool, lu PathLookup, bs Blobstore) *Tree { return &Tree{ lookup: lu, @@ -94,7 +94,7 @@ func New(root string, tta bool, tsa bool, lu PathLookup, bs Blobstore) *Tree { } } -// Setup prepares the tree structure +// Setup prepares the tree structure. func (t *Tree) Setup(owner *userpb.UserId, propagateToRoot bool) error { // create data paths for internal layout dataPaths := []string{ @@ -173,7 +173,7 @@ func (t *Tree) Setup(owner *userpb.UserId, propagateToRoot bool) error { return nil } -// linkSpace creates a new symbolic link for a space with the given type st, and node id +// linkSpace creates a new symbolic link for a space with the given type st, and node id. func (t *Tree) linkSpace(spaceType, spaceID, nodeID string) { spacesPath := filepath.Join(t.root, "spaces", spaceType, spaceID) expectedTarget := "../../nodes/" + nodeID @@ -222,7 +222,7 @@ func isSharedNode(nodePath string) bool { return false } -// GetMD returns the metadata of a node in the tree +// GetMD returns the metadata of a node in the tree. func (t *Tree) GetMD(ctx context.Context, n *node.Node) (os.FileInfo, error) { md, err := os.Stat(n.InternalPath()) if err != nil { @@ -235,9 +235,8 @@ func (t *Tree) GetMD(ctx context.Context, n *node.Node) (os.FileInfo, error) { return md, nil } -// CreateDir creates a new directory entry in the tree +// CreateDir creates a new directory entry in the tree. func (t *Tree) CreateDir(ctx context.Context, n *node.Node) (err error) { - if n.Exists || n.ID != "" { return errtypes.AlreadyExists(n.ID) // path? } @@ -270,13 +269,13 @@ func (t *Tree) CreateDir(ctx context.Context, n *node.Node) (err error) { return t.Propagate(ctx, n) } -// Move replaces the target with the source +// Move replaces the target with the source. func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) (err error) { // if target exists delete it without trashing it if newNode.Exists { // TODO make sure all children are deleted if err := os.RemoveAll(newNode.InternalPath()); err != nil { - return errors.Wrap(err, "Decomposedfs: Move: error deleting target node "+newNode.ID) + return errors.Wrap(err, "decomposedfs: Move: error deleting target node "+newNode.ID) } } @@ -287,7 +286,6 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) // are we just renaming (parent stays the same)? if oldNode.ParentID == newNode.ParentID { - parentPath := t.lookup.InternalPath(oldNode.ParentID) // rename child @@ -296,12 +294,12 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) filepath.Join(parentPath, newNode.Name), ) if err != nil { - return errors.Wrap(err, "Decomposedfs: could not rename child") + return errors.Wrap(err, "decomposedfs: could not rename child") } // update name attribute if err := xattr.Set(tgtPath, xattrs.NameAttr, []byte(newNode.Name)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") + return errors.Wrap(err, "decomposedfs: could not set name attribute") } return t.Propagate(ctx, newNode) @@ -316,15 +314,15 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) filepath.Join(t.lookup.InternalPath(newNode.ParentID), newNode.Name), ) if err != nil { - return errors.Wrap(err, "Decomposedfs: could not move child") + return errors.Wrap(err, "decomposedfs: could not move child") } // update target parentid and name if err := xattr.Set(tgtPath, xattrs.ParentidAttr, []byte(newNode.ParentID)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set parentid attribute") + return errors.Wrap(err, "decomposedfs: could not set parentid attribute") } if err := xattr.Set(tgtPath, xattrs.NameAttr, []byte(newNode.Name)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") + return errors.Wrap(err, "decomposedfs: could not set name attribute") } // TODO inefficient because we might update several nodes twice, only propagate unchanged nodes? @@ -333,16 +331,16 @@ func (t *Tree) Move(ctx context.Context, oldNode *node.Node, newNode *node.Node) err = t.Propagate(ctx, oldNode) if err != nil { - return errors.Wrap(err, "Decomposedfs: Move: could not propagate old node") + return errors.Wrap(err, "decomposedfs: Move: could not propagate old node") } err = t.Propagate(ctx, newNode) if err != nil { - return errors.Wrap(err, "Decomposedfs: Move: could not propagate new node") + return errors.Wrap(err, "decomposedfs: Move: could not propagate new node") } return nil } -// ListFolder lists the content of a folder node +// ListFolder lists the content of a folder node. func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, error) { dir := n.InternalPath() f, err := os.Open(dir) @@ -376,7 +374,7 @@ func (t *Tree) ListFolder(ctx context.Context, n *node.Node) ([]*node.Node, erro return nodes, nil } -// Delete deletes a node in the tree by moving it to the trash +// Delete deletes a node in the tree by moving it to the trash. func (t *Tree) Delete(ctx context.Context, n *node.Node) (err error) { deletingSharedResource := ctx.Value(appctx.DeletingSharedResource) @@ -518,13 +516,13 @@ func (t *Tree) RestoreRecycleItemFunc(ctx context.Context, key, trashPath, resto n.Exists = true // update name attribute if err := xattr.Set(nodePath, xattrs.NameAttr, []byte(n.Name)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") + return errors.Wrap(err, "decomposedfs: could not set name attribute") } // set ParentidAttr to restorePath's node parent id if trashPath != "" { if err := xattr.Set(nodePath, xattrs.ParentidAttr, []byte(n.ParentID)); err != nil { - return errors.Wrap(err, "Decomposedfs: could not set name attribute") + return errors.Wrap(err, "decomposedfs: could not set name attribute") } } @@ -537,7 +535,7 @@ func (t *Tree) RestoreRecycleItemFunc(ctx context.Context, key, trashPath, resto return rn, p, fn, nil } -// PurgeRecycleItemFunc returns a node and a function to purge it from the trash +// PurgeRecycleItemFunc returns a node and a function to purge it from the trash. func (t *Tree) PurgeRecycleItemFunc(ctx context.Context, key string, path string) (*node.Node, func() error, error) { rn, trashItem, deletedNodePath, _, err := t.readRecycleItem(ctx, key, path) if err != nil { @@ -570,7 +568,7 @@ func (t *Tree) PurgeRecycleItemFunc(ctx context.Context, key string, path string return rn, fn, nil } -// Propagate propagates changes to the root of the tree +// Propagate propagates changes to the root of the tree. func (t *Tree) Propagate(ctx context.Context, n *node.Node) (err error) { sublog := appctx.GetLogger(ctx).With().Interface("node", n).Logger() if !t.treeTimeAccounting && !t.treeSizeAccounting { @@ -743,20 +741,19 @@ func calculateTreeSize(ctx context.Context, nodePath string) (uint64, error) { } } return size, err - } -// WriteBlob writes a blob to the blobstore +// WriteBlob writes a blob to the blobstore. func (t *Tree) WriteBlob(key string, reader io.Reader) error { return t.blobstore.Upload(key, reader) } -// ReadBlob reads a blob from the blobstore +// ReadBlob reads a blob from the blobstore. func (t *Tree) ReadBlob(key string) (io.ReadCloser, error) { return t.blobstore.Download(key) } -// DeleteBlob deletes a blob from the blobstore +// DeleteBlob deletes a blob from the blobstore. func (t *Tree) DeleteBlob(key string) error { if key == "" { return fmt.Errorf("could not delete blob, empty key was given") @@ -770,7 +767,7 @@ func (t *Tree) createNode(n *node.Node, owner *userpb.UserId) (err error) { // create a directory node nodePath := n.InternalPath() if err = os.MkdirAll(nodePath, 0700); err != nil { - return errors.Wrap(err, "Decomposedfs: error creating node") + return errors.Wrap(err, "decomposedfs: error creating node") } return n.WriteMetadata(owner) diff --git a/pkg/storage/utils/decomposedfs/tree/tree_test.go b/pkg/storage/utils/decomposedfs/tree/tree_test.go index af2d9873829..14db30efab4 100644 --- a/pkg/storage/utils/decomposedfs/tree/tree_test.go +++ b/pkg/storage/utils/decomposedfs/tree/tree_test.go @@ -26,11 +26,10 @@ import ( helpers "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/testhelpers" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/xattrs" - "github.com/pkg/xattr" - "github.com/stretchr/testify/mock" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/pkg/xattr" + "github.com/stretchr/testify/mock" ) var _ = Describe("Tree", func() { diff --git a/pkg/storage/utils/decomposedfs/upload.go b/pkg/storage/utils/decomposedfs/upload.go index 3fec88244d8..f41572c96ca 100644 --- a/pkg/storage/utils/decomposedfs/upload.go +++ b/pkg/storage/utils/decomposedfs/upload.go @@ -56,7 +56,7 @@ var defaultFilePerm = os.FileMode(0664) func (fs *Decomposedfs) Upload(ctx context.Context, ref *provider.Reference, r io.ReadCloser) (err error) { upload, err := fs.GetUpload(ctx, ref.GetPath()) if err != nil { - return errors.Wrap(err, "Decomposedfs: error retrieving upload") + return errors.Wrap(err, "decomposedfs: error retrieving upload") } uploadInfo := upload.(*fileUpload) @@ -64,7 +64,7 @@ func (fs *Decomposedfs) Upload(ctx context.Context, ref *provider.Reference, r i p := uploadInfo.info.Storage["NodeName"] ok, err := chunking.IsChunked(p) // check chunking v1 if err != nil { - return errors.Wrap(err, "Decomposedfs: error checking path") + return errors.Wrap(err, "decomposedfs: error checking path") } if ok { var assembledFile string @@ -81,7 +81,7 @@ func (fs *Decomposedfs) Upload(ctx context.Context, ref *provider.Reference, r i uploadInfo.info.Storage["NodeName"] = p fd, err := os.Open(assembledFile) if err != nil { - return errors.Wrap(err, "Decomposedfs: error opening assembled file") + return errors.Wrap(err, "decomposedfs: error opening assembled file") } defer fd.Close() defer os.RemoveAll(assembledFile) @@ -89,7 +89,7 @@ func (fs *Decomposedfs) Upload(ctx context.Context, ref *provider.Reference, r i } if _, err := uploadInfo.WriteChunk(ctx, 0, r); err != nil { - return errors.Wrap(err, "Decomposedfs: error writing to binary file") + return errors.Wrap(err, "decomposedfs: error writing to binary file") } return uploadInfo.FinishUpload(ctx) @@ -99,7 +99,6 @@ func (fs *Decomposedfs) Upload(ctx context.Context, ref *provider.Reference, r i // TODO read optional content for small files in this request // TODO InitiateUpload (and Upload) needs a way to receive the expected checksum. Maybe in metadata as 'checksum' => 'sha1 aeosvp45w5xaeoe' = lowercase, space separated? func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - log := appctx.GetLogger(ctx) n, err := fs.lu.NodeFromResource(ctx, ref) @@ -178,9 +177,8 @@ func (fs *Decomposedfs) UseIn(composer *tusd.StoreComposer) { // - the storage needs to implement NewUpload and GetUpload // - the upload needs to implement the tusd.Upload interface: WriteChunk, GetInfo, GetReader and FinishUpload -// NewUpload returns a new tus Upload instance +// NewUpload returns a new tus Upload instance. func (fs *Decomposedfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - log := appctx.GetLogger(ctx) log.Debug().Interface("info", info).Msg("Decomposedfs: NewUpload") @@ -198,7 +196,7 @@ func (fs *Decomposedfs) NewUpload(ctx context.Context, info tusd.FileInfo) (uplo n, err := fs.lookupNode(ctx, filepath.Join(info.MetaData["dir"], info.MetaData["filename"])) if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error wrapping filename") + return nil, errors.Wrap(err, "decomposedfs: error wrapping filename") } log.Debug().Interface("info", info).Interface("node", n).Msg("Decomposedfs: resolved filename") @@ -233,13 +231,13 @@ func (fs *Decomposedfs) NewUpload(ctx context.Context, info tusd.FileInfo) (uplo binPath, err := fs.getUploadPath(ctx, info.ID) if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error resolving upload path") + return nil, errors.Wrap(err, "decomposedfs: error resolving upload path") } usr := ctxpkg.ContextMustGetUser(ctx) owner, err := p.Owner() if err != nil { - return nil, errors.Wrap(err, "Decomposedfs: error determining owner") + return nil, errors.Wrap(err, "decomposedfs: error determining owner") } var spaceRoot string if info.Storage != nil { @@ -298,7 +296,7 @@ func (fs *Decomposedfs) getUploadPath(ctx context.Context, uploadID string) (str return filepath.Join(fs.o.Root, "uploads", uploadID), nil } -// GetUpload returns the Upload for the given upload id +// GetUpload returns the Upload for the given upload id. func (fs *Decomposedfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { infoPath := filepath.Join(fs.o.Root, "uploads", id+".info") @@ -393,12 +391,12 @@ type fileUpload struct { ctx context.Context } -// GetInfo returns the FileInfo +// GetInfo returns the FileInfo. func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { return upload.info, nil } -// WriteChunk writes the stream from the reader to the given offset of the upload +// WriteChunk writes the stream from the reader to the given offset of the upload. func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { @@ -428,7 +426,7 @@ func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.R return n, err } -// GetReader returns an io.Reader for the upload +// GetReader returns an io.Reader for the upload. func (upload *fileUpload) GetReader(ctx context.Context) (io.Reader, error) { return os.Open(upload.binPath) } @@ -442,9 +440,8 @@ func (upload *fileUpload) writeInfo() error { return os.WriteFile(upload.infoPath, data, defaultFilePerm) } -// FinishUpload finishes an upload and moves the file to the internal destination +// FinishUpload finishes an upload and moves the file to the internal destination. func (upload *fileUpload) FinishUpload(ctx context.Context) (err error) { - // ensure cleanup defer upload.discardChunk() @@ -578,7 +575,7 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) (err error) { OpaqueId: upload.info.Storage["OwnerId"], }) if err != nil { - return errors.Wrap(err, "Decomposedfs: could not write metadata") + return errors.Wrap(err, "decomposedfs: could not write metadata") } // link child name to parent if it is new @@ -593,12 +590,12 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) (err error) { Msg("Decomposedfs: child name link has wrong target id, repairing") if err = os.Remove(childNameLink); err != nil { - return errors.Wrap(err, "Decomposedfs: could not remove symlink child entry") + return errors.Wrap(err, "decomposedfs: could not remove symlink child entry") } } if os.IsNotExist(err) || link != "../"+n.ID { if err = os.Symlink("../"+n.ID, childNameLink); err != nil { - return errors.Wrap(err, "Decomposedfs: could not symlink child entry") + return errors.Wrap(err, "decomposedfs: could not symlink child entry") } } @@ -659,12 +656,12 @@ func (upload *fileUpload) discardChunk() { // - the storage needs to implement AsTerminatableUpload // - the upload needs to implement Terminate -// AsTerminatableUpload returns a TerminatableUpload +// AsTerminatableUpload returns a TerminatableUpload. func (fs *Decomposedfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { return upload.(*fileUpload) } -// Terminate terminates the upload +// Terminate terminates the upload. func (upload *fileUpload) Terminate(ctx context.Context) error { if err := os.Remove(upload.infoPath); err != nil { if !os.IsNotExist(err) { @@ -683,12 +680,12 @@ func (upload *fileUpload) Terminate(ctx context.Context) error { // - the storage needs to implement AsLengthDeclarableUpload // - the upload needs to implement DeclareLength -// AsLengthDeclarableUpload returns a LengthDeclarableUpload +// AsLengthDeclarableUpload returns a LengthDeclarableUpload. func (fs *Decomposedfs) AsLengthDeclarableUpload(upload tusd.Upload) tusd.LengthDeclarableUpload { return upload.(*fileUpload) } -// DeclareLength updates the upload length information +// DeclareLength updates the upload length information. func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error { upload.info.Size = length upload.info.SizeIsDeferred = false @@ -699,12 +696,12 @@ func (upload *fileUpload) DeclareLength(ctx context.Context, length int64) error // - the storage needs to implement AsConcatableUpload // - the upload needs to implement ConcatUploads -// AsConcatableUpload returns a ConcatableUpload +// AsConcatableUpload returns a ConcatableUpload. func (fs *Decomposedfs) AsConcatableUpload(upload tusd.Upload) tusd.ConcatableUpload { return upload.(*fileUpload) } -// ConcatUploads concatenates multiple uploads +// ConcatUploads concatenates multiple uploads. func (upload *fileUpload) ConcatUploads(ctx context.Context, uploads []tusd.Upload) (err error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { diff --git a/pkg/storage/utils/decomposedfs/upload_test.go b/pkg/storage/utils/decomposedfs/upload_test.go index 1ae39d20cde..039be0e1836 100644 --- a/pkg/storage/utils/decomposedfs/upload_test.go +++ b/pkg/storage/utils/decomposedfs/upload_test.go @@ -38,11 +38,10 @@ import ( treemocks "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/tree/mocks" "github.com/cs3org/reva/pkg/storage/utils/decomposedfs/xattrs" "github.com/cs3org/reva/tests/helpers" - "github.com/pkg/xattr" - "github.com/stretchr/testify/mock" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/pkg/xattr" + "github.com/stretchr/testify/mock" ) var _ = Describe("File uploads", func() { diff --git a/pkg/storage/utils/decomposedfs/xattrs/xattrs.go b/pkg/storage/utils/decomposedfs/xattrs/xattrs.go index 6a8dcc5ef32..40dca8f022d 100644 --- a/pkg/storage/utils/decomposedfs/xattrs/xattrs.go +++ b/pkg/storage/utils/decomposedfs/xattrs/xattrs.go @@ -31,7 +31,7 @@ import ( // A non root user can only manipulate the user. namespace, which is what // we will use to store ownCloud specific metadata. To prevent name // collisions with other apps We are going to introduce a sub namespace -// "user.ocis." +// "user.ocis.". const ( OcisPrefix string = "user.ocis." ParentidAttr string = OcisPrefix + "parentid" @@ -39,20 +39,20 @@ const ( OwnerIDPAttr string = OcisPrefix + "owner.idp" OwnerTypeAttr string = OcisPrefix + "owner.type" // the base name of the node - // updated when the file is renamed or moved + // updated when the file is renamed or moved. NameAttr string = OcisPrefix + "name" BlobIDAttr string = OcisPrefix + "blobid" BlobsizeAttr string = OcisPrefix + "blobsize" - // grantPrefix is the prefix for sharing related extended attributes + // grantPrefix is the prefix for sharing related extended attributes. GrantPrefix string = OcisPrefix + "grant." MetadataPrefix string = OcisPrefix + "md." - // favorite flag, per user + // favorite flag, per user. FavPrefix string = OcisPrefix + "fav." - // a temporary etag for a folder that is removed when the mtime propagation happens + // a temporary etag for a folder that is removed when the mtime propagation happens. TmpEtagAttr string = OcisPrefix + "tmp.etag" ReferenceAttr string = OcisPrefix + "cs3.ref" // arbitrary metadata ChecksumPrefix string = OcisPrefix + "cs." // followed by the algorithm, eg. ocis.cs.sha1 @@ -66,16 +66,16 @@ const ( // the tree modification time of the tree below this node, // propagated when synctime_accounting is true and // user.ocis.propagation=1 is set - // stored as a readable time.RFC3339Nano + // stored as a readable time.RFC3339Nano. TreeMTimeAttr string = OcisPrefix + "tmtime" // the size of the tree below this node, // propagated when treesize_accounting is true and // user.ocis.propagation=1 is set - // stored as uint64, little endian + // stored as uint64, little endian. TreesizeAttr string = OcisPrefix + "treesize" - // the quota for the storage space / tree, regardless who accesses it + // the quota for the storage space / tree, regardless who accesses it. QuotaAttr string = OcisPrefix + "quota" // the name given to a storage space. It should not contain any semantics as its only purpose is to be read. @@ -86,7 +86,7 @@ const ( ) // ReferenceFromAttr returns a CS3 reference from xattr of a node. -// Supported formats are: "cs3:storageid/nodeid" +// Supported formats are: "cs3:storageid/nodeid". func ReferenceFromAttr(b []byte) (*provider.Reference, error) { return refFromCS3(b) } diff --git a/pkg/storage/utils/downloader/downloader.go b/pkg/storage/utils/downloader/downloader.go index b0040329828..a7c577333b8 100644 --- a/pkg/storage/utils/downloader/downloader.go +++ b/pkg/storage/utils/downloader/downloader.go @@ -33,7 +33,7 @@ import ( ) // Downloader is the interface implemented by the objects that are able to -// download a path into a destination Writer +// download a path into a destination Writer. type Downloader interface { Download(context.Context, string, io.Writer) error } @@ -43,7 +43,7 @@ type revaDownloader struct { httpClient *http.Client } -// NewDownloader creates a Downloader from the reva gateway +// NewDownloader creates a Downloader from the reva gateway. func NewDownloader(gtw gateway.GatewayAPIClient, options ...rhttp.Option) Downloader { return &revaDownloader{ gtw: gtw, @@ -60,7 +60,7 @@ func getDownloadProtocol(protocols []*gateway.FileDownloadProtocol, prot string) return nil, errtypes.InternalError(fmt.Sprintf("protocol %s not supported for downloading", prot)) } -// Download downloads a resource given the path to the dst Writer +// Download downloads a resource given the path to the dst Writer. func (r *revaDownloader) Download(ctx context.Context, path string, dst io.Writer) error { downResp, err := r.gtw.InitiateFileDownload(ctx, &provider.InitiateFileDownloadRequest{ Ref: &provider.Reference{ diff --git a/pkg/storage/utils/downloader/mock/downloader_mock.go b/pkg/storage/utils/downloader/mock/downloader_mock.go index 4930dbebd1c..ed8404e5a20 100644 --- a/pkg/storage/utils/downloader/mock/downloader_mock.go +++ b/pkg/storage/utils/downloader/mock/downloader_mock.go @@ -30,12 +30,12 @@ import ( type mockDownloader struct{} // NewDownloader creates a mock downloader that implements the Downloader interface -// supposed to be used for testing +// supposed to be used for testing. func NewDownloader() downloader.Downloader { return &mockDownloader{} } -// Download copies the content of a local file into the dst Writer +// Download copies the content of a local file into the dst Writer. func (m *mockDownloader) Download(ctx context.Context, path string, dst io.Writer) error { f, err := os.Open(path) if err != nil { diff --git a/pkg/storage/utils/eosfs/eosfs.go b/pkg/storage/utils/eosfs/eosfs.go index e66e6a7b363..9f09b11d824 100644 --- a/pkg/storage/utils/eosfs/eosfs.go +++ b/pkg/storage/utils/eosfs/eosfs.go @@ -20,6 +20,7 @@ package eosfs import ( "context" + b64 "encoding/base64" "encoding/json" "fmt" "io" @@ -33,8 +34,6 @@ import ( "strings" "time" - b64 "encoding/base64" - "github.com/ReneKroon/ttlcache/v2" "github.com/bluele/gcache" grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1" @@ -74,13 +73,13 @@ const ( UserAttr ) -// LockPayloadKey is the key in the xattr for lock payload +// LockPayloadKey is the key in the xattr for lock payload. const LockPayloadKey = "reva.lock.payload" -// LockExpirationKey is the key in the xattr for lock expiration +// LockExpirationKey is the key in the xattr for lock expiration. const LockExpirationKey = "reva.lock.expiration" -// LockTypeKey is the key in the xattr for lock payload +// LockTypeKey is the key in the xattr for lock payload. const LockTypeKey = "reva.lock.type" var hiddenReg = regexp.MustCompile(`\.sys\..#.`) @@ -161,7 +160,7 @@ type eosfs struct { tokenCache gcache.Cache } -// NewEOSFS returns a storage.FS interface implementation that connects to an EOS instance +// NewEOSFS returns a storage.FS interface implementation that connects to an EOS instance. func NewEOSFS(c *Config) (storage.FS, error) { c.init() @@ -543,7 +542,6 @@ func (fs *eosfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Referen if err != nil { return errors.Wrap(err, "eosfs: error setting xattr in eos driver") } - } return nil } @@ -572,7 +570,6 @@ func (fs *eosfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Refer if err != nil { return errors.Wrap(err, "eosfs: error unsetting xattr in eos driver") } - } return nil } @@ -628,7 +625,6 @@ func (fs *eosfs) getLockContent(ctx context.Context, auth eosclient.Authorizatio l.Expiration = expiration return l, nil - } func (fs *eosfs) removeLockAttrs(ctx context.Context, auth eosclient.Authorization, path string) error { @@ -696,7 +692,7 @@ func (fs *eosfs) getLock(ctx context.Context, auth eosclient.Authorization, user return l, nil } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *eosfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { path, err := fs.resolve(ctx, ref) if err != nil { @@ -759,7 +755,7 @@ func (fs *eosfs) setLock(ctx context.Context, auth eosclient.Authorization, lock return nil } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) error { if l.Type == provider.LockType_LOCK_TYPE_SHARED { return errtypes.NotSupported("shared lock not yet implemented") @@ -871,7 +867,7 @@ func encodeLock(l *provider.Lock) (string, error) { return b64.StdEncoding.EncodeToString(data), nil } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *eosfs) RefreshLock(ctx context.Context, ref *provider.Reference, newLock *provider.Lock, existingLockID string) error { if newLock.Type == provider.LockType_LOCK_TYPE_SHARED { return errtypes.NotSupported("shared lock not yet implemented") @@ -938,7 +934,7 @@ func sameHolder(l1, l2 *provider.Lock) bool { return same } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { if lock.Type == provider.LockType_LOCK_TYPE_SHARED { return errtypes.NotSupported("shared lock not yet implemented") @@ -1029,7 +1025,6 @@ func (fs *eosfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provi return errors.Wrap(err, "eosfs: error adding acl") } return nil - } func (fs *eosfs) DenyGrant(ctx context.Context, ref *provider.Reference, g *provider.Grantee) error { @@ -1404,7 +1399,7 @@ func (fs *eosfs) listShareFolderRoot(ctx context.Context, p string) (finfos []*p return finfos, nil } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *eosfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { return nil, fmt.Errorf("unimplemented: CreateStorageSpace") } @@ -1637,7 +1632,7 @@ func (fs *eosfs) CreateDir(ctx context.Context, ref *provider.Reference) error { return fs.c.CreateDir(ctx, auth, fn) } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *eosfs) TouchFile(ctx context.Context, ref *provider.Reference) error { log := appctx.GetLogger(ctx) @@ -1979,7 +1974,6 @@ func (fs *eosfs) ListRecycle(ctx context.Context, basePath, key, relativePath st if hiddenReg.MatchString(base) { continue } - } if recycleItem, err := fs.convertToRecycleItem(ctx, entry); err == nil { recycleEntries = append(recycleEntries, recycleItem) @@ -2026,7 +2020,7 @@ func (fs *eosfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListS return nil, errtypes.NotSupported("list storage spaces") } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *eosfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { return nil, errtypes.NotSupported("update storage space") } @@ -2083,7 +2077,7 @@ func (fs *eosfs) convertToFileReference(ctx context.Context, eosFileInfo *eoscli return info, nil } -// permissionSet returns the permission set for the current user +// permissionSet returns the permission set for the current user. func (fs *eosfs) permissionSet(ctx context.Context, eosFileInfo *eosclient.FileInfo, owner *userpb.UserId) *provider.ResourcePermissions { u, ok := ctxpkg.ContextGetUser(ctx) if !ok || u.Id == nil { diff --git a/pkg/storage/utils/etag/etag.go b/pkg/storage/utils/etag/etag.go index eaa8662503d..4a15426de9d 100644 --- a/pkg/storage/utils/etag/etag.go +++ b/pkg/storage/utils/etag/etag.go @@ -49,7 +49,7 @@ var ( // clients such as S3 expect these to follow the specified format. // GenerateEtagFromResources creates a unique etag for the root folder deriving -// information from its multiple children +// information from its multiple children. func GenerateEtagFromResources(root *provider.ResourceInfo, children []*provider.ResourceInfo) string { if root != nil { if params := getEtagParams(eosMtimeEtag, root.Etag); len(params) > 0 { diff --git a/pkg/storage/utils/grants/grants.go b/pkg/storage/utils/grants/grants.go index f7185ba8de5..9d0a77d3e32 100644 --- a/pkg/storage/utils/grants/grants.go +++ b/pkg/storage/utils/grants/grants.go @@ -109,7 +109,7 @@ func GetGrantPermissionSet(perm string) *provider.ResourcePermissions { return &rp } -// GetACLType returns a char representation of the type of grantee +// GetACLType returns a char representation of the type of grantee. func GetACLType(gt provider.GranteeType) (string, error) { switch gt { case provider.GranteeType_GRANTEE_TYPE_USER: @@ -121,7 +121,7 @@ func GetACLType(gt provider.GranteeType) (string, error) { } } -// GetGranteeType returns the grantee type from a char +// GetGranteeType returns the grantee type from a char. func GetGranteeType(aclType string) provider.GranteeType { switch aclType { case acl.TypeUser, acl.TypeLightweight: @@ -133,12 +133,12 @@ func GetGranteeType(aclType string) provider.GranteeType { } } -// PermissionsEqual returns true if the permissions are equal +// PermissionsEqual returns true if the permissions are equal. func PermissionsEqual(p1, p2 *provider.ResourcePermissions) bool { return p1 != nil && p2 != nil && cmp.Equal(*p1, *p2) } -// GranteeEqual returns true if the grantee are equal +// GranteeEqual returns true if the grantee are equal. func GranteeEqual(g1, g2 *provider.Grantee) bool { return g1 != nil && g2 != nil && cmp.Equal(*g1, *g2) } diff --git a/pkg/storage/utils/localfs/db.go b/pkg/storage/utils/localfs/db.go index 15b0b6ff2f7..119520fc542 100644 --- a/pkg/storage/utils/localfs/db.go +++ b/pkg/storage/utils/localfs/db.go @@ -23,10 +23,9 @@ import ( "database/sql" "path" - "github.com/pkg/errors" - - // Provides sqlite drivers + // Provides sqlite drivers. _ "github.com/mattn/go-sqlite3" + "github.com/pkg/errors" ) func initializeDB(root, dbName string) (*sql.DB, error) { diff --git a/pkg/storage/utils/localfs/localfs.go b/pkg/storage/utils/localfs/localfs.go index a0b9162058e..51db73aef39 100644 --- a/pkg/storage/utils/localfs/localfs.go +++ b/pkg/storage/utils/localfs/localfs.go @@ -89,7 +89,6 @@ func (c *Config) init() { c.References = path.Join(c.Shadow, "references") c.RecycleBin = path.Join(c.Shadow, "recycle_bin") c.Versions = path.Join(c.Shadow, "versions") - } type localfs struct { @@ -271,7 +270,7 @@ func (fs *localfs) isShareFolderChild(ctx context.Context, p string) bool { return len(vals) > 1 && vals[1] != "" } -// permissionSet returns the permission set for the current user +// permissionSet returns the permission set for the current user. func (fs *localfs) permissionSet(ctx context.Context, owner *userpb.UserId) *provider.ResourcePermissions { u, ok := ctxpkg.ContextGetUser(ctx) if !ok { @@ -422,7 +421,7 @@ func (fs *localfs) retrieveArbitraryMetadata(ctx context.Context, fn string, mdK } // GetPathByID returns the path pointed by the file id -// In this implementation the file id is in the form `fileid-url_encoded_path` +// In this implementation the file id is in the form `fileid-url_encoded_path`. func (fs *localfs) GetPathByID(ctx context.Context, ref *provider.ResourceId) (string, error) { var layout string if !fs.conf.DisableHome { @@ -505,7 +504,6 @@ func (fs *localfs) ListGrants(ctx context.Context, ref *provider.Reference) ([]* }) } return grantList, nil - } func (fs *localfs) RemoveGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error { @@ -564,13 +562,12 @@ func (fs *localfs) CreateReference(ctx context.Context, path string, targetURI * return fs.propagate(ctx, fn) } -// CreateStorageSpace creates a storage space +// CreateStorageSpace creates a storage space. func (fs *localfs) CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error) { return nil, fmt.Errorf("unimplemented: CreateStorageSpace") } func (fs *localfs) SetArbitraryMetadata(ctx context.Context, ref *provider.Reference, md *provider.ArbitraryMetadata) error { - np, err := fs.resolve(ctx, ref) if err != nil { return errors.Wrap(err, "localfs: error resolving ref") @@ -657,7 +654,6 @@ func parseMTime(v string) (t time.Time, err error) { } func (fs *localfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference, keys []string) error { - np, err := fs.resolve(ctx, ref) if err != nil { return errors.Wrap(err, "localfs: error resolving ref") @@ -711,22 +707,22 @@ func (fs *localfs) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Ref return fs.propagate(ctx, np) } -// GetLock returns an existing lock on the given reference +// GetLock returns an existing lock on the given reference. func (fs *localfs) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) { return nil, errtypes.NotSupported("unimplemented") } -// SetLock puts a lock on the given reference +// SetLock puts a lock on the given reference. func (fs *localfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } -// RefreshLock refreshes an existing lock on the given reference +// RefreshLock refreshes an existing lock on the given reference. func (fs *localfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error { return errtypes.NotSupported("unimplemented") } -// Unlock removes an existing lock from the given reference +// Unlock removes an existing lock from the given reference. func (fs *localfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error { return errtypes.NotSupported("unimplemented") } @@ -777,7 +773,6 @@ func (fs *localfs) createHomeInternal(ctx context.Context, fn string) error { } func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) error { - fn, err := fs.resolve(ctx, ref) if err != nil { return nil @@ -802,7 +797,7 @@ func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) error return fs.propagate(ctx, path.Dir(fn)) } -// TouchFile as defined in the storage.FS interface +// TouchFile as defined in the storage.FS interface. func (fs *localfs) TouchFile(ctx context.Context, ref *provider.Reference) error { return fmt.Errorf("unimplemented: TouchFile") } @@ -882,7 +877,6 @@ func (fs *localfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) } func (fs *localfs) moveReferences(ctx context.Context, oldName, newName string) error { - if fs.isShareFolderRoot(ctx, oldName) || fs.isShareFolderRoot(ctx, newName) { return errtypes.PermissionDenied("localfs: cannot move/rename the virtual share folder") } @@ -941,7 +935,6 @@ func (fs *localfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys [] } func (fs *localfs) getMDShareFolder(ctx context.Context, p string, mdKeys []string) (*provider.ResourceInfo, error) { - fn := fs.wrapReferences(ctx, p) md, err := os.Stat(fn) if err != nil { @@ -990,7 +983,6 @@ func (fs *localfs) ListFolder(ctx context.Context, ref *provider.Reference, mdKe } func (fs *localfs) listFolder(ctx context.Context, fn string, mdKeys []string) ([]*provider.ResourceInfo, error) { - fn = fs.wrap(ctx, fn) entries, err := os.ReadDir(fn) @@ -1021,7 +1013,6 @@ func (fs *localfs) listFolder(ctx context.Context, fn string, mdKeys []string) ( } func (fs *localfs) listShareFolderRoot(ctx context.Context, home string, mdKeys []string) ([]*provider.ResourceInfo, error) { - fn := fs.wrapReferences(ctx, home) entries, err := os.ReadDir(fn) @@ -1078,7 +1069,6 @@ func (fs *localfs) Download(ctx context.Context, ref *provider.Reference) (io.Re } func (fs *localfs) archiveRevision(ctx context.Context, np string) error { - versionsDir := fs.wrapVersions(ctx, fs.unwrap(ctx, np)) if err := os.MkdirAll(versionsDir, 0700); err != nil { return errors.Wrap(err, "localfs: error creating file versions dir "+versionsDir) @@ -1248,7 +1238,6 @@ func (fs *localfs) convertToRecycleItem(ctx context.Context, rp string, md os.Fi } func (fs *localfs) ListRecycle(ctx context.Context, basePath, key, relativePath string) ([]*provider.RecycleItem, error) { - rp := fs.wrapRecycleBin(ctx, "/") entries, err := os.ReadDir(rp) @@ -1274,7 +1263,6 @@ func (fs *localfs) ListRecycle(ctx context.Context, basePath, key, relativePath } func (fs *localfs) RestoreRecycleItem(ctx context.Context, basePath, key, relativePath string, restoreRef *provider.Reference) error { - suffix := path.Ext(key) if len(suffix) == 0 || !strings.HasPrefix(suffix, ".d") { return errors.New("localfs: invalid trash item suffix") @@ -1323,13 +1311,12 @@ func (fs *localfs) ListStorageSpaces(ctx context.Context, filter []*provider.Lis return nil, errtypes.NotSupported("list storage spaces") } -// UpdateStorageSpace updates a storage space +// UpdateStorageSpace updates a storage space. func (fs *localfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error) { return nil, errtypes.NotSupported("update storage space") } func (fs *localfs) propagate(ctx context.Context, leafPath string) error { - var root string if fs.isShareFolderChild(ctx, leafPath) || strings.HasSuffix(path.Clean(leafPath), fs.conf.ShareFolder) { root = fs.wrapReferences(ctx, "/") diff --git a/pkg/storage/utils/localfs/localfs_unix.go b/pkg/storage/utils/localfs/localfs_unix.go index 61cdaf9e86d..24b01b5f908 100644 --- a/pkg/storage/utils/localfs/localfs_unix.go +++ b/pkg/storage/utils/localfs/localfs_unix.go @@ -39,7 +39,7 @@ import ( // - inode (if available), // - device (if available) and // - size. -// errors are logged, but an etag will still be returned +// errors are logged, but an etag will still be returned. func calcEtag(ctx context.Context, fi os.FileInfo) string { log := appctx.GetLogger(ctx) h := md5.New() diff --git a/pkg/storage/utils/localfs/upload.go b/pkg/storage/utils/localfs/upload.go index 8bc43c46402..394c87514d5 100644 --- a/pkg/storage/utils/localfs/upload.go +++ b/pkg/storage/utils/localfs/upload.go @@ -85,9 +85,8 @@ func (fs *localfs) Upload(ctx context.Context, ref *provider.Reference, r io.Rea // It resolves the resource and then reuses the NewUpload function // Currently requires the uploadLength to be set // TODO to implement LengthDeferrerDataStore make size optional -// TODO read optional content for small files in this request +// TODO read optional content for small files in this request. func (fs *localfs) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) { - np, err := fs.resolve(ctx, ref) if err != nil { return nil, errors.Wrap(err, "localfs: error resolving reference") @@ -135,7 +134,6 @@ func (fs *localfs) UseIn(composer *tusd.StoreComposer) { // the Fileinfo metadata must contain a dir and a filename. // returns a unique id which is used to identify the upload. The properties Size and MetaData will be filled. func (fs *localfs) NewUpload(ctx context.Context, info tusd.FileInfo) (upload tusd.Upload, err error) { - log := appctx.GetLogger(ctx) log.Debug().Interface("info", info).Msg("localfs: NewUpload") @@ -202,7 +200,7 @@ func (fs *localfs) getUploadPath(ctx context.Context, uploadID string) (string, return filepath.Join(fs.conf.Uploads, uploadID), nil } -// GetUpload returns the Upload for the given upload id +// GetUpload returns the Upload for the given upload id. func (fs *localfs) GetUpload(ctx context.Context, id string) (tusd.Upload, error) { binPath, err := fs.getUploadPath(ctx, id) if err != nil { @@ -262,17 +260,17 @@ type fileUpload struct { ctx context.Context } -// GetInfo returns the FileInfo +// GetInfo returns the FileInfo. func (upload *fileUpload) GetInfo(ctx context.Context) (tusd.FileInfo, error) { return upload.info, nil } -// GetReader returns an io.Reader for the upload +// GetReader returns an io.Reader for the upload. func (upload *fileUpload) GetReader(ctx context.Context) (io.Reader, error) { return os.Open(upload.binPath) } -// WriteChunk writes the stream from the reader to the given offset of the upload +// WriteChunk writes the stream from the reader to the given offset of the upload. func (upload *fileUpload) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) { file, err := os.OpenFile(upload.binPath, os.O_WRONLY|os.O_APPEND, defaultFilePerm) if err != nil { @@ -307,9 +305,8 @@ func (upload *fileUpload) writeInfo() error { return os.WriteFile(upload.infoPath, data, defaultFilePerm) } -// FinishUpload finishes an upload and moves the file to the internal destination +// FinishUpload finishes an upload and moves the file to the internal destination. func (upload *fileUpload) FinishUpload(ctx context.Context) error { - np := upload.info.Storage["InternalDestination"] // TODO check etag with If-Match header @@ -351,12 +348,12 @@ func (upload *fileUpload) FinishUpload(ctx context.Context) error { // - the storage needs to implement AsTerminatableUpload // - the upload needs to implement Terminate -// AsTerminatableUpload returns a a TerminatableUpload +// AsTerminatableUpload returns a TerminatableUpload. func (fs *localfs) AsTerminatableUpload(upload tusd.Upload) tusd.TerminatableUpload { return upload.(*fileUpload) } -// Terminate terminates the upload +// Terminate terminates the upload. func (upload *fileUpload) Terminate(ctx context.Context) error { if err := os.Remove(upload.infoPath); err != nil { return err diff --git a/pkg/storage/utils/templates/templates.go b/pkg/storage/utils/templates/templates.go index 2741073cc6a..78733e1b101 100644 --- a/pkg/storage/utils/templates/templates.go +++ b/pkg/storage/utils/templates/templates.go @@ -37,7 +37,7 @@ import ( ) // UserData contains the template placeholders for a user. -// For example {{.Username}} or {{.Id.Idp}} +// For example {{.Username}} or {{.Id.Idp}}. type UserData struct { *userpb.User Email EmailData diff --git a/pkg/storage/utils/templates/templates_test.go b/pkg/storage/utils/templates/templates_test.go index fb02dc3de3a..28f0c95421d 100644 --- a/pkg/storage/utils/templates/templates_test.go +++ b/pkg/storage/utils/templates/templates_test.go @@ -109,14 +109,14 @@ func TestUserPanic(t *testing.T) { assertPanic(t, testBadUser) } -// should panic +// should panic. func testBadLayout() { layout := "{{ bad layout syntax" user := &userpb.User{} WithUser(user, layout) } -// should panic +// should panic. func testBadUser() { layout := "{{ .DoesNotExist }}" user := &userpb.User{} diff --git a/pkg/storage/utils/walker/mock/walker_mock.go b/pkg/storage/utils/walker/mock/walker_mock.go index 725bf79dd99..85f9783764e 100644 --- a/pkg/storage/utils/walker/mock/walker_mock.go +++ b/pkg/storage/utils/walker/mock/walker_mock.go @@ -31,12 +31,12 @@ import ( type mockWalker struct{} // NewWalker creates a mock walker that implements the Walk interface -// supposed to be used for testing +// supposed to be used for testing. func NewWalker() walker.Walker { return &mockWalker{} } -// converts a FileInfo to a reva ResourceInfo +// converts a FileInfo to a reva ResourceInfo. func convertFileInfoToResourceInfo(path string, f fs.FileInfo) *provider.ResourceInfo { if f == nil { return nil @@ -62,7 +62,7 @@ func mockWalkFunc(fn walker.WalkFunc) filepath.WalkFunc { } } -// Walk walks into the local file system using the built-in filepath.Walk go function +// Walk walks into the local file system using the built-in filepath.Walk go function. func (m *mockWalker) Walk(_ context.Context, root string, fn walker.WalkFunc) error { return filepath.Walk(root, mockWalkFunc(fn)) } diff --git a/pkg/storage/utils/walker/walker.go b/pkg/storage/utils/walker/walker.go index 2a6059994a9..10a62ab0a1f 100644 --- a/pkg/storage/utils/walker/walker.go +++ b/pkg/storage/utils/walker/walker.go @@ -23,10 +23,9 @@ import ( "fmt" "path/filepath" - provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" - gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" + provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" "github.com/cs3org/reva/pkg/errtypes" ) @@ -40,7 +39,7 @@ import ( // Otherwise, if the function returns a non-nil error, Walk stops entirely and returns that error. type WalkFunc func(path string, info *provider.ResourceInfo, err error) error -// Walker is an interface implemented by objects that are able to walk from a dir rooted into the passed path +// Walker is an interface implemented by objects that are able to walk from a dir rooted into the passed path. type Walker interface { // Walk walks the file tree rooted at root, calling fn for each file or folder in the tree, including the root. Walk(context.Context, string, WalkFunc) error @@ -50,7 +49,7 @@ type revaWalker struct { gtw gateway.GatewayAPIClient } -// NewWalker creates a Walker object that uses the reva gateway +// NewWalker creates a Walker object that uses the reva gateway. func NewWalker(gtw gateway.GatewayAPIClient) Walker { return &revaWalker{gtw: gtw} } @@ -73,7 +72,6 @@ func (r *revaWalker) Walk(ctx context.Context, root string, fn WalkFunc) error { } func (r *revaWalker) walkRecursively(ctx context.Context, path string, info *provider.ResourceInfo, fn WalkFunc) error { - if info.Type != provider.ResourceType_RESOURCE_TYPE_CONTAINER { return fn(path, info, nil) } diff --git a/pkg/sysinfo/metrics.go b/pkg/sysinfo/metrics.go index 2dced38f56a..9518668b659 100644 --- a/pkg/sysinfo/metrics.go +++ b/pkg/sysinfo/metrics.go @@ -24,12 +24,11 @@ import ( "reflect" "strings" + "github.com/cs3org/reva/pkg/utils" "github.com/pkg/errors" "go.opencensus.io/stats" "go.opencensus.io/stats/view" "go.opencensus.io/tag" - - "github.com/cs3org/reva/pkg/utils" ) type sysInfoMetricsLabels = map[tag.Key]string diff --git a/pkg/test/vars.go b/pkg/test/vars.go index ba3799d0acb..4abd18be0fd 100644 --- a/pkg/test/vars.go +++ b/pkg/test/vars.go @@ -26,25 +26,25 @@ import ( ) const ( - // TmpDirPattern is the pattern used for tmp folder creation + // TmpDirPattern is the pattern used for tmp folder creation. TmpDirPattern = "tmp-reva-" ) // File struct represents a test file, -// with a certain content. Its name is defined in TestDir +// with a certain content. Its name is defined in TestDir. type File struct { Content string } // Dir struct represents a test dir, where each -// key is the resource (Dir or File) name +// key is the resource (Dir or File) name. type Dir map[string]interface{} -// CleanerFunc is a function to call after creating a TestDir +// CleanerFunc is a function to call after creating a TestDir. type CleanerFunc func() // TmpDir creates a dir in the system temp folder that has -// TmpDirPattern as prefix +// TmpDirPattern as prefix. func TmpDir() (string, CleanerFunc, error) { name, err := os.MkdirTemp("", TmpDirPattern) if err != nil { @@ -58,7 +58,7 @@ func TmpDir() (string, CleanerFunc, error) { return name, c, nil } -// NewTestDir creates the Dir structure in a local temporary folder +// NewTestDir creates the Dir structure in a local temporary folder. func NewTestDir(src Dir) (tmpdir string, cleanup CleanerFunc, err error) { tmpdir, cleanup, err = TmpDir() if err != nil { @@ -68,7 +68,7 @@ func NewTestDir(src Dir) (tmpdir string, cleanup CleanerFunc, err error) { return } -// NewFile creates a new file given the path and the content +// NewFile creates a new file given the path and the content. func NewFile(path, content string) error { file, err := os.Create(path) if err != nil { @@ -103,7 +103,7 @@ func newTestDirFileRecursive(p string, res interface{}) error { } } -// checks if the two files have the same content +// checks if the two files have the same content. func fileEquals(file1, file2 string) bool { c1, _ := os.ReadFile(file1) c2, _ := os.ReadFile(file2) @@ -114,7 +114,6 @@ func fileEquals(file1, file2 string) bool { // Two files are equals if the name and the content is equal, while two folders // are equal if the name is equal and the content is recursively equal. func DirEquals(dir1, dir2 string) bool { - l1, _ := os.ReadDir(dir1) l2, _ := os.ReadDir(dir2) @@ -143,7 +142,6 @@ func DirEquals(dir1, dir2 string) bool { default: // different resource type return false } - } return true } diff --git a/pkg/token/manager/demo/demo.go b/pkg/token/manager/demo/demo.go index a200de0898c..d20dfd071a7 100644 --- a/pkg/token/manager/demo/demo.go +++ b/pkg/token/manager/demo/demo.go @@ -65,7 +65,7 @@ func (m *manager) DismantleToken(ctx context.Context, token string) (*user.User, } // from https://stackoverflow.com/questions/28020070/golang-serialize-and-deserialize-back -// go binary encoder +// go binary encoder. func encode(c *claims) (string, error) { b := bytes.Buffer{} e := gob.NewEncoder(&b) @@ -77,7 +77,7 @@ func encode(c *claims) (string, error) { } // from https://stackoverflow.com/questions/28020070/golang-serialize-and-deserialize-back -// go binary decoder +// go binary decoder. func decode(token string) (*claims, error) { c := &claims{} by, err := base64.StdEncoding.DecodeString(token) diff --git a/pkg/token/token.go b/pkg/token/token.go index edc9d6d6889..395a4f9d82f 100644 --- a/pkg/token/token.go +++ b/pkg/token/token.go @@ -25,7 +25,7 @@ import ( user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ) -// Manager is the interface to implement to sign and verify tokens +// Manager is the interface to implement to sign and verify tokens. type Manager interface { MintToken(ctx context.Context, u *user.User, scope map[string]*auth.Scope) (string, error) DismantleToken(ctx context.Context, token string) (*user.User, map[string]*auth.Scope, error) diff --git a/pkg/user/blocked.go b/pkg/user/blocked.go index 298a02b56c7..e5227f59ca1 100644 --- a/pkg/user/blocked.go +++ b/pkg/user/blocked.go @@ -18,10 +18,10 @@ package user -// BlockedUsers is a set containing all the blocked users +// BlockedUsers is a set containing all the blocked users. type BlockedUsers map[string]struct{} -// NewBlockedUsersSet creates a new set of blocked users from a list +// NewBlockedUsersSet creates a new set of blocked users from a list. func NewBlockedUsersSet(users []string) BlockedUsers { s := make(map[string]struct{}) for _, u := range users { @@ -30,7 +30,7 @@ func NewBlockedUsersSet(users []string) BlockedUsers { return s } -// IsBlocked returns true if the user is blocked +// IsBlocked returns true if the user is blocked. func (b BlockedUsers) IsBlocked(user string) bool { _, ok := b[user] return ok diff --git a/pkg/user/manager/json/json.go b/pkg/user/manager/json/json.go index f03d0f12721..d4a748741e4 100644 --- a/pkg/user/manager/json/json.go +++ b/pkg/user/manager/json/json.go @@ -25,13 +25,12 @@ import ( "strconv" "strings" + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/user" "github.com/cs3org/reva/pkg/user/manager/registry" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - "github.com/cs3org/reva/pkg/errtypes" ) func init() { diff --git a/pkg/user/manager/ldap/ldap.go b/pkg/user/manager/ldap/ldap.go index 402240996db..c1885ef76c5 100644 --- a/pkg/user/manager/ldap/ldap.go +++ b/pkg/user/manager/ldap/ldap.go @@ -77,7 +77,7 @@ type attributes struct { GIDNumber string `mapstructure:"gidNumber"` } -// Default attributes (Active Directory) +// Default attributes (Active Directory). var ldapDefaults = attributes{ DN: "dn", UID: "ms-DS-ConsistencyGuid", // you can fall back to objectguid or even samaccountname but you will run into trouble when user names change. You have been warned. @@ -297,7 +297,6 @@ func (m *manager) GetUserByClaim(ctx context.Context, claim, value string, skipF } return u, nil - } func (m *manager) FindUsers(ctx context.Context, query string, skipFetchingGroups bool) ([]*userpb.User, error) { diff --git a/pkg/user/manager/loader/loader.go b/pkg/user/manager/loader/loader.go index 7640c3ff313..492cb9d7232 100644 --- a/pkg/user/manager/loader/loader.go +++ b/pkg/user/manager/loader/loader.go @@ -25,5 +25,5 @@ import ( _ "github.com/cs3org/reva/pkg/user/manager/ldap" _ "github.com/cs3org/reva/pkg/user/manager/nextcloud" _ "github.com/cs3org/reva/pkg/user/manager/owncloudsql" - // Add your own here + // Add your own here. ) diff --git a/pkg/user/manager/nextcloud/nextcloud.go b/pkg/user/manager/nextcloud/nextcloud.go index f425fc3300a..ad413380b23 100644 --- a/pkg/user/manager/nextcloud/nextcloud.go +++ b/pkg/user/manager/nextcloud/nextcloud.go @@ -26,16 +26,14 @@ import ( "net/http" "strings" + userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" ctxpkg "github.com/cs3org/reva/pkg/ctx" - "github.com/cs3org/reva/pkg/errtypes" "github.com/cs3org/reva/pkg/user" "github.com/cs3org/reva/pkg/user/manager/registry" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" - - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - // "github.com/cs3org/reva/pkg/errtypes" + // "github.com/cs3org/reva/pkg/errtypes". ) func init() { @@ -50,7 +48,7 @@ type Manager struct { endPoint string } -// UserManagerConfig contains config for a Nextcloud-based UserManager +// UserManagerConfig contains config for a Nextcloud-based UserManager. type UserManagerConfig struct { EndPoint string `mapstructure:"endpoint" docs:";The Nextcloud backend endpoint for user management"` SharedSecret string `mapstructure:"shared_secret"` @@ -73,7 +71,7 @@ func parseConfig(m map[string]interface{}) (*UserManagerConfig, error) { return c, nil } -// Action describes a REST request to forward to the Nextcloud backend +// Action describes a REST request to forward to the Nextcloud backend. type Action struct { verb string argS string @@ -90,7 +88,7 @@ func New(m map[string]interface{}) (user.Manager, error) { return NewUserManager(c) } -// NewUserManager returns a new Nextcloud-based UserManager +// NewUserManager returns a new Nextcloud-based UserManager. func NewUserManager(c *UserManagerConfig) (*Manager, error) { var client *http.Client if c.MockHTTP { @@ -110,7 +108,7 @@ func NewUserManager(c *UserManagerConfig) (*Manager, error) { }, nil } -// SetHTTPClient sets the HTTP client +// SetHTTPClient sets the HTTP client. func (um *Manager) SetHTTPClient(c *http.Client) { um.client = c } diff --git a/pkg/user/manager/nextcloud/nextcloud_server_mock.go b/pkg/user/manager/nextcloud/nextcloud_server_mock.go index 2d6ebc9a941..88445d2c823 100644 --- a/pkg/user/manager/nextcloud/nextcloud_server_mock.go +++ b/pkg/user/manager/nextcloud/nextcloud_server_mock.go @@ -29,7 +29,7 @@ import ( ) // Response contains data for the Nextcloud mock server to respond -// and to switch to a new server state +// and to switch to a new server state. type Response struct { code int body string @@ -49,7 +49,7 @@ var responses = map[string]Response{ `POST /apps/sciencemesh/~tester/api/user/FindUsers some-query`: {200, `[{"id":{"idp":"some-idp","opaque_id":"some-opaque-user-id","type":1}}]`, serverStateHome}, } -// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server +// GetNextcloudServerMock returns a handler that pretends to be a remote Nextcloud server. func GetNextcloudServerMock(called *[]string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { buf := new(strings.Builder) diff --git a/pkg/user/manager/nextcloud/nextcloud_test.go b/pkg/user/manager/nextcloud/nextcloud_test.go index ca875fb757d..8fff58cb5ef 100644 --- a/pkg/user/manager/nextcloud/nextcloud_test.go +++ b/pkg/user/manager/nextcloud/nextcloud_test.go @@ -22,18 +22,15 @@ import ( "context" "os" - "google.golang.org/grpc/metadata" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" - "github.com/cs3org/reva/pkg/auth/scope" ctxpkg "github.com/cs3org/reva/pkg/ctx" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" "github.com/cs3org/reva/pkg/user/manager/nextcloud" "github.com/cs3org/reva/tests/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/grpc/metadata" ) func setUpNextcloudServer() (*nextcloud.Manager, *[]string, func()) { diff --git a/pkg/user/manager/owncloudsql/accounts/accounts.go b/pkg/user/manager/owncloudsql/accounts/accounts.go index 0a24f311a7a..f1491fbbcc0 100644 --- a/pkg/user/manager/owncloudsql/accounts/accounts.go +++ b/pkg/user/manager/owncloudsql/accounts/accounts.go @@ -28,7 +28,7 @@ import ( "github.com/pkg/errors" ) -// Accounts represents oc10-style Accounts +// Accounts represents oc10-style Accounts. type Accounts struct { driver string db *sql.DB @@ -36,7 +36,7 @@ type Accounts struct { selectSQL string } -// NewMysql returns a new Cache instance connecting to a MySQL database +// NewMysql returns a new Cache instance connecting to a MySQL database. func NewMysql(dsn string, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) { sqldb, err := sql.Open("mysql", dsn) if err != nil { @@ -54,9 +54,8 @@ func NewMysql(dsn string, joinUsername, joinUUID, enableMedialSearch bool) (*Acc return New("mysql", sqldb, joinUsername, joinUUID, enableMedialSearch) } -// New returns a new Cache instance connecting to the given sql.DB +// New returns a new Cache instance connecting to the given sql.DB. func New(driver string, sqldb *sql.DB, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) { - sel := "SELECT id, email, user_id, display_name, quota, last_login, backend, home, state" from := ` FROM oc_accounts a @@ -117,12 +116,12 @@ func (as *Accounts) rowToAccount(ctx context.Context, row Scannable) (*Account, return &a, nil } -// Scannable describes the interface providing a Scan method +// Scannable describes the interface providing a Scan method. type Scannable interface { Scan(...interface{}) error } -// GetAccountByClaim fetches an account by mail, username or userid +// GetAccountByClaim fetches an account by mail, username or userid. func (as *Accounts) GetAccountByClaim(ctx context.Context, claim, value string) (*Account, error) { // TODO align supported claims with rest driver and the others, maybe refactor into common mapping var row *sql.Row @@ -201,7 +200,7 @@ func (as *Accounts) FindAccounts(ctx context.Context, query string) ([]Account, return accounts, nil } -// GetAccountGroups lasts the groups for an account +// GetAccountGroups lasts the groups for an account. func (as *Accounts) GetAccountGroups(ctx context.Context, uid string) ([]string, error) { rows, err := as.db.QueryContext(ctx, "SELECT gid FROM oc_group_user WHERE uid=?", uid) if err != nil { diff --git a/pkg/user/manager/owncloudsql/accounts/accounts_test.go b/pkg/user/manager/owncloudsql/accounts/accounts_test.go index 1fd9f8cd4ea..e40d59103d7 100644 --- a/pkg/user/manager/owncloudsql/accounts/accounts_test.go +++ b/pkg/user/manager/owncloudsql/accounts/accounts_test.go @@ -23,10 +23,8 @@ import ( "database/sql" "os" - _ "github.com/mattn/go-sqlite3" - "github.com/cs3org/reva/pkg/user/manager/owncloudsql/accounts" - + _ "github.com/mattn/go-sqlite3" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -34,30 +32,30 @@ import ( var _ = Describe("Accounts", func() { var ( conn *accounts.Accounts - testDbFile *os.File + testDBFile *os.File sqldb *sql.DB ) BeforeEach(func() { var err error - testDbFile, err = os.CreateTemp("", "example") + testDBFile, err = os.CreateTemp("", "example") Expect(err).ToNot(HaveOccurred()) dbData, err := os.ReadFile("test.sqlite") Expect(err).ToNot(HaveOccurred()) - _, err = testDbFile.Write(dbData) + _, err = testDBFile.Write(dbData) Expect(err).ToNot(HaveOccurred()) - err = testDbFile.Close() + err = testDBFile.Close() Expect(err).ToNot(HaveOccurred()) - sqldb, err = sql.Open("sqlite3", testDbFile.Name()) + sqldb, err = sql.Open("sqlite3", testDBFile.Name()) Expect(err).ToNot(HaveOccurred()) }) AfterEach(func() { - os.Remove(testDbFile.Name()) + os.Remove(testDBFile.Name()) }) Describe("GetAccountByClaim", func() { diff --git a/pkg/user/manager/owncloudsql/owncloudsql.go b/pkg/user/manager/owncloudsql/owncloudsql.go index e56bc7cf0ff..6f27aa33f9a 100644 --- a/pkg/user/manager/owncloudsql/owncloudsql.go +++ b/pkg/user/manager/owncloudsql/owncloudsql.go @@ -29,11 +29,11 @@ import ( "github.com/cs3org/reva/pkg/user" "github.com/cs3org/reva/pkg/user/manager/owncloudsql/accounts" "github.com/cs3org/reva/pkg/user/manager/registry" - "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" - // Provides mysql drivers + // Provides mysql drivers. _ "github.com/go-sql-driver/mysql" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" ) func init() { @@ -46,11 +46,11 @@ type manager struct { } type config struct { - DbUsername string `mapstructure:"dbusername"` - DbPassword string `mapstructure:"dbpassword"` - DbHost string `mapstructure:"dbhost"` - DbPort int `mapstructure:"dbport"` - DbName string `mapstructure:"dbname"` + DBUsername string `mapstructure:"dbusername"` + DBPassword string `mapstructure:"dbpassword"` + DBHost string `mapstructure:"dbhost"` + DBPort int `mapstructure:"dbport"` + DBName string `mapstructure:"dbname"` Idp string `mapstructure:"idp"` Nobody int64 `mapstructure:"nobody"` JoinUsername bool `mapstructure:"join_username"` @@ -58,7 +58,7 @@ type config struct { EnableMedialSearch bool `mapstructure:"enable_medial_search"` } -// NewMysql returns a new user manager connection to an owncloud mysql database +// NewMysql returns a new user manager connection to an owncloud mysql database. func NewMysql(m map[string]interface{}) (user.Manager, error) { mgr := &manager{} err := mgr.Configure(m) @@ -68,7 +68,7 @@ func NewMysql(m map[string]interface{}) (user.Manager, error) { } mgr.db, err = accounts.NewMysql( - fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mgr.c.DbUsername, mgr.c.DbPassword, mgr.c.DbHost, mgr.c.DbPort, mgr.c.DbName), + fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mgr.c.DBUsername, mgr.c.DBPassword, mgr.c.DBHost, mgr.c.DBPort, mgr.c.DBName), mgr.c.JoinUsername, mgr.c.JoinOwnCloudUUID, mgr.c.EnableMedialSearch, @@ -122,7 +122,6 @@ func (m *manager) GetUserByClaim(ctx context.Context, claim, value string, skipF } func (m *manager) FindUsers(ctx context.Context, query string, skipFetchingGroups bool) ([]*userpb.User, error) { - accounts, err := m.db.FindAccounts(ctx, query) if err == sql.ErrNoRows { return nil, errtypes.NotFound("no users found for " + query) diff --git a/pkg/user/rpc_user.go b/pkg/user/rpc_user.go index 9c64c8572d5..55c7396e761 100644 --- a/pkg/user/rpc_user.go +++ b/pkg/user/rpc_user.go @@ -39,12 +39,12 @@ type ProviderPlugin struct { Impl Manager } -// Server returns the RPC Server which serves the methods that the Client calls over net/rpc +// Server returns the RPC Server which serves the methods that the Client calls over net/rpc. func (p *ProviderPlugin) Server(*hcplugin.MuxBroker) (interface{}, error) { return &RPCServer{Impl: p.Impl}, nil } -// Client returns interface implementation for the plugin that communicates to the server end of the plugin +// Client returns interface implementation for the plugin that communicates to the server end of the plugin. func (p *ProviderPlugin) Client(b *hcplugin.MuxBroker, c *rpc.Client) (interface{}, error) { return &RPCClient{Client: c}, nil } @@ -52,17 +52,17 @@ func (p *ProviderPlugin) Client(b *hcplugin.MuxBroker, c *rpc.Client) (interface // RPCClient is an implementation of Manager that talks over RPC. type RPCClient struct{ Client *rpc.Client } -// ConfigureArg for RPC +// ConfigureArg for RPC. type ConfigureArg struct { Ml map[string]interface{} } -// ConfigureReply for RPC +// ConfigureReply for RPC. type ConfigureReply struct { Err error } -// Configure RPCClient configure method +// Configure RPCClient configure method. func (m *RPCClient) Configure(ml map[string]interface{}) error { args := ConfigureArg{Ml: ml} resp := ConfigureReply{} @@ -73,20 +73,20 @@ func (m *RPCClient) Configure(ml map[string]interface{}) error { return resp.Err } -// GetUserArg for RPC +// GetUserArg for RPC. type GetUserArg struct { Ctx map[interface{}]interface{} UID *userpb.UserId SkipFetchingGroups bool } -// GetUserReply for RPC +// GetUserReply for RPC. type GetUserReply struct { User *userpb.User Err error } -// GetUser RPCClient GetUser method +// GetUser RPCClient GetUser method. func (m *RPCClient) GetUser(ctx context.Context, uid *userpb.UserId, skipFetchingGroups bool) (*userpb.User, error) { ctxVal := appctx.GetKeyValuesFromCtx(ctx) args := GetUserArg{Ctx: ctxVal, UID: uid, SkipFetchingGroups: skipFetchingGroups} @@ -98,7 +98,7 @@ func (m *RPCClient) GetUser(ctx context.Context, uid *userpb.UserId, skipFetchin return resp.User, resp.Err } -// GetUserByClaimArg for RPC +// GetUserByClaimArg for RPC. type GetUserByClaimArg struct { Ctx map[interface{}]interface{} Claim string @@ -106,13 +106,13 @@ type GetUserByClaimArg struct { SkipFetchingGroups bool } -// GetUserByClaimReply for RPC +// GetUserByClaimReply for RPC. type GetUserByClaimReply struct { User *userpb.User Err error } -// GetUserByClaim RPCClient GetUserByClaim method +// GetUserByClaim RPCClient GetUserByClaim method. func (m *RPCClient) GetUserByClaim(ctx context.Context, claim, value string, skipFetchingGroups bool) (*userpb.User, error) { ctxVal := appctx.GetKeyValuesFromCtx(ctx) args := GetUserByClaimArg{Ctx: ctxVal, Claim: claim, Value: value, SkipFetchingGroups: skipFetchingGroups} @@ -124,19 +124,19 @@ func (m *RPCClient) GetUserByClaim(ctx context.Context, claim, value string, ski return resp.User, resp.Err } -// GetUserGroupsArg for RPC +// GetUserGroupsArg for RPC. type GetUserGroupsArg struct { Ctx map[interface{}]interface{} User *userpb.UserId } -// GetUserGroupsReply for RPC +// GetUserGroupsReply for RPC. type GetUserGroupsReply struct { Group []string Err error } -// GetUserGroups RPCClient GetUserGroups method +// GetUserGroups RPCClient GetUserGroups method. func (m *RPCClient) GetUserGroups(ctx context.Context, user *userpb.UserId) ([]string, error) { ctxVal := appctx.GetKeyValuesFromCtx(ctx) args := GetUserGroupsArg{Ctx: ctxVal, User: user} @@ -148,20 +148,20 @@ func (m *RPCClient) GetUserGroups(ctx context.Context, user *userpb.UserId) ([]s return resp.Group, resp.Err } -// FindUsersArg for RPC +// FindUsersArg for RPC. type FindUsersArg struct { Ctx map[interface{}]interface{} Query string SkipFetchingGroups bool } -// FindUsersReply for RPC +// FindUsersReply for RPC. type FindUsersReply struct { User []*userpb.User Err error } -// FindUsers RPCClient FindUsers method +// FindUsers RPCClient FindUsers method. func (m *RPCClient) FindUsers(ctx context.Context, query string, skipFetchingGroups bool) ([]*userpb.User, error) { ctxVal := appctx.GetKeyValuesFromCtx(ctx) args := FindUsersArg{Ctx: ctxVal, Query: query, SkipFetchingGroups: skipFetchingGroups} @@ -173,40 +173,40 @@ func (m *RPCClient) FindUsers(ctx context.Context, query string, skipFetchingGro return resp.User, resp.Err } -// RPCServer is the server that RPCClient talks to, conforming to the requirements of net/rpc +// RPCServer is the server that RPCClient talks to, conforming to the requirements of net/rpc. type RPCServer struct { // This is the real implementation Impl Manager } -// Configure RPCServer Configure method +// Configure RPCServer Configure method. func (m *RPCServer) Configure(args ConfigureArg, resp *ConfigureReply) error { resp.Err = m.Impl.Configure(args.Ml) return nil } -// GetUser RPCServer GetUser method +// GetUser RPCServer GetUser method. func (m *RPCServer) GetUser(args GetUserArg, resp *GetUserReply) error { ctx := appctx.PutKeyValuesToCtx(args.Ctx) resp.User, resp.Err = m.Impl.GetUser(ctx, args.UID, args.SkipFetchingGroups) return nil } -// GetUserByClaim RPCServer GetUserByClaim method +// GetUserByClaim RPCServer GetUserByClaim method. func (m *RPCServer) GetUserByClaim(args GetUserByClaimArg, resp *GetUserByClaimReply) error { ctx := appctx.PutKeyValuesToCtx(args.Ctx) resp.User, resp.Err = m.Impl.GetUserByClaim(ctx, args.Claim, args.Value, args.SkipFetchingGroups) return nil } -// GetUserGroups RPCServer GetUserGroups method +// GetUserGroups RPCServer GetUserGroups method. func (m *RPCServer) GetUserGroups(args GetUserGroupsArg, resp *GetUserGroupsReply) error { ctx := appctx.PutKeyValuesToCtx(args.Ctx) resp.Group, resp.Err = m.Impl.GetUserGroups(ctx, args.User) return nil } -// FindUsers RPCServer FindUsers method +// FindUsers RPCServer FindUsers method. func (m *RPCServer) FindUsers(args FindUsersArg, resp *FindUsersReply) error { ctx := appctx.PutKeyValuesToCtx(args.Ctx) resp.User, resp.Err = m.Impl.FindUsers(ctx, args.Query, args.SkipFetchingGroups) diff --git a/pkg/utils/ldap.go b/pkg/utils/ldap.go index 0d3aa9da069..84980a8d5fb 100644 --- a/pkg/utils/ldap.go +++ b/pkg/utils/ldap.go @@ -41,7 +41,7 @@ type LDAPConn struct { // GetLDAPConnection initializes an LDAPS connection and allows // to set TLS options e.g. to add trusted Certificates or disable -// Certificate verification +// Certificate verification. func GetLDAPConnection(c *LDAPConn) (*ldap.Conn, error) { tlsconfig := &tls.Config{InsecureSkipVerify: c.Insecure} diff --git a/pkg/utils/resourceid/owncloud.go b/pkg/utils/resourceid/owncloud.go index c6041f902ce..5d34ff8e80d 100644 --- a/pkg/utils/resourceid/owncloud.go +++ b/pkg/utils/resourceid/owncloud.go @@ -31,7 +31,7 @@ const ( ) // OwnCloudResourceIDUnwrap returns the wrapped resource id -// by OwnCloudResourceIDWrap and returns nil if not possible +// by OwnCloudResourceIDWrap and returns nil if not possible. func OwnCloudResourceIDUnwrap(rid string) *provider.ResourceId { id, err := unwrap(rid) if err != nil { @@ -57,14 +57,14 @@ func unwrap(rid string) (*provider.ResourceId, error) { } // OwnCloudResourceIDWrap wraps a resource id into a xml safe string -// which can then be passed to the outside world +// which can then be passed to the outside world. func OwnCloudResourceIDWrap(r *provider.ResourceId) string { return wrap(r.StorageId, r.OpaqueId) } // The storageID and OpaqueID need to be separated by a delimiter // this delimiter should be Url safe -// we use a reserved character +// we use a reserved character. func wrap(sid string, oid string) string { return sid + idDelimiter + oid } diff --git a/pkg/utils/resourceid/owncloud_test.go b/pkg/utils/resourceid/owncloud_test.go index 8c8f928519e..e229757aa96 100644 --- a/pkg/utils/resourceid/owncloud_test.go +++ b/pkg/utils/resourceid/owncloud_test.go @@ -84,5 +84,4 @@ func TestUnwrap(t *testing.T) { t.Error("StorageID or OpaqueID doesn't match") } } - } diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 539acf5b576..f2e80ae1b80 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -40,7 +40,7 @@ import ( "github.com/cs3org/reva/pkg/registry" "github.com/cs3org/reva/pkg/registry/memory" - // gocritic is disabled because google.golang.org/protobuf/proto does not provide a method to convert MessageV1 to MessageV2 + // gocritic is disabled because google.golang.org/protobuf/proto does not provide a method to convert MessageV1 to MessageV2. "github.com/golang/protobuf/proto" //nolint:staticcheck "google.golang.org/protobuf/encoding/protojson" ) @@ -55,7 +55,7 @@ var ( ) // Skip evaluates whether a source endpoint contains any of the prefixes. -// i.e: /a/b/c/d/e contains prefix /a/b/c +// i.e: /a/b/c/d/e contains prefix /a/b/c. func Skip(source string, prefixes []string) bool { for i := range prefixes { if strings.HasPrefix(source, prefixes[i]) { @@ -65,7 +65,7 @@ func Skip(source string, prefixes []string) bool { return false } -// GetClientIP retrieves the client IP from incoming requests +// GetClientIP retrieves the client IP from incoming requests. func GetClientIP(r *http.Request) (string, error) { var clientIP string forwarded := r.Header.Get("X-FORWARDED-FOR") @@ -93,7 +93,7 @@ func ToSnakeCase(str string) string { return strings.ToLower(snake) } -// ResolvePath converts relative local paths to absolute paths +// ResolvePath converts relative local paths to absolute paths. func ResolvePath(path string) (string, error) { usr, err := user.Current() if err != nil { @@ -140,7 +140,7 @@ func LaterTS(t1 *types.Timestamp, t2 *types.Timestamp) *types.Timestamp { return t2 } -// ExtractGranteeID returns the ID, user or group, set in the GranteeId object +// ExtractGranteeID returns the ID, user or group, set in the GranteeId object. func ExtractGranteeID(grantee *provider.Grantee) (*userpb.UserId, *grouppb.GroupId) { switch t := grantee.Id.(type) { case *provider.Grantee_UserId: @@ -209,14 +209,14 @@ func IsValidName(name string) bool { } // MarshalProtoV1ToJSON marshals a proto V1 message to a JSON byte array -// TODO: update this once we start using V2 in CS3APIs +// TODO: update this once we start using V2 in CS3APIs. func MarshalProtoV1ToJSON(m proto.Message) ([]byte, error) { mV2 := proto.MessageV2(m) return protojson.Marshal(mV2) } // UnmarshalJSONToProtoV1 decodes a JSON byte array to a specified proto message type -// TODO: update this once we start using V2 in CS3APIs +// TODO: update this once we start using V2 in CS3APIs. func UnmarshalJSONToProtoV1(b []byte, m proto.Message) error { mV2 := proto.MessageV2(m) if err := protojson.Unmarshal(b, mV2); err != nil { @@ -246,12 +246,12 @@ func IsAbsoluteReference(ref *provider.Reference) bool { } // IsAbsolutePathReference returns true if the given reference qualifies as a global path -// when only the path is set and starts with / +// when only the path is set and starts with /. func IsAbsolutePathReference(ref *provider.Reference) bool { return ref.ResourceId == nil && strings.HasPrefix(ref.Path, "/") } -// MakeRelativePath prefixes the path with a . to use it in a relative reference +// MakeRelativePath prefixes the path with a . to use it in a relative reference. func MakeRelativePath(p string) string { p = path.Join("/", p) @@ -261,7 +261,7 @@ func MakeRelativePath(p string) string { return "." + p } -// UserTypeMap translates account type string to CS3 UserType +// UserTypeMap translates account type string to CS3 UserType. func UserTypeMap(accountType string) userpb.UserType { var t userpb.UserType switch accountType { @@ -283,7 +283,7 @@ func UserTypeMap(accountType string) userpb.UserType { return t } -// UserTypeToString translates CS3 UserType to user-readable string +// UserTypeToString translates CS3 UserType to user-readable string. func UserTypeToString(accountType userpb.UserType) string { var t string switch accountType { @@ -359,7 +359,7 @@ func GetViewMode(viewMode string) gateway.OpenInAppRequest_ViewMode { } // HasPublicShareRole return true if the user has a public share role. -// If yes, the string is the type of role, viewer, editor or uploader +// If yes, the string is the type of role, viewer, editor or uploader. func HasPublicShareRole(u *userpb.User) (string, bool) { if u.Opaque == nil { return "", false @@ -371,7 +371,7 @@ func HasPublicShareRole(u *userpb.User) (string, bool) { } // HasPermissions returns true if all permissions defined in the stuict toCheck -// are set in the target +// are set in the target. func HasPermissions(target, toCheck *provider.ResourcePermissions) bool { targetStruct := reflect.ValueOf(target).Elem() toCheckStruct := reflect.ValueOf(toCheck).Elem() @@ -386,7 +386,7 @@ func HasPermissions(target, toCheck *provider.ResourcePermissions) bool { } // UserIsLightweight returns true if the user is a lightweith -// or federated account +// or federated account. func UserIsLightweight(u *userpb.User) bool { return u.Id.Type == userpb.UserType_USER_TYPE_FEDERATED || u.Id.Type == userpb.UserType_USER_TYPE_LIGHTWEIGHT diff --git a/tests/helpers/helpers.go b/tests/helpers/helpers.go index b8ff8077d13..92dc4271af6 100644 --- a/tests/helpers/helpers.go +++ b/tests/helpers/helpers.go @@ -37,7 +37,10 @@ import ( // /tmp directories are often tmpfs mounts which do not support user // extended attributes. func TempDir(name string) (string, error) { - _, currentFileName, _, _ := runtime.Caller(0) + _, currentFileName, _, ok := runtime.Caller(0) + if !ok { + return "nil", errors.New("failed to retrieve currentFileName") + } tmpDir := filepath.Join(filepath.Dir(currentFileName), "../../tmp") err := os.MkdirAll(tmpDir, 0755) if err != nil { @@ -51,7 +54,7 @@ func TempDir(name string) (string, error) { return tmpRoot, nil } -// Upload can be used to initiate an upload and do the upload to a storage.FS in one step +// Upload can be used to initiate an upload and do the upload to a storage.FS in one step. func Upload(ctx context.Context, fs storage.FS, ref *provider.Reference, content []byte) error { uploadIds, err := fs.InitiateUpload(ctx, ref, 0, map[string]string{}) if err != nil { diff --git a/tests/integration/grpc/grpc_suite_test.go b/tests/integration/grpc/grpc_suite_test.go index 60302a36fbd..fae8bbeeaf5 100644 --- a/tests/integration/grpc/grpc_suite_test.go +++ b/tests/integration/grpc/grpc_suite_test.go @@ -29,10 +29,9 @@ import ( "testing" "time" - "github.com/pkg/errors" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/pkg/errors" ) const timeoutMs = 30000 @@ -47,7 +46,7 @@ func TestGrpc(t *testing.T) { type cleanupFunc func(bool) error -// Revad represents a running revad process +// Revad represents a running revad process. type Revad struct { TmpRoot string // Temporary directory on disk. Will be cleaned up by the Cleanup func. GrpcAddress string // Address of the grpc service diff --git a/tests/integration/grpc/storageprovider_test.go b/tests/integration/grpc/storageprovider_test.go index 56553698301..91c20479de5 100644 --- a/tests/integration/grpc/storageprovider_test.go +++ b/tests/integration/grpc/storageprovider_test.go @@ -22,8 +22,6 @@ import ( "context" "os" - "google.golang.org/grpc/metadata" - userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1" storagep "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1" @@ -34,9 +32,9 @@ import ( "github.com/cs3org/reva/pkg/storage/fs/owncloud" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" "github.com/cs3org/reva/tests/helpers" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/grpc/metadata" ) // This test suite tests the gprc storageprovider interface using different diff --git a/tests/integration/grpc/userprovider_test.go b/tests/integration/grpc/userprovider_test.go index 14af27fde2c..d2cfec7ed46 100644 --- a/tests/integration/grpc/userprovider_test.go +++ b/tests/integration/grpc/userprovider_test.go @@ -27,10 +27,9 @@ import ( ctxpkg "github.com/cs3org/reva/pkg/ctx" "github.com/cs3org/reva/pkg/rgrpc/todo/pool" jwt "github.com/cs3org/reva/pkg/token/manager/jwt" - "google.golang.org/grpc/metadata" - . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "google.golang.org/grpc/metadata" ) var _ = Describe("user providers", func() { diff --git a/tools/create-artifacts/main.go b/tools/create-artifacts/main.go index 3abc1c980db..8bf4ab36fd8 100644 --- a/tools/create-artifacts/main.go +++ b/tools/create-artifacts/main.go @@ -58,7 +58,6 @@ func init() { } func main() { - if err := os.RemoveAll("dist"); err != nil { fmt.Fprintf(os.Stderr, "error removing dist folder: %s", err) os.Exit(1) diff --git a/tools/prepare-release/main.go b/tools/prepare-release/main.go index fa902a4b0ce..c9849189e2c 100644 --- a/tools/prepare-release/main.go +++ b/tools/prepare-release/main.go @@ -187,7 +187,6 @@ func add(msg string, files ...string) { cmd.Dir = "." run(cmd) } - } func createCommit(msg string) {