Enable more rigorous version of gofmt linting (#488)

* Enable a stricter linter

* Fix new lint errors
This commit is contained in:
ashmrtn 2022-08-05 13:33:20 -07:00 committed by GitHub
parent eff95b7702
commit da66cc4c2f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 106 additions and 112 deletions

View File

@ -3,9 +3,10 @@ run:
linters:
enable:
- gofmt
- misspell
- gci
- gofmt
- gofumpt
- misspell
- revive
linters-settings:

View File

@ -40,13 +40,15 @@ func handleBackupCmd(cmd *cobra.Command, args []string) error {
// The backup create subcommand.
// `corso backup create <service> [<flag>...]`
var createCommand = "create"
var createCmd = &cobra.Command{
Use: createCommand,
Short: "Backup an M365 Service",
RunE: handleCreateCmd,
Args: cobra.NoArgs,
}
var (
createCommand = "create"
createCmd = &cobra.Command{
Use: createCommand,
Short: "Backup an M365 Service",
RunE: handleCreateCmd,
Args: cobra.NoArgs,
}
)
// Handler for calls to `corso backup create`.
// Produces the same output as `corso backup create --help`.
@ -56,13 +58,15 @@ func handleCreateCmd(cmd *cobra.Command, args []string) error {
// The backup list subcommand.
// `corso backup list <service> [<flag>...]`
var listCommand = "list"
var listCmd = &cobra.Command{
Use: listCommand,
Short: "List the history of backups for a service",
RunE: handleListCmd,
Args: cobra.NoArgs,
}
var (
listCommand = "list"
listCmd = &cobra.Command{
Use: listCommand,
Short: "List the history of backups for a service",
RunE: handleListCmd,
Args: cobra.NoArgs,
}
)
// Handler for calls to `corso backup list`.
// Produces the same output as `corso backup list --help`.
@ -72,13 +76,15 @@ func handleListCmd(cmd *cobra.Command, args []string) error {
// The backup details subcommand.
// `corso backup list <service> [<flag>...]`
var detailsCommand = "details"
var detailsCmd = &cobra.Command{
Use: detailsCommand,
Short: "Shows the details of a backup for a service",
RunE: handleDetailsCmd,
Args: cobra.NoArgs,
}
var (
detailsCommand = "details"
detailsCmd = &cobra.Command{
Use: detailsCommand,
Short: "Shows the details of a backup for a service",
RunE: handleDetailsCmd,
Args: cobra.NoArgs,
}
)
// Handler for calls to `corso backup details`.
// Produces the same output as `corso backup details --help`.

View File

@ -25,7 +25,7 @@ func TestCLISuite(t *testing.T) {
func (suite *CLISuite) TestAddCommands_noPanics() {
t := suite.T()
var test = &cobra.Command{
test := &cobra.Command{
Use: "test",
Short: "Protect your Microsoft 365 data.",
Long: `Reliable, secure, and efficient data protection for Microsoft 365.`,

View File

@ -51,7 +51,7 @@ func (suite *ConfigSuite) TestReadRepoConfigBasic() {
// Generate test config file
testConfigData := fmt.Sprintf(configFileTemplate, b, tID)
testConfigFilePath := path.Join(t.TempDir(), "corso.toml")
err := ioutil.WriteFile(testConfigFilePath, []byte(testConfigData), 0700)
err := ioutil.WriteFile(testConfigFilePath, []byte(testConfigData), 0o700)
require.NoError(t, err)
// Configure viper to read test config file

View File

@ -6,9 +6,7 @@ import (
"github.com/alcionai/corso/pkg/control"
)
var (
fastFail bool
)
var fastFail bool
// AddFlags adds the operation option flags
func AddOperationFlags(parent *cobra.Command) {

View File

@ -38,14 +38,16 @@ func handleRepoCmd(cmd *cobra.Command, args []string) error {
// The repo init subcommand.
// `corso repo init <repository> [<flag>...]`
var initCommand = "init"
var initCmd = &cobra.Command{
Use: initCommand,
Short: "Initialize a repository.",
Long: `Create a new repository to store your backups.`,
RunE: handleInitCmd,
Args: cobra.NoArgs,
}
var (
initCommand = "init"
initCmd = &cobra.Command{
Use: initCommand,
Short: "Initialize a repository.",
Long: `Create a new repository to store your backups.`,
RunE: handleInitCmd,
Args: cobra.NoArgs,
}
)
// Handler for calls to `corso repo init`.
func handleInitCmd(cmd *cobra.Command, args []string) error {
@ -54,14 +56,16 @@ func handleInitCmd(cmd *cobra.Command, args []string) error {
// The repo connect subcommand.
// `corso repo connect <repository> [<flag>...]`
var connectCommand = "connect"
var connectCmd = &cobra.Command{
Use: connectCommand,
Short: "Connect to a repository.",
Long: `Connect to an existing repository.`,
RunE: handleConnectCmd,
Args: cobra.NoArgs,
}
var (
connectCommand = "connect"
connectCmd = &cobra.Command{
Use: connectCommand,
Short: "Connect to a repository.",
Long: `Connect to an existing repository.`,
RunE: handleConnectCmd,
Args: cobra.NoArgs,
}
)
// Handler for calls to `corso repo connect`.
func handleConnectCmd(cmd *cobra.Command, args []string) error {

View File

@ -12,12 +12,10 @@ import (
"github.com/alcionai/corso/cli"
)
var (
// generate markdown files in the given.
// callers of this func can then migrate the files
// to where they need.
cliMarkdownDir string
)
// generate markdown files in the given.
// callers of this func can then migrate the files
// to where they need.
var cliMarkdownDir string
// The root-level command.
// `corso <command> [<subcommand>] [<service>] [<flag>...]`

View File

@ -22,6 +22,7 @@ type Err struct {
func EncapsulateError(e error) *Err {
return &Err{Err: e}
}
func (e Err) Error() string {
return e.Err.Error()
}

View File

@ -20,9 +20,11 @@ import (
"github.com/alcionai/corso/pkg/logger"
)
var _ data.Collection = &Collection{}
var _ data.Stream = &Stream{}
var _ data.StreamInfo = &Stream{}
var (
_ data.Collection = &Collection{}
_ data.Stream = &Stream{}
_ data.StreamInfo = &Stream{}
)
const (
collectionChannelBufferSize = 1000
@ -47,7 +49,7 @@ type Collection struct {
populate populater
statusCh chan<- *support.ConnectorOperationStatus
// FullPath is the slice representation of the action context passed down through the hierarchy.
//The original request can be gleaned from the slice. (e.g. {<tenant ID>, <user ID>, "emails"})
// The original request can be gleaned from the slice. (e.g. {<tenant ID>, <user ID>, "emails"})
fullPath []string
}
@ -288,12 +290,11 @@ type Stream struct {
// going forward. Using []byte for now but I assume we'll have
// some structured type in here (serialization to []byte can be done in `Read`)
message []byte
info *details.ExchangeInfo //temporary change to bring populate function into directory
info *details.ExchangeInfo // temporary change to bring populate function into directory
}
func (od *Stream) UUID() string {
return od.id
}
func (od *Stream) ToReader() io.ReadCloser {
@ -311,5 +312,4 @@ func NewStream(identifier string, dataBytes []byte, detail details.ExchangeInfo)
message: dataBytes,
info: &detail,
}
}

View File

@ -47,6 +47,7 @@ func (suite *ExchangeDataCollectionSuite) TestExchangeDataReader_Empty() {
suite.Equal(expected, received)
assert.Nil(suite.T(), err, "received buf.Readfrom error ")
}
func (suite *ExchangeDataCollectionSuite) TestExchangeData_FullPath() {
user := "a-user"
fullPath := []string{"a-tenant", user, "emails"}
@ -80,7 +81,6 @@ func (suite *ExchangeDataCollectionSuite) TestExchangeCollection_AddJob() {
eoc.AddJob(item)
}
suite.Equal(len(shopping), len(eoc.jobs))
}
// TestExchangeCollection_Items() tests for the Collection.Items() ability
@ -92,7 +92,8 @@ func (suite *ExchangeDataCollectionSuite) TestExchangeCollection_Items() {
user string,
jobs []string,
dataChannel chan<- data.Stream,
notUsed chan<- *support.ConnectorOperationStatus) {
notUsed chan<- *support.ConnectorOperationStatus,
) {
detail := &details.ExchangeInfo{Sender: "foo@bar.com", Subject: "Hello world!", Received: time.Now()}
for i := 0; i < expected; i++ {
temp := NewStream(uuid.NewString(), mockconnector.GetMockMessageBytes("Test_Items()"), *detail)

View File

@ -91,9 +91,7 @@ func (suite *ExchangeServiceSuite) TestExchangeService_optionsForFolders() {
suite.Equal(test.expected, len(config.QueryParameters.Select))
}
})
}
}
// NOTE the requirements are in PR 475

View File

@ -76,7 +76,8 @@ func (suite *MessageSuite) TestMessageInfo() {
msg.SetReceivedDateTime(&now)
return msg, &details.ExchangeInfo{Sender: sender, Subject: subject, Received: now}
},
}}
},
}
for _, tt := range tests {
suite.T().Run(tt.name, func(t *testing.T) {
msg, expected := tt.msgAndRP()

View File

@ -169,8 +169,8 @@ func GetMailFolderID(service graph.Service, folderName, user string) (*string, e
} else if folderID == nil {
return nil, ErrFolderNotFound
}
return folderID, errs
return folderID, errs
}
// SetupExchangeCollectionVars is a helper function returns a sets
@ -183,24 +183,25 @@ func SetupExchangeCollectionVars(scope selectors.ExchangeScope) (
) {
if scope.IncludesCategory(selectors.ExchangeMail) {
if scope.IsAny(selectors.ExchangeMailFolder) {
return models.CreateMessageCollectionResponseFromDiscriminatorValue,
GetAllMessagesForUser,
IterateSelectAllMessagesForCollections,
nil
}
return models.CreateMessageCollectionResponseFromDiscriminatorValue,
GetAllMessagesForUser,
IterateAndFilterMessagesForCollections,
nil
}
if scope.IncludesCategory(selectors.ExchangeContactFolder) {
return models.CreateContactFromDiscriminatorValue,
GetAllContactsForUser,
IterateAllContactsForCollection,
nil
}
return nil, nil, nil, errors.New("exchange scope option not supported")
}
@ -220,8 +221,8 @@ func GetCopyRestoreFolder(service graph.Service, user string) (*string, error) {
}
return nil, err
}
return isFolder, nil
}
@ -264,7 +265,6 @@ func RestoreMailMessage(
fallthrough
case control.Copy:
return SendMailToBackStore(service, user, destination, clone)
}
}
@ -281,5 +281,4 @@ func SendMailToBackStore(service graph.Service, user, destination string, messag
return errors.New("message not Sent: blocked by server")
}
return nil
}

View File

@ -36,17 +36,18 @@ const (
// GraphQuery represents functions which perform exchange-specific queries
// into M365 backstore.
//TODO: use selector or path for granularity into specific folders or specific date ranges
// TODO: use selector or path for granularity into specific folders or specific date ranges
type GraphQuery func(graph.Service, string) (absser.Parsable, error)
// GetAllMessagesForUser is a GraphQuery function for receiving all messages for a single user
func GetAllMessagesForUser(gs graph.Service, user string) (absser.Parsable, error) {
selecting := []string{"id", "parentFolderId"}
options, err := optionsForMessages(selecting)
options, err := optionsForMessages(selecting)
if err != nil {
return nil, err
}
return gs.Client().UsersById(user).Messages().GetWithRequestConfigurationAndResponseHandler(options, nil)
}
@ -57,21 +58,19 @@ func GetAllContactsForUser(gs graph.Service, user string) (absser.Parsable, erro
if err != nil {
return nil, err
}
return gs.Client().UsersById(user).Contacts().GetWithRequestConfigurationAndResponseHandler(options, nil)
return gs.Client().UsersById(user).Contacts().GetWithRequestConfigurationAndResponseHandler(options, nil)
}
// GetAllFolderDisplayNamesForUser is a GraphQuery function for getting FolderId and display
// names for Mail Folder. All other information for the MailFolder object is omitted.
func GetAllFolderNamesForUser(gs graph.Service, identities []string) (absser.Parsable, error) {
options, err := optionsForMailFolders([]string{"id", "displayName"})
if err != nil {
return nil, err
}
return gs.Client().UsersById(identities[0]).MailFolders().GetWithRequestConfigurationAndResponseHandler(options, nil)
}
// GraphIterateFuncs are iterate functions to be used with the M365 iterators (e.g. msgraphgocore.NewPageIterator)
@ -144,7 +143,6 @@ func IterateAllContactsForCollection(
statusCh chan<- *support.ConnectorOperationStatus,
) func(any) bool {
return func(contactsItem any) bool {
user := scope.Get(selectors.ExchangeUser)[0]
contact, ok := contactsItem.(models.Contactable)
@ -215,7 +213,6 @@ func IterateAndFilterMessagesForCollections(
}
collections[directory].AddJob(*message.GetId())
return true
}
}
@ -287,7 +284,6 @@ func CollectMailFolders(
err = support.WrapAndAppend(user+" iterate failure", iterateFailure, err)
}
return err
}
//---------------------------------------------------

View File

@ -35,7 +35,7 @@ const (
type GraphConnector struct {
graphService
tenant string
Users map[string]string //key<email> value<id>
Users map[string]string // key<email> value<id>
status *support.ConnectorOperationStatus // contains the status of the last run status
statusCh chan *support.ConnectorOperationStatus
awaitingMessages int32

View File

@ -28,7 +28,6 @@ func TestDisconnectedGraphSuite(t *testing.T) {
}
func (suite *DisconnectedGraphConnectorSuite) TestBadConnection() {
table := []struct {
name string
acct func(t *testing.T) account.Account
@ -81,7 +80,6 @@ func (suite *DisconnectedGraphConnectorSuite) TestBuild() {
suite.Contains(last, "Bundy")
suite.Contains(last, "Ripley")
suite.Contains(last, "Foley")
}
func (suite *DisconnectedGraphConnectorSuite) TestInterfaceAlignment() {
@ -89,7 +87,6 @@ func (suite *DisconnectedGraphConnectorSuite) TestInterfaceAlignment() {
concrete := mockconnector.NewMockExchangeCollection([]string{"a", "path"}, 1)
dc = concrete
assert.NotNil(suite.T(), dc)
}
func (suite *DisconnectedGraphConnectorSuite) TestGraphConnector_Status() {
@ -110,6 +107,7 @@ func (suite *DisconnectedGraphConnectorSuite) TestGraphConnector_Status() {
suite.Greater(len(gc.PrintableStatus()), 0)
suite.Greater(gc.Status().ObjectCount, 0)
}
func (suite *DisconnectedGraphConnectorSuite) TestGraphConnector_ErrorChecking() {
tests := []struct {
name string
@ -129,7 +127,8 @@ func (suite *DisconnectedGraphConnectorSuite) TestGraphConnector_ErrorChecking()
returnRecoverable: assert.True,
returnNonRecoverable: assert.False,
},
{name: "Validate NonRecoverable",
{
name: "Validate NonRecoverable",
err: support.SetNonRecoverableError(errors.New("Non-recoverable")),
returnRecoverable: assert.False,
returnNonRecoverable: assert.True,

View File

@ -164,7 +164,7 @@ func (suite *GraphConnectorIntegrationSuite) TestGraphConnector_TestContactSeque
suite.Greater(len(collections), 0)
}
//TestGraphConnector_restoreMessages uses mock data to ensure GraphConnector
// TestGraphConnector_restoreMessages uses mock data to ensure GraphConnector
// is able to restore a messageable item to a Mailbox.
func (suite *GraphConnectorIntegrationSuite) TestGraphConnector_restoreMessages() {
user := "TEST_GRAPH_USER" // user.GetId()

View File

@ -88,7 +88,6 @@ func (med *MockExchangeData) Info() details.ItemInfo {
// GetMockMessageBytes returns bytes for Messageable item.
// Contents verified as working with sample data from kiota-serialization-json-go v0.5.5
func GetMockMessageBytes(subject string) []byte {
userID, err := tester.M365UserID()
if err != nil {
userID = "lidiah@8qzvrj.onmicrosoft.com"

View File

@ -39,14 +39,12 @@ func (suite *MockExchangeCollectionSuite) TestMockExchangeCollection() {
func (suite *MockExchangeCollectionSuite) TestMockExchangeCollection_NewExchangeCollectionMail_Hydration() {
t := suite.T()
mdc := mockconnector.NewMockExchangeCollection([]string{"foo", "bar"}, 3)
var (
byteArray []byte
)
buf := &bytes.Buffer{}
for stream := range mdc.Items() {
_, err := buf.ReadFrom(stream.ToReader())
assert.NoError(t, err)
byteArray = buf.Bytes()
byteArray := buf.Bytes()
something, err := support.CreateFromBytes(byteArray, models.CreateMessageFromDiscriminatorValue)
assert.NoError(t, err)
assert.NotNil(t, something)

View File

@ -60,7 +60,6 @@ func (suite *GraphConnectorErrorSuite) TestWrapAndAppend_Add3() {
suite.True(strings.Contains(combined.Error(), "unix36"))
suite.True(strings.Contains(combined.Error(), "user1"))
suite.True(strings.Contains(allErrors.Error(), "fxi92874"))
}
func (suite *GraphConnectorErrorSuite) TestWrapAndAppendf() {

View File

@ -23,7 +23,6 @@ func CreateFromBytes(bytes []byte, createFunc absser.ParsableFactory) (absser.Pa
// CreateMessageFromBytes function to transform bytes into Messageable object
func CreateMessageFromBytes(bytes []byte) (models.Messageable, error) {
aMessage, err := CreateFromBytes(bytes, models.CreateMessageFromDiscriminatorValue)
if err != nil {
return nil, err

View File

@ -9,8 +9,10 @@ import (
"github.com/pkg/errors"
)
var eventResponsableFields = []string{"responseType"}
var eventRequestableFields = []string{"allowNewTimeProposals", "meetingRequestType", "responseRequested"}
var (
eventResponsableFields = []string{"responseType"}
eventRequestableFields = []string{"allowNewTimeProposals", "meetingRequestType", "responseRequested"}
)
func CloneMessageableFields(orig, message models.Messageable) models.Messageable {
message.SetSubject(orig.GetSubject())
@ -92,7 +94,6 @@ func SetEventMessageResponse(orig models.Messageable, adtl map[string]any) (mode
newMessage, err := SetAdditionalDataToEventMessage(adtl, message)
if err != nil {
return nil, errors.Wrap(err, *orig.GetId()+" eventMessageResponse could not set additional data")
}
message, ok = newMessage.(models.EventMessageResponseable)
if !ok {
@ -117,7 +118,6 @@ func SetEventMessageResponse(orig models.Messageable, adtl map[string]any) (mode
default:
return nil, errors.New(key + " not supported for setEventMessageResponse")
}
}
return message, nil
}
@ -180,8 +180,10 @@ func buildMapFromAdditional(list []string, adtl map[string]any) (map[string]*str
return returnMap, nil
}
func setEventRequestableFields(em models.EventMessageRequestable, adtl map[string]*string) (models.EventMessageRequestable, error) {
func setEventRequestableFields(
em models.EventMessageRequestable,
adtl map[string]*string,
) (models.EventMessageRequestable, error) {
for key, value := range adtl {
switch key {
case "meetingRequestType":
@ -192,7 +194,6 @@ func setEventRequestableFields(em models.EventMessageRequestable, adtl map[strin
rType, ok := temp.(*models.MeetingRequestType)
if !ok {
return nil, errors.New(*em.GetId() + ": failed to set meeting request type")
}
em.SetMeetingRequestType(rType)
case "responseRequested":

View File

@ -40,5 +40,4 @@ func (suite *SupportTestSuite) TestToMessage() {
suite.Equal(message.GetSender(), clone.GetSender())
suite.Equal(message.GetSentDateTime(), clone.GetSentDateTime())
suite.NotEqual(message.GetId(), clone.GetId())
}

View File

@ -56,7 +56,6 @@ func (suite *GCStatusTestSuite) TestCreateStatus() {
test.params.err)
test.expect(t, result.incomplete, "status is incomplete")
})
}
}

View File

@ -6,8 +6,10 @@ import (
"github.com/alcionai/corso/internal/data"
)
var _ data.Collection = &kopiaDataCollection{}
var _ data.Stream = &kopiaDataStream{}
var (
_ data.Collection = &kopiaDataCollection{}
_ data.Stream = &kopiaDataStream{}
)
type kopiaDataCollection struct {
path []string

View File

@ -38,6 +38,7 @@ type ModelStoreUnitSuite struct {
func TestModelStoreUnitSuite(t *testing.T) {
suite.Run(t, new(ModelStoreUnitSuite))
}
func (suite *ModelStoreUnitSuite) TestCloseWithoutInitDoesNotPanic() {
assert.NotPanics(suite.T(), func() {
m := &ModelStore{}

View File

@ -300,7 +300,6 @@ func (w Wrapper) makeSnapshotWithRoot(
return nil
},
)
// Telling kopia to always flush may hide other errors if it fails while
// flushing the write session (hence logging above).
if err != nil {
@ -461,7 +460,6 @@ func walkDirectory(
return nil
})
if err != nil {
// If the iterator itself had an error add it to the list.
errs = multierror.Append(errs, errors.Wrap(err, "getting directory data"))

View File

@ -46,12 +46,10 @@ const (
pathSeparator = '/'
)
var (
charactersToEscape = map[rune]struct{}{
pathSeparator: {},
escapeCharacter: {},
}
)
var charactersToEscape = map[rune]struct{}{
pathSeparator: {},
escapeCharacter: {},
}
var errMissingSegment = errors.New("missing required path segment")

View File

@ -12,9 +12,7 @@ const (
user = "me@my.onmicrosoft.com"
)
var (
dataType = ExchangeEvent.String()
)
var dataType = ExchangeEvent.String()
func stubScope() map[string]string {
return map[string]string{
@ -86,7 +84,8 @@ func (suite *SelectorSuite) TestPrintable_IncludedResources() {
sel.Includes = []map[string]string{
stubScope(),
{scopeKeyResource: "smarf", scopeKeyDataType: dataType},
{scopeKeyResource: "smurf", scopeKeyDataType: dataType}}
{scopeKeyResource: "smurf", scopeKeyDataType: dataType},
}
p = sel.Printable()
res = p.Resources()