Use ptr package where possible (#2773)

Few minor logic updates and remove a duplicate bit of code/test

---

#### Does this PR need a docs update or release note?

- [ ]  Yes, it's included
- [ ] 🕐 Yes, but in a later PR
- [x]  No

#### Type of change

- [ ] 🌻 Feature
- [ ] 🐛 Bugfix
- [ ] 🗺️ Documentation
- [ ] 🤖 Test
- [ ] 💻 CI/Deployment
- [x] 🧹 Tech Debt/Cleanup

#### Issue(s)

* closes #2474

#### Test Plan

- [ ] 💪 Manual
- [x]  Unit test
- [ ] 💚 E2E
This commit is contained in:
ashmrtn 2023-03-14 08:39:25 -07:00 committed by GitHub
parent b8e2c25d03
commit eb6d6f59cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 199 additions and 222 deletions

View File

@ -135,8 +135,11 @@ func checkIDAndName(c graph.Container) error {
} }
func HasAttachments(body models.ItemBodyable) bool { func HasAttachments(body models.ItemBodyable) bool {
if body.GetContent() == nil || body.GetContentType() == nil || if ct, ok := ptr.ValOK(body.GetContentType()); !ok || ct == models.TEXT_BODYTYPE {
*body.GetContentType() == models.TEXT_BODYTYPE || len(*body.GetContent()) == 0 { return false
}
if body, ok := ptr.ValOK(body.GetContent()); !ok || len(body) == 0 {
return false return false
} }

View File

@ -108,7 +108,7 @@ func (c Events) GetItem(
return nil, nil, graph.Stack(ctx, err) return nil, nil, graph.Stack(ctx, err)
} }
if *event.GetHasAttachments() || HasAttachments(event.GetBody()) { if ptr.Val(event.GetHasAttachments()) || HasAttachments(event.GetBody()) {
options := &users.ItemEventsItemAttachmentsRequestBuilderGetRequestConfiguration{ options := &users.ItemEventsItemAttachmentsRequestBuilderGetRequestConfiguration{
QueryParameters: &users.ItemEventsItemAttachmentsRequestBuilderGetQueryParameters{ QueryParameters: &users.ItemEventsItemAttachmentsRequestBuilderGetQueryParameters{
Expand: []string{"microsoft.graph.itemattachment/item"}, Expand: []string{"microsoft.graph.itemattachment/item"},

View File

@ -131,7 +131,7 @@ func (c Mail) GetItem(
return nil, nil, graph.Stack(ctx, err) return nil, nil, graph.Stack(ctx, err)
} }
if *mail.GetHasAttachments() || HasAttachments(mail.GetBody()) { if ptr.Val(mail.GetHasAttachments()) || HasAttachments(mail.GetBody()) {
options := &users.ItemMessagesItemAttachmentsRequestBuilderGetRequestConfiguration{ options := &users.ItemMessagesItemAttachmentsRequestBuilderGetRequestConfiguration{
QueryParameters: &users.ItemMessagesItemAttachmentsRequestBuilderGetQueryParameters{ QueryParameters: &users.ItemMessagesItemAttachmentsRequestBuilderGetQueryParameters{
Expand: []string{"microsoft.graph.itemattachment/item"}, Expand: []string{"microsoft.graph.itemattachment/item"},

View File

@ -126,6 +126,9 @@ func getItemAttachmentItemType(query models.Attachmentable) string {
} }
item := attachment.GetItem() item := attachment.GetItem()
if item == nil {
return empty
}
return ptr.Val(item.GetOdataType()) return ptr.Val(item.GetOdataType())
} }

View File

@ -7,6 +7,7 @@ import (
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/pkg/fault" "github.com/alcionai/corso/src/pkg/fault"
"github.com/alcionai/corso/src/pkg/path" "github.com/alcionai/corso/src/pkg/path"
@ -81,14 +82,18 @@ func (cr *containerResolver) idToPath(
return p, c.Location(), nil return p, c.Location(), nil
} }
parentPath, parentLoc, err := cr.idToPath(ctx, *c.GetParentFolderId(), depth+1, useIDInPath) parentPath, parentLoc, err := cr.idToPath(
ctx,
ptr.Val(c.GetParentFolderId()),
depth+1,
useIDInPath)
if err != nil { if err != nil {
return nil, nil, errors.Wrap(err, "retrieving parent folder") return nil, nil, errors.Wrap(err, "retrieving parent folder")
} }
toAppend := *c.GetDisplayName() toAppend := ptr.Val(c.GetDisplayName())
if useIDInPath { if useIDInPath {
toAppend = *c.GetId() toAppend = ptr.Val(c.GetId())
} }
fullPath := parentPath.Append(toAppend) fullPath := parentPath.Append(toAppend)
@ -97,7 +102,7 @@ func (cr *containerResolver) idToPath(
var locPath *path.Builder var locPath *path.Builder
if parentLoc != nil { if parentLoc != nil {
locPath = parentLoc.Append(*c.GetDisplayName()) locPath = parentLoc.Append(ptr.Val(c.GetDisplayName()))
c.SetLocation(locPath) c.SetLocation(locPath)
} }
@ -118,7 +123,7 @@ func (cr *containerResolver) PathInCache(pathString string) (string, bool) {
} }
if cc.Path().String() == pathString { if cc.Path().String() == pathString {
return *cc.GetId(), true return ptr.Val(cc.GetId()), true
} }
} }
@ -139,11 +144,11 @@ func (cr *containerResolver) addFolder(cf graph.CacheFolder) error {
} }
} }
if _, ok := cr.cache[*cf.GetId()]; ok { if _, ok := cr.cache[ptr.Val(cf.GetId())]; ok {
return nil return nil
} }
cr.cache[*cf.GetId()] = &cf cr.cache[ptr.Val(cf.GetId())] = &cf
return nil return nil
} }
@ -174,7 +179,7 @@ func (cr *containerResolver) AddToCache(
// Populate the path for this entry so calls to PathInCache succeed no matter // Populate the path for this entry so calls to PathInCache succeed no matter
// when they're made. // when they're made.
_, _, err := cr.IDToPath(ctx, *f.GetId(), useIDInPath) _, _, err := cr.IDToPath(ctx, ptr.Val(f.GetId()), useIDInPath)
if err != nil { if err != nil {
return errors.Wrap(err, "adding cache entry") return errors.Wrap(err, "adding cache entry")
} }
@ -193,7 +198,7 @@ func (cr *containerResolver) populatePaths(ctx context.Context, useIDInPath bool
// Populate all folder paths. // Populate all folder paths.
for _, f := range cr.Items() { for _, f := range cr.Items() {
_, _, err := cr.IDToPath(ctx, *f.GetId(), useIDInPath) _, _, err := cr.IDToPath(ctx, ptr.Val(f.GetId()), useIDInPath)
if err != nil { if err != nil {
errs = multierror.Append(errs, errors.Wrap(err, "populating path")) errs = multierror.Append(errs, errors.Wrap(err, "populating path"))
} }

View File

@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
"github.com/alcionai/corso/src/pkg/account" "github.com/alcionai/corso/src/pkg/account"
@ -387,7 +388,7 @@ func (suite *ConfiguredFolderCacheUnitSuite) TestLookupCachedFolderNoPathsCached
defer flush() defer flush()
for _, c := range suite.allContainers { for _, c := range suite.allContainers {
suite.Run(*c.GetDisplayName(), func() { suite.Run(ptr.Val(c.GetDisplayName()), func() {
t := suite.T() t := suite.T()
p, l, err := suite.fc.IDToPath(ctx, c.id, false) p, l, err := suite.fc.IDToPath(ctx, c.id, false)
@ -403,7 +404,7 @@ func (suite *ConfiguredFolderCacheUnitSuite) TestLookupCachedFolderNoPathsCached
defer flush() defer flush()
for _, c := range suite.containersWithID { for _, c := range suite.containersWithID {
suite.Run(*c.GetDisplayName(), func() { suite.Run(ptr.Val(c.GetDisplayName()), func() {
t := suite.T() t := suite.T()
p, l, err := suite.fcWithID.IDToPath(ctx, c.id, true) p, l, err := suite.fcWithID.IDToPath(ctx, c.id, true)

View File

@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/support" "github.com/alcionai/corso/src/internal/connector/support"
@ -553,12 +554,12 @@ func (suite *DataCollectionsIntegrationSuite) TestEventsSerializationRegression(
) )
fn := func(gcf graph.CacheFolder) error { fn := func(gcf graph.CacheFolder) error {
if *gcf.GetDisplayName() == DefaultCalendar { if ptr.Val(gcf.GetDisplayName()) == DefaultCalendar {
calID = *gcf.GetId() calID = ptr.Val(gcf.GetId())
} }
if *gcf.GetDisplayName() == "Birthdays" { if ptr.Val(gcf.GetDisplayName()) == "Birthdays" {
bdayID = *gcf.GetId() bdayID = ptr.Val(gcf.GetId())
} }
return nil return nil

View File

@ -6,6 +6,7 @@ import (
"github.com/alcionai/clues" "github.com/alcionai/clues"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/pkg/fault" "github.com/alcionai/corso/src/pkg/fault"
"github.com/alcionai/corso/src/pkg/path" "github.com/alcionai/corso/src/pkg/path"
@ -48,8 +49,8 @@ func (ecc *eventCalendarCache) populateEventRoot(ctx context.Context) error {
temp := graph.NewCacheFolder( temp := graph.NewCacheFolder(
f, f,
path.Builder{}.Append(*f.GetId()), // storage path path.Builder{}.Append(ptr.Val(f.GetId())), // storage path
path.Builder{}.Append(*f.GetDisplayName())) // display location path.Builder{}.Append(ptr.Val(f.GetDisplayName()))) // display location
if err := ecc.addFolder(temp); err != nil { if err := ecc.addFolder(temp); err != nil {
return clues.Wrap(err, "initializing calendar resolver").WithClues(ctx) return clues.Wrap(err, "initializing calendar resolver").WithClues(ctx)
} }
@ -96,25 +97,25 @@ func (ecc *eventCalendarCache) AddToCache(ctx context.Context, f graph.Container
temp := graph.NewCacheFolder( temp := graph.NewCacheFolder(
f, f,
path.Builder{}.Append(*f.GetId()), // storage path path.Builder{}.Append(ptr.Val(f.GetId())), // storage path
path.Builder{}.Append(*f.GetDisplayName())) // display location path.Builder{}.Append(ptr.Val(f.GetDisplayName()))) // display location
if len(ecc.newAdditions) == 0 { if len(ecc.newAdditions) == 0 {
ecc.newAdditions = map[string]string{} ecc.newAdditions = map[string]string{}
} }
ecc.newAdditions[*f.GetDisplayName()] = *f.GetId() ecc.newAdditions[ptr.Val(f.GetDisplayName())] = ptr.Val(f.GetId())
if err := ecc.addFolder(temp); err != nil { if err := ecc.addFolder(temp); err != nil {
delete(ecc.newAdditions, *f.GetDisplayName()) delete(ecc.newAdditions, ptr.Val(f.GetDisplayName()))
return clues.Wrap(err, "adding container").WithClues(ctx) return clues.Wrap(err, "adding container").WithClues(ctx)
} }
// Populate the path for this entry so calls to PathInCache succeed no matter // Populate the path for this entry so calls to PathInCache succeed no matter
// when they're made. // when they're made.
_, _, err := ecc.IDToPath(ctx, *f.GetId(), true) _, _, err := ecc.IDToPath(ctx, ptr.Val(f.GetId()), true)
if err != nil { if err != nil {
delete(ecc.newAdditions, *f.GetDisplayName()) delete(ecc.newAdditions, ptr.Val(f.GetDisplayName()))
return errors.Wrap(err, "setting path to container id") return errors.Wrap(err, "setting path to container id")
} }

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
@ -72,7 +73,7 @@ func (suite *CacheResolverSuite) TestPopulate() {
}{ }{
{ {
name: "Default Event Cache", name: "Default Event Cache",
folderInCache: *cal.GetId(), folderInCache: ptr.Val(cal.GetId()),
root: DefaultCalendar, root: DefaultCalendar,
basePath: DefaultCalendar, basePath: DefaultCalendar,
resolverFunc: eventFunc, resolverFunc: eventFunc,

View File

@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common" "github.com/alcionai/corso/src/internal/common"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/mockconnector" "github.com/alcionai/corso/src/internal/connector/mockconnector"
@ -73,7 +74,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreContact() {
aFolder, err := suite.ac.Contacts().CreateContactFolder(ctx, userID, folderName) aFolder, err := suite.ac.Contacts().CreateContactFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
folderID := *aFolder.GetId() folderID := ptr.Val(aFolder.GetId())
defer func() { defer func() {
// Remove the folder containing contact prior to exiting test // Remove the folder containing contact prior to exiting test
@ -107,7 +108,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreEvent() {
calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, name) calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, name)
require.NoError(t, err) require.NoError(t, err)
calendarID := *calendar.GetId() calendarID := ptr.Val(calendar.GetId())
defer func() { defer func() {
// Removes calendar containing events created during the test // Removes calendar containing events created during the test
@ -163,7 +164,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -175,7 +176,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -187,7 +188,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -199,7 +200,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -214,7 +215,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -229,7 +230,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -244,7 +245,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ // Restore will upload the Message without uploading the attachment { // Restore will upload the Message without uploading the attachment
@ -256,7 +257,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -268,7 +269,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -280,7 +281,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -292,7 +293,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName) folder, err := suite.ac.Mail().CreateMailFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
// TODO: #884 - reinstate when able to specify root folder by name // TODO: #884 - reinstate when able to specify root folder by name
@ -305,7 +306,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
folder, err := suite.ac.Contacts().CreateContactFolder(ctx, userID, folderName) folder, err := suite.ac.Contacts().CreateContactFolder(ctx, userID, folderName)
require.NoError(t, err) require.NoError(t, err)
return *folder.GetId() return ptr.Val(folder.GetId())
}, },
}, },
{ {
@ -317,7 +318,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, calendarName) calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, calendarName)
require.NoError(t, err) require.NoError(t, err)
return *calendar.GetId() return ptr.Val(calendar.GetId())
}, },
}, },
{ {
@ -329,7 +330,7 @@ func (suite *ExchangeRestoreSuite) TestRestoreExchangeObject() {
calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, calendarName) calendar, err := suite.ac.Events().CreateCalendar(ctx, userID, calendarName)
require.NoError(t, err) require.NoError(t, err)
return *calendar.GetId() return ptr.Val(calendar.GetId())
}, },
}, },
} }

View File

@ -6,6 +6,7 @@ import (
"github.com/alcionai/clues" "github.com/alcionai/clues"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/pkg/account" "github.com/alcionai/corso/src/pkg/account"
@ -106,7 +107,7 @@ func includeContainer(
) )
// Clause ensures that DefaultContactFolder is inspected properly // Clause ensures that DefaultContactFolder is inspected properly
if category == path.ContactsCategory && *c.GetDisplayName() == DefaultContactFolder { if category == path.ContactsCategory && ptr.Val(c.GetDisplayName()) == DefaultContactFolder {
pb = pb.Append(DefaultContactFolder) pb = pb.Append(DefaultContactFolder)
if loc != nil { if loc != nil {

View File

@ -6,6 +6,7 @@ import (
"github.com/alcionai/clues" "github.com/alcionai/clues"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/support" "github.com/alcionai/corso/src/internal/connector/support"
@ -75,7 +76,7 @@ func filterContainersAndFillCollections(
return el.Failure() return el.Failure()
} }
cID := *c.GetId() cID := ptr.Val(c.GetId())
delete(tombstones, cID) delete(tombstones, cID)
currPath, locPath, ok := includeContainer(qp, c, scope) currPath, locPath, ok := includeContainer(qp, c, scope)

View File

@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/exchange/api" "github.com/alcionai/corso/src/internal/connector/exchange/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/support" "github.com/alcionai/corso/src/internal/connector/support"
@ -82,7 +83,7 @@ func (m mockResolver) AddToCache(ctx context.Context, gc graph.Container, b bool
m.added = map[string]string{} m.added = map[string]string{}
} }
m.added[*gc.GetDisplayName()] = *gc.GetId() m.added[ptr.Val(gc.GetDisplayName())] = ptr.Val(gc.GetId())
return nil return nil
} }

View File

@ -117,7 +117,7 @@ func RestoreExchangeEvent(
attached []models.Attachmentable attached []models.Attachmentable
) )
if *event.GetHasAttachments() { if ptr.Val(event.GetHasAttachments()) {
attached = event.GetAttachments() attached = event.GetAttachments()
transformedEvent.SetAttachments([]models.Attachmentable{}) transformedEvent.SetAttachments([]models.Attachmentable{})
@ -136,7 +136,7 @@ func RestoreExchangeEvent(
calendarID: destination, calendarID: destination,
userID: user, userID: user,
service: service, service: service,
itemID: *response.GetId(), itemID: ptr.Val(response.GetId()),
} }
for _, attach := range attached { for _, attach := range attached {
@ -195,7 +195,7 @@ func RestoreMailMessage(
if clone.GetSentDateTime() != nil { if clone.GetSentDateTime() != nil {
sv2 := models.NewSingleValueLegacyExtendedProperty() sv2 := models.NewSingleValueLegacyExtendedProperty()
sendPropertyValue := common.FormatLegacyTime(*clone.GetSentDateTime()) sendPropertyValue := common.FormatLegacyTime(ptr.Val(clone.GetSentDateTime()))
sendPropertyTag := MailSendDateTimeOverrideProperty sendPropertyTag := MailSendDateTimeOverrideProperty
sv2.SetId(&sendPropertyTag) sv2.SetId(&sendPropertyTag)
sv2.SetValue(&sendPropertyValue) sv2.SetValue(&sendPropertyValue)
@ -205,7 +205,7 @@ func RestoreMailMessage(
if clone.GetReceivedDateTime() != nil { if clone.GetReceivedDateTime() != nil {
sv3 := models.NewSingleValueLegacyExtendedProperty() sv3 := models.NewSingleValueLegacyExtendedProperty()
recvPropertyValue := common.FormatLegacyTime(*clone.GetReceivedDateTime()) recvPropertyValue := common.FormatLegacyTime(ptr.Val(clone.GetReceivedDateTime()))
recvPropertyTag := MailReceiveDateTimeOverriveProperty recvPropertyTag := MailReceiveDateTimeOverriveProperty
sv3.SetId(&recvPropertyTag) sv3.SetId(&recvPropertyTag)
sv3.SetValue(&recvPropertyValue) sv3.SetValue(&recvPropertyValue)
@ -612,7 +612,7 @@ func establishMailRestoreLocation(
return "", err return "", err
} }
folderID = *temp.GetId() folderID = ptr.Val(temp.GetId())
// Only populate the cache if we actually had to create it. Since we set // Only populate the cache if we actually had to create it. Since we set
// newCache to false in this we'll only try to populate it once per function // newCache to false in this we'll only try to populate it once per function
@ -661,7 +661,7 @@ func establishContactsRestoreLocation(
return "", err return "", err
} }
folderID := *temp.GetId() folderID := ptr.Val(temp.GetId())
if isNewCache { if isNewCache {
if err := cfc.Populate(ctx, errs, folderID, folders[0]); err != nil { if err := cfc.Populate(ctx, errs, folderID, folders[0]); err != nil {
@ -698,7 +698,7 @@ func establishEventsRestoreLocation(
return "", err return "", err
} }
folderID := *temp.GetId() folderID := ptr.Val(temp.GetId())
if isNewCache { if isNewCache {
if err = ecc.Populate(ctx, errs, folderID, folders[0]); err != nil { if err = ecc.Populate(ctx, errs, folderID, folders[0]); err != nil {

View File

@ -17,6 +17,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/exp/maps" "golang.org/x/exp/maps"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/discovery/api" "github.com/alcionai/corso/src/internal/connector/discovery/api"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/sharepoint" "github.com/alcionai/corso/src/internal/connector/sharepoint"
@ -151,23 +152,25 @@ func identifySite(item any) (string, string, error) {
return "", "", clues.New("non-Siteable item").With("item_type", fmt.Sprintf("%T", item)) return "", "", clues.New("non-Siteable item").With("item_type", fmt.Sprintf("%T", item))
} }
id := ptr.Val(m.GetId())
url, ok := ptr.ValOK(m.GetWebUrl())
if m.GetName() == nil { if m.GetName() == nil {
// the built-in site at "https://{tenant-domain}/search" never has a name. // the built-in site at "https://{tenant-domain}/search" never has a name.
if m.GetWebUrl() != nil && strings.HasSuffix(*m.GetWebUrl(), "/search") { if ok && strings.HasSuffix(url, "/search") {
// TODO: pii siteID, on this and all following cases // TODO: pii siteID, on this and all following cases
return "", "", clues.Stack(errKnownSkippableCase).With("site_id", *m.GetId()) return "", "", clues.Stack(errKnownSkippableCase).With("site_id", id)
} }
return "", "", clues.New("site has no name").With("site_id", *m.GetId()) return "", "", clues.New("site has no name").With("site_id", id)
} }
// personal (ie: oneDrive) sites have to be filtered out server-side. // personal (ie: oneDrive) sites have to be filtered out server-side.
url := m.GetWebUrl() if ok && strings.Contains(url, personalSitePath) {
if url != nil && strings.Contains(*url, personalSitePath) { return "", "", clues.Stack(errKnownSkippableCase).With("site_id", id)
return "", "", clues.Stack(errKnownSkippableCase).With("site_id", *m.GetId())
} }
return *m.GetWebUrl(), *m.GetId(), nil return url, id, nil
} }
// GetSiteWebURLs returns the WebURLs of sharepoint sites within the tenant. // GetSiteWebURLs returns the WebURLs of sharepoint sites within the tenant.

View File

@ -626,8 +626,8 @@ func compareExchangeEmail(
return return
} }
expectedBytes, ok := expected[*itemMessage.GetSubject()] expectedBytes, ok := expected[ptr.Val(itemMessage.GetSubject())]
if !assert.True(t, ok, "unexpected item with Subject %q", *itemMessage.GetSubject()) { if !assert.True(t, ok, "unexpected item with Subject %q", ptr.Val(itemMessage.GetSubject())) {
return return
} }
@ -653,8 +653,8 @@ func compareExchangeContact(
return return
} }
expectedBytes, ok := expected[*itemContact.GetMiddleName()] expectedBytes, ok := expected[ptr.Val(itemContact.GetMiddleName())]
if !assert.True(t, ok, "unexpected item with middle name %q", *itemContact.GetMiddleName()) { if !assert.True(t, ok, "unexpected item with middle name %q", ptr.Val(itemContact.GetMiddleName())) {
return return
} }
@ -681,8 +681,8 @@ func compareExchangeEvent(
return return
} }
expectedBytes, ok := expected[*itemEvent.GetSubject()] expectedBytes, ok := expected[ptr.Val(itemEvent.GetSubject())]
if !assert.True(t, ok, "unexpected item with subject %q", *itemEvent.GetSubject()) { if !assert.True(t, ok, "unexpected item with subject %q", ptr.Val(itemEvent.GetSubject())) {
return return
} }
@ -704,7 +704,7 @@ func permissionEqual(expected onedrive.UserPermission, got onedrive.UserPermissi
if expected.Expiration != nil && if expected.Expiration != nil &&
got.Expiration != nil && got.Expiration != nil &&
!expected.Expiration.Equal(*got.Expiration) { !expected.Expiration.Equal(ptr.Val(got.Expiration)) {
return false return false
} }

View File

@ -11,6 +11,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/onedrive" "github.com/alcionai/corso/src/internal/connector/onedrive"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
@ -128,11 +129,11 @@ func (suite *GraphConnectorOneDriveIntegrationSuite) SetupSuite() {
user, err := suite.connector.Owners.Users().GetByID(ctx, suite.user) user, err := suite.connector.Owners.Users().GetByID(ctx, suite.user)
require.NoErrorf(suite.T(), err, "fetching user %s", suite.user) require.NoErrorf(suite.T(), err, "fetching user %s", suite.user)
suite.userID = *user.GetId() suite.userID = ptr.Val(user.GetId())
secondaryUser, err := suite.connector.Owners.Users().GetByID(ctx, suite.secondaryUser) secondaryUser, err := suite.connector.Owners.Users().GetByID(ctx, suite.secondaryUser)
require.NoErrorf(suite.T(), err, "fetching user %s", suite.secondaryUser) require.NoErrorf(suite.T(), err, "fetching user %s", suite.secondaryUser)
suite.secondaryUserID = *secondaryUser.GetId() suite.secondaryUserID = ptr.Val(secondaryUser.GetId())
tester.LogTimeOfTest(suite.T()) tester.LogTimeOfTest(suite.T())
} }

View File

@ -156,20 +156,20 @@ func NewCollection(
// populated. The return values denotes if the item was previously // populated. The return values denotes if the item was previously
// present or is new one. // present or is new one.
func (oc *Collection) Add(item models.DriveItemable) bool { func (oc *Collection) Add(item models.DriveItemable) bool {
_, found := oc.driveItems[*item.GetId()] _, found := oc.driveItems[ptr.Val(item.GetId())]
oc.driveItems[*item.GetId()] = item oc.driveItems[ptr.Val(item.GetId())] = item
return !found // !found = new return !found // !found = new
} }
// Remove removes a item from the collection // Remove removes a item from the collection
func (oc *Collection) Remove(item models.DriveItemable) bool { func (oc *Collection) Remove(item models.DriveItemable) bool {
_, found := oc.driveItems[*item.GetId()] _, found := oc.driveItems[ptr.Val(item.GetId())]
if !found { if !found {
return false return false
} }
delete(oc.driveItems, *item.GetId()) delete(oc.driveItems, ptr.Val(item.GetId()))
return true return true
} }

View File

@ -403,7 +403,7 @@ func GetAllFolders(
continue continue
} }
if !strings.HasPrefix(*item.GetName(), prefix) { if !strings.HasPrefix(ptr.Val(item.GetName()), prefix) {
continue continue
} }

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/alcionai/clues"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors"
@ -12,8 +13,8 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/clues"
"github.com/alcionai/corso/src/internal/common" "github.com/alcionai/corso/src/internal/common"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/connector/graph/api" "github.com/alcionai/corso/src/internal/connector/graph/api"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
@ -358,7 +359,7 @@ func (suite *OneDriveSuite) TestCreateGetDeleteFolder() {
require.NotEmpty(t, drives) require.NotEmpty(t, drives)
// TODO: Verify the intended drive // TODO: Verify the intended drive
driveID := *drives[0].GetId() driveID := ptr.Val(drives[0].GetId())
defer func() { defer func() {
for _, id := range folderIDs { for _, id := range folderIDs {
@ -410,11 +411,11 @@ func (suite *OneDriveSuite) TestCreateGetDeleteFolder() {
for _, f := range allFolders { for _, f := range allFolders {
if *f.GetName() == folderName1 || *f.GetName() == folderName2 { if ptr.Val(f.GetName()) == folderName1 || ptr.Val(f.GetName()) == folderName2 {
foundFolderIDs = append(foundFolderIDs, *f.GetId()) foundFolderIDs = append(foundFolderIDs, ptr.Val(f.GetId()))
} }
assert.True(t, strings.HasPrefix(*f.GetName(), test.prefix), "folder prefix") assert.True(t, strings.HasPrefix(ptr.Val(f.GetName()), test.prefix), "folder prefix")
} }
assert.ElementsMatch(t, folderIDs, foundFolderIDs) assert.ElementsMatch(t, folderIDs, foundFolderIDs)

View File

@ -56,7 +56,7 @@ func sharePointItemReader(
} }
dii := details.ItemInfo{ dii := details.ItemInfo{
SharePoint: sharePointItemInfo(item, *item.GetSize()), SharePoint: sharePointItemInfo(item, ptr.Val(item.GetSize())),
} }
return dii, resp.Body, nil return dii, resp.Body, nil
@ -70,7 +70,7 @@ func oneDriveItemMetaReader(
fetchPermissions bool, fetchPermissions bool,
) (io.ReadCloser, int, error) { ) (io.ReadCloser, int, error) {
meta := Metadata{ meta := Metadata{
FileName: *item.GetName(), FileName: ptr.Val(item.GetName()),
} }
if item.GetShared() == nil { if item.GetShared() == nil {
@ -139,7 +139,7 @@ func oneDriveItemReader(
} }
dii := details.ItemInfo{ dii := details.ItemInfo{
OneDrive: oneDriveItemInfo(item, *item.GetSize()), OneDrive: oneDriveItemInfo(item, ptr.Val(item.GetSize())),
} }
return dii, rc, nil return dii, rc, nil
@ -271,18 +271,18 @@ func filterUserPermissions(ctx context.Context, perms []models.Permissionable) [
entityID := "" entityID := ""
if gv2.GetUser() != nil { if gv2.GetUser() != nil {
entityID = *gv2.GetUser().GetId() entityID = ptr.Val(gv2.GetUser().GetId())
} else if gv2.GetGroup() != nil { } else if gv2.GetGroup() != nil {
entityID = *gv2.GetGroup().GetId() entityID = ptr.Val(gv2.GetGroup().GetId())
} else { } else {
// TODO Add appliction permissions when adding permissions for SharePoint // TODO Add appliction permissions when adding permissions for SharePoint
// https://devblogs.microsoft.com/microsoft365dev/controlling-app-access-on-specific-sharepoint-site-collections/ // https://devblogs.microsoft.com/microsoft365dev/controlling-app-access-on-specific-sharepoint-site-collections/
logm := logger.Ctx(ctx) logm := logger.Ctx(ctx)
if gv2.GetApplication() != nil { if gv2.GetApplication() != nil {
logm.With("application_id", *gv2.GetApplication().GetId()) logm.With("application_id", ptr.Val(gv2.GetApplication().GetId()))
} }
if gv2.GetDevice() != nil { if gv2.GetDevice() != nil {
logm.With("application_id", *gv2.GetDevice().GetId()) logm.With("application_id", ptr.Val(gv2.GetDevice().GetId()))
} }
logm.Warn("untracked permission") logm.Warn("untracked permission")
} }

View File

@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common" "github.com/alcionai/corso/src/internal/common"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
"github.com/alcionai/corso/src/pkg/fault" "github.com/alcionai/corso/src/pkg/fault"
@ -52,7 +53,7 @@ func (suite *ItemIntegrationSuite) SetupSuite() {
require.Greaterf(t, len(odDrives), 0, "user %s does not have a drive", suite.user) require.Greaterf(t, len(odDrives), 0, "user %s does not have a drive", suite.user)
// Pick the first drive // Pick the first drive
suite.userDriveID = *odDrives[0].GetId() suite.userDriveID = ptr.Val(odDrives[0].GetId())
} }
// TestItemReader is an integration test that makes a few assumptions // TestItemReader is an integration test that makes a few assumptions
@ -152,32 +153,42 @@ func (suite *ItemIntegrationSuite) TestItemWriter() {
require.NoError(t, err) require.NoError(t, err)
// Test Requirement 2: "Test Folder" should exist // Test Requirement 2: "Test Folder" should exist
folder, err := getFolder(ctx, srv, test.driveID, *root.GetId(), "Test Folder") folder, err := getFolder(ctx, srv, test.driveID, ptr.Val(root.GetId()), "Test Folder")
require.NoError(t, err) require.NoError(t, err)
newFolderName := "testfolder_" + common.FormatNow(common.SimpleTimeTesting) newFolderName := "testfolder_" + common.FormatNow(common.SimpleTimeTesting)
t.Logf("Test will create folder %s", newFolderName) t.Logf("Test will create folder %s", newFolderName)
newFolder, err := CreateItem(ctx, srv, test.driveID, *folder.GetId(), newItem(newFolderName, true)) newFolder, err := CreateItem(
ctx,
srv,
test.driveID,
ptr.Val(folder.GetId()),
newItem(newFolderName, true))
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, newFolder.GetId()) require.NotNil(t, newFolder.GetId())
newItemName := "testItem_" + common.FormatNow(common.SimpleTimeTesting) newItemName := "testItem_" + common.FormatNow(common.SimpleTimeTesting)
t.Logf("Test will create item %s", newItemName) t.Logf("Test will create item %s", newItemName)
newItem, err := CreateItem(ctx, srv, test.driveID, *newFolder.GetId(), newItem(newItemName, false)) newItem, err := CreateItem(
ctx,
srv,
test.driveID,
ptr.Val(newFolder.GetId()),
newItem(newItemName, false))
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, newItem.GetId()) require.NotNil(t, newItem.GetId())
// HACK: Leveraging this to test getFolder behavior for a file. `getFolder()` on the // HACK: Leveraging this to test getFolder behavior for a file. `getFolder()` on the
// newly created item should fail because it's a file not a folder // newly created item should fail because it's a file not a folder
_, err = getFolder(ctx, srv, test.driveID, *newFolder.GetId(), newItemName) _, err = getFolder(ctx, srv, test.driveID, ptr.Val(newFolder.GetId()), newItemName)
require.ErrorIs(t, err, errFolderNotFound) require.ErrorIs(t, err, errFolderNotFound)
// Initialize a 100KB mockDataProvider // Initialize a 100KB mockDataProvider
td, writeSize := mockDataReader(int64(100 * 1024)) td, writeSize := mockDataReader(int64(100 * 1024))
w, err := driveItemWriter(ctx, srv, test.driveID, *newItem.GetId(), writeSize) w, err := driveItemWriter(ctx, srv, test.driveID, ptr.Val(newItem.GetId()), writeSize)
require.NoError(t, err) require.NoError(t, err)
// Using a 32 KB buffer for the copy allows us to validate the // Using a 32 KB buffer for the copy allows us to validate the
@ -224,11 +235,11 @@ func (suite *ItemIntegrationSuite) TestDriveGetFolder() {
require.NoError(t, err) require.NoError(t, err)
// Lookup a folder that doesn't exist // Lookup a folder that doesn't exist
_, err = getFolder(ctx, srv, test.driveID, *root.GetId(), "FolderDoesNotExist") _, err = getFolder(ctx, srv, test.driveID, ptr.Val(root.GetId()), "FolderDoesNotExist")
require.ErrorIs(t, err, errFolderNotFound) require.ErrorIs(t, err, errFolderNotFound)
// Lookup a folder that does exist // Lookup a folder that does exist
_, err = getFolder(ctx, srv, test.driveID, *root.GetId(), "") _, err = getFolder(ctx, srv, test.driveID, ptr.Val(root.GetId()), "")
require.NoError(t, err) require.NoError(t, err)
}) })
} }

View File

@ -8,6 +8,7 @@ import (
"github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph" "github.com/alcionai/corso/src/internal/connector/graph"
"github.com/alcionai/corso/src/internal/data" "github.com/alcionai/corso/src/internal/data"
"github.com/alcionai/corso/src/internal/version" "github.com/alcionai/corso/src/internal/version"
@ -219,7 +220,7 @@ func restorePermissions(
return graph.Wrap(ctx, err, "setting permissions") return graph.Wrap(ctx, err, "setting permissions")
} }
permissionIDMappings[p.ID] = *np.GetValue()[0].GetId() permissionIDMappings[p.ID] = ptr.Val(np.GetValue()[0].GetId())
} }
return nil return nil

View File

@ -530,7 +530,7 @@ func restoreData(
} }
// Get a drive item writer // Get a drive item writer
w, err := driveItemWriter(ctx, service, driveID, *newItem.GetId(), ss.Size()) w, err := driveItemWriter(ctx, service, driveID, ptr.Val(newItem.GetId()), ss.Size())
if err != nil { if err != nil {
return "", details.ItemInfo{}, clues.Wrap(err, "creating item writer") return "", details.ItemInfo{}, clues.Wrap(err, "creating item writer")
} }
@ -555,7 +555,7 @@ func restoreData(
dii.OneDrive = oneDriveItemInfo(newItem, written) dii.OneDrive = oneDriveItemInfo(newItem, written)
} }
return *newItem.GetId(), dii, nil return ptr.Val(newItem.GetId()), dii, nil
} }
func fetchAndReadMetadata( func fetchAndReadMetadata(

View File

@ -118,7 +118,7 @@ func FetchPages(ctx context.Context, bs *discover.BetaService, siteID string) ([
for _, entry := range resp.GetValue() { for _, entry := range resp.GetValue() {
var ( var (
pid = *entry.GetId() pid = ptr.Val(entry.GetId())
temp = NameID{pid, pid} temp = NameID{pid, pid}
) )
@ -130,11 +130,12 @@ func FetchPages(ctx context.Context, bs *discover.BetaService, siteID string) ([
pages = append(pages, temp) pages = append(pages, temp)
} }
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = sites.NewItemPagesRequestBuilder(*resp.GetOdataNextLink(), bs.Client().Adapter()) builder = sites.NewItemPagesRequestBuilder(link, bs.Client().Adapter())
} }
return pages, nil return pages, nil

View File

@ -249,7 +249,7 @@ func (sc *Collection) retrieveLists(
metrics.Successes++ metrics.Successes++
sc.data <- &Item{ sc.data <- &Item{
id: *lst.GetId(), id: ptr.Val(lst.GetId()),
data: io.NopCloser(bytes.NewReader(byteArray)), data: io.NopCloser(bytes.NewReader(byteArray)),
info: sharePointListInfo(lst, size), info: sharePointListInfo(lst, size),
modTime: t, modTime: t,
@ -311,7 +311,7 @@ func (sc *Collection) retrievePages(
metrics.Bytes += size metrics.Bytes += size
metrics.Successes++ metrics.Successes++
sc.data <- &Item{ sc.data <- &Item{
id: *pg.GetId(), id: ptr.Val(pg.GetId()),
data: io.NopCloser(bytes.NewReader(byteArray)), data: io.NopCloser(bytes.NewReader(byteArray)),
info: sharePointPageInfo(pg, root, size), info: sharePointPageInfo(pg, root, size),
modTime: ptr.OrNow(pg.GetLastModifiedDateTime()), modTime: ptr.OrNow(pg.GetLastModifiedDateTime()),

View File

@ -12,6 +12,7 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common" "github.com/alcionai/corso/src/internal/common"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/mockconnector" "github.com/alcionai/corso/src/internal/connector/mockconnector"
"github.com/alcionai/corso/src/internal/connector/onedrive" "github.com/alcionai/corso/src/internal/connector/onedrive"
"github.com/alcionai/corso/src/internal/connector/sharepoint/api" "github.com/alcionai/corso/src/internal/connector/sharepoint/api"
@ -211,20 +212,20 @@ func (suite *SharePointCollectionSuite) TestListCollection_Restore() {
assert.NoError(t, err, "getting site lists") assert.NoError(t, err, "getting site lists")
for _, temp := range resp.GetValue() { for _, temp := range resp.GetValue() {
if *temp.GetDisplayName() == deets.SharePoint.ItemName { if ptr.Val(temp.GetDisplayName()) == deets.SharePoint.ItemName {
isFound = true isFound = true
deleteID = *temp.GetId() deleteID = ptr.Val(temp.GetId())
break break
} }
} }
// Get Next Link // Get Next Link
link := resp.GetOdataNextLink() link, ok := ptr.ValOK(resp.GetOdataNextLink())
if link == nil { if !ok {
break break
} }
builder = sites.NewItemListsRequestBuilder(*link, service.Adapter()) builder = sites.NewItemListsRequestBuilder(link, service.Adapter())
} }
if isFound { if isFound {
@ -254,7 +255,7 @@ func (suite *SharePointCollectionSuite) TestRestoreLocation() {
siteDrive, err := service.Client().SitesById(suite.siteID).Drive().Get(ctx, nil) siteDrive, err := service.Client().SitesById(suite.siteID).Drive().Get(ctx, nil)
require.NoError(t, err) require.NoError(t, err)
driveID := *siteDrive.GetId() driveID := ptr.Val(siteDrive.GetId())
err = onedrive.DeleteItem(ctx, service, driveID, folderID) err = onedrive.DeleteItem(ctx, service, driveID, folderID)
assert.NoError(t, err) assert.NoError(t, err)
} }

View File

@ -61,11 +61,12 @@ func preFetchLists(
listTuples = append(listTuples, temp) listTuples = append(listTuples, temp)
} }
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite.NewItemListsRequestBuilder(ptr.Val(resp.GetOdataNextLink()), gs.Adapter()) builder = mssite.NewItemListsRequestBuilder(link, gs.Adapter())
} }
return listTuples, nil return listTuples, nil
@ -215,7 +216,7 @@ func fetchListItems(
break break
} }
newPrefix := prefix.ItemsById(*itm.GetId()) newPrefix := prefix.ItemsById(ptr.Val(itm.GetId()))
fields, err := newPrefix.Fields().Get(ctx, nil) fields, err := newPrefix.Fields().Get(ctx, nil)
if err != nil { if err != nil {
@ -228,11 +229,12 @@ func fetchListItems(
itms = append(itms, itm) itms = append(itms, itm)
} }
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite.NewItemListsItemItemsRequestBuilder(*resp.GetOdataNextLink(), gs.Adapter()) builder = mssite.NewItemListsItemItemsRequestBuilder(link, gs.Adapter())
} }
return itms, el.Failure() return itms, el.Failure()
@ -260,11 +262,12 @@ func fetchColumns(
cs = append(cs, resp.GetValue()...) cs = append(cs, resp.GetValue()...)
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite.NewItemListsItemColumnsRequestBuilder(*resp.GetOdataNextLink(), gs.Adapter()) builder = mssite.NewItemListsItemColumnsRequestBuilder(link, gs.Adapter())
} }
} else { } else {
builder := gs.Client().SitesById(siteID).ListsById(listID).ContentTypesById(cTypeID).Columns() builder := gs.Client().SitesById(siteID).ListsById(listID).ContentTypesById(cTypeID).Columns()
@ -277,11 +280,12 @@ func fetchColumns(
cs = append(cs, resp.GetValue()...) cs = append(cs, resp.GetValue()...)
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite.NewItemListsItemContentTypesItemColumnsRequestBuilder(*resp.GetOdataNextLink(), gs.Adapter()) builder = mssite.NewItemListsItemContentTypesItemColumnsRequestBuilder(link, gs.Adapter())
} }
} }
@ -342,11 +346,12 @@ func fetchContentTypes(
cTypes = append(cTypes, cont) cTypes = append(cTypes, cont)
} }
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite.NewItemListsItemContentTypesRequestBuilder(*resp.GetOdataNextLink(), gs.Adapter()) builder = mssite.NewItemListsItemContentTypesRequestBuilder(link, gs.Adapter())
} }
return cTypes, el.Failure() return cTypes, el.Failure()
@ -370,15 +375,14 @@ func fetchColumnLinks(
links = append(links, resp.GetValue()...) links = append(links, resp.GetValue()...)
if resp.GetOdataNextLink() == nil { link, ok := ptr.ValOK(resp.GetOdataNextLink())
if !ok {
break break
} }
builder = mssite. builder = mssite.NewItemListsItemContentTypesItemColumnLinksRequestBuilder(
NewItemListsItemContentTypesItemColumnLinksRequestBuilder( link,
*resp.GetOdataNextLink(), gs.Adapter())
gs.Adapter(),
)
} }
return links, nil return links, nil

View File

@ -3,6 +3,7 @@ package sharepoint
import ( import (
"time" "time"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/graph/betasdk/models" "github.com/alcionai/corso/src/internal/connector/graph/betasdk/models"
"github.com/alcionai/corso/src/pkg/backup/details" "github.com/alcionai/corso/src/pkg/backup/details"
) )
@ -16,8 +17,8 @@ func sharePointPageInfo(page models.SitePageable, root string, size int64) *deta
created, modified time.Time created, modified time.Time
) )
if page.GetTitle() != nil { if title, ok := ptr.ValOK(page.GetTitle()); ok {
name = *page.GetTitle() name = title
} }
if page.GetWebUrl() != nil { if page.GetWebUrl() != nil {
@ -25,16 +26,14 @@ func sharePointPageInfo(page models.SitePageable, root string, size int64) *deta
prefix = root + "/" prefix = root + "/"
} }
webURL = prefix + *page.GetWebUrl() webURL = prefix + ptr.Val(page.GetWebUrl())
} }
if page.GetCreatedDateTime() != nil { if page.GetCreatedDateTime() != nil {
created = *page.GetCreatedDateTime() created = ptr.Val(page.GetCreatedDateTime())
} }
if page.GetLastModifiedDateTime() != nil { modified = ptr.OrNow(page.GetLastModifiedDateTime())
modified = *page.GetLastModifiedDateTime()
}
return &details.SharePointInfo{ return &details.SharePointInfo{
ItemType: details.SharePointPage, ItemType: details.SharePointPage,

View File

@ -129,7 +129,7 @@ func createRestoreFolders(
return "", graph.Wrap(ctx, err, "getting site drive root") return "", graph.Wrap(ctx, err, "getting site drive root")
} }
return onedrive.CreateRestoreFolders(ctx, service, *mainDrive.GetId(), restoreFolders) return onedrive.CreateRestoreFolders(ctx, service, ptr.Val(mainDrive.GetId()), restoreFolders)
} }
// restoreListItem utility function restores a List to the siteID. // restoreListItem utility function restores a List to the siteID.
@ -162,8 +162,8 @@ func restoreListItem(
return dii, clues.Wrap(err, "creating item").WithClues(ctx) return dii, clues.Wrap(err, "creating item").WithClues(ctx)
} }
if oldList.GetDisplayName() != nil { if name, ok := ptr.ValOK(oldList.GetDisplayName()); ok {
listName = *oldList.GetDisplayName() listName = name
} }
var ( var (
@ -191,7 +191,7 @@ func restoreListItem(
for _, lItem := range contents { for _, lItem := range contents {
_, err := service.Client(). _, err := service.Client().
SitesById(siteID). SitesById(siteID).
ListsById(*restoredList.GetId()). ListsById(ptr.Val(restoredList.GetId())).
Items(). Items().
Post(ctx, lItem, nil) Post(ctx, lItem, nil)
if err != nil { if err != nil {

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/alcionai/corso/src/internal/common/ptr"
) )
type attendee struct { type attendee struct {
@ -30,12 +32,12 @@ func FormatAttendees(event models.Eventable, isHTML bool) string {
} }
temp := attendee{ temp := attendee{
name: *entry.GetEmailAddress().GetName(), name: ptr.Val(entry.GetEmailAddress().GetName()),
email: *entry.GetEmailAddress().GetAddress(), email: ptr.Val(entry.GetEmailAddress().GetAddress()),
response: entry.GetStatus().GetResponse().String(), response: entry.GetStatus().GetResponse().String(),
} }
switch *entry.GetType() { switch ptr.Val(entry.GetType()) {
case models.REQUIRED_ATTENDEETYPE: case models.REQUIRED_ATTENDEETYPE:
required = append(required, temp) required = append(required, temp)

View File

@ -1,8 +1,6 @@
package support package support
import ( import (
"strings"
absser "github.com/microsoft/kiota-abstractions-go/serialization" absser "github.com/microsoft/kiota-abstractions-go/serialization"
js "github.com/microsoft/kiota-serialization-json-go" js "github.com/microsoft/kiota-serialization-json-go"
"github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models"
@ -87,14 +85,3 @@ func CreatePageFromBytes(bytes []byte) (bmodels.SitePageable, error) {
return page, nil return page, nil
} }
func HasAttachments(body models.ItemBodyable) bool {
if body.GetContent() == nil || body.GetContentType() == nil ||
*body.GetContentType() == models.TEXT_BODYTYPE || len(*body.GetContent()) == 0 {
return false
}
content := *body.GetContent()
return strings.Contains(content, "src=\"cid:")
}

View File

@ -4,7 +4,6 @@ import (
"testing" "testing"
kioser "github.com/microsoft/kiota-serialization-json-go" kioser "github.com/microsoft/kiota-serialization-json-go"
"github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
@ -233,58 +232,3 @@ func (suite *DataSupportSuite) TestCreatePageFromBytes() {
}) })
} }
} }
func (suite *DataSupportSuite) TestHasAttachments() {
tests := []struct {
name string
hasAttachment assert.BoolAssertionFunc
getBodyable func(t *testing.T) models.ItemBodyable
}{
{
name: "Mock w/out attachment",
hasAttachment: assert.False,
getBodyable: func(t *testing.T) models.ItemBodyable {
byteArray := mockconnector.GetMockMessageWithBodyBytes(
"Test",
"This is testing",
"This is testing",
)
message, err := CreateMessageFromBytes(byteArray)
require.NoError(t, err)
return message.GetBody()
},
},
{
name: "Mock w/ inline attachment",
hasAttachment: assert.True,
getBodyable: func(t *testing.T) models.ItemBodyable {
byteArray := mockconnector.GetMessageWithOneDriveAttachment("Test legacy")
message, err := CreateMessageFromBytes(byteArray)
require.NoError(t, err)
return message.GetBody()
},
},
{
name: "Edge Case",
hasAttachment: assert.True,
getBodyable: func(t *testing.T) models.ItemBodyable {
//nolint:lll
content := "<html><head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><style type=\"text/css\" style=\"display:none\">\r\n<!--\r\np\r\n\t{margin-top:0;\r\n\tmargin-bottom:0}\r\n-->\r\n</style></head><body dir=\"ltr\"><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">Happy New Year,</div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">In accordance with TPS report guidelines, there have been questions about how to address our activities SharePoint Cover page. Do you believe this is the best picture?&nbsp;</div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><img class=\"FluidPluginCopy ContentPasted0 w-2070 h-1380\" size=\"5854817\" data-outlook-trace=\"F:1|T:1\" src=\"cid:85f4faa3-9851-40c7-ba0a-e63dce1185f9\" style=\"max-width:100%\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">Let me know if this meets our culture requirements.</div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">Warm Regards,</div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\"><br></div><div class=\"elementToProof\" style=\"font-family:Calibri,Arial,Helvetica,sans-serif; font-size:12pt; color:rgb(0,0,0); background-color:rgb(255,255,255)\">Dustin</div></body></html>"
body := models.NewItemBody()
body.SetContent(&content)
cat := models.HTML_BODYTYPE
body.SetContentType(&cat)
return body
},
},
}
for _, test := range tests {
suite.Run(test.name, func() {
t := suite.T()
found := HasAttachments(test.getBodyable(t))
test.hasAttachment(t, found)
})
}
}

View File

@ -5,6 +5,8 @@ import (
"strings" "strings"
"github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/alcionai/corso/src/internal/common/ptr"
) )
//========================================================== //==========================================================
@ -68,7 +70,7 @@ func ToMessage(orig models.Messageable) models.Messageable {
// add a summary of attendees at the beginning to the event before the original body content // add a summary of attendees at the beginning to the event before the original body content
// - event.attendees is set to an empty list // - event.attendees is set to an empty list
func ToEventSimplified(orig models.Eventable) models.Eventable { func ToEventSimplified(orig models.Eventable) models.Eventable {
attendees := FormatAttendees(orig, *orig.GetBody().GetContentType() == models.HTML_BODYTYPE) attendees := FormatAttendees(orig, ptr.Val(orig.GetBody().GetContentType()) == models.HTML_BODYTYPE)
orig.SetAttendees([]models.Attendeeable{}) orig.SetAttendees([]models.Attendeeable{})
origBody := orig.GetBody() origBody := orig.GetBody()
newContent := insertStringToBody(origBody, attendees) newContent := insertStringToBody(origBody, attendees)
@ -97,14 +99,14 @@ type getContenter interface {
// @returns string containing the content string of altered body. // @returns string containing the content string of altered body.
func insertStringToBody(body getContenter, newContent string) string { func insertStringToBody(body getContenter, newContent string) string {
if body.GetContent() == nil || if body.GetContent() == nil ||
len(*body.GetContent()) == 0 || len(ptr.Val(body.GetContent())) == 0 ||
body.GetContentType() == nil { body.GetContentType() == nil {
return "" return ""
} }
content := *body.GetContent() content := ptr.Val(body.GetContent())
switch *body.GetContentType() { switch ptr.Val(body.GetContentType()) {
case models.TEXT_BODYTYPE: case models.TEXT_BODYTYPE:
return newContent + content return newContent + content
@ -225,12 +227,12 @@ func ToListable(orig models.Listable, displayName string) models.Listable {
readOnly bool readOnly bool
) )
if cd.GetDisplayName() != nil { if name, ok := ptr.ValOK(cd.GetDisplayName()); ok {
displayName = *cd.GetDisplayName() displayName = name
} }
if cd.GetReadOnly() != nil { if ro, ok := ptr.ValOK(cd.GetReadOnly()); ok {
readOnly = *cd.GetReadOnly() readOnly = ro
} }
_, isLegacy := leg[displayName] _, isLegacy := leg[displayName]
@ -369,7 +371,7 @@ func ToItemAttachment(orig models.Attachmentable) (models.Attachmentable, error)
// attachments := make([]models.Attachmentable, len(attached)) // attachments := make([]models.Attachmentable, len(attached))
// for _, ax := range attached { // for _, ax := range attached {
// if *ax.GetOdataType() == itemAttachment { // if ptr.Val(ax.GetOdataType()) == itemAttachment {
// newAttachment, err := ToItemAttachment(ax) // newAttachment, err := ToItemAttachment(ax)
// if err != nil { // if err != nil {
// return nil, err // return nil, err

View File

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/alcionai/corso/src/internal/common/ptr"
"github.com/alcionai/corso/src/internal/connector/mockconnector" "github.com/alcionai/corso/src/internal/connector/mockconnector"
"github.com/alcionai/corso/src/internal/tester" "github.com/alcionai/corso/src/internal/tester"
) )
@ -45,13 +46,13 @@ func (suite *SupportTestSuite) TestToEventSimplified() {
newEvent := ToEventSimplified(event) newEvent := ToEventSimplified(event)
assert.Empty(t, newEvent.GetHideAttendees()) assert.Empty(t, newEvent.GetHideAttendees())
assert.Equal(t, *event.GetBody().GetContentType(), *newEvent.GetBody().GetContentType()) assert.Equal(t, ptr.Val(event.GetBody().GetContentType()), ptr.Val(newEvent.GetBody().GetContentType()))
assert.Equal(t, event.GetBody().GetAdditionalData(), newEvent.GetBody().GetAdditionalData()) assert.Equal(t, event.GetBody().GetAdditionalData(), newEvent.GetBody().GetAdditionalData())
assert.Contains(t, *event.GetBody().GetContent(), "Required:") assert.Contains(t, ptr.Val(event.GetBody().GetContent()), "Required:")
for _, member := range attendees { for _, member := range attendees {
assert.Contains(t, *event.GetBody().GetContent(), *member.GetEmailAddress().GetName()) assert.Contains(t, ptr.Val(event.GetBody().GetContent()), ptr.Val(member.GetEmailAddress().GetName()))
assert.Contains(t, *event.GetBody().GetContent(), *member.GetEmailAddress().GetAddress()) assert.Contains(t, ptr.Val(event.GetBody().GetContent()), ptr.Val(member.GetEmailAddress().GetAddress()))
} }
} }