From 316212599a2a5767ed5c8ce45bb7820d5612f311 Mon Sep 17 00:00:00 2001 From: rot1024 Date: Fri, 14 Jan 2022 20:27:18 +0900 Subject: [PATCH 1/5] rename IDToKeys, some methods support nil ids, refactor ids --- internal/infrastructure/mongo/asset.go | 4 +- internal/infrastructure/mongo/dataset.go | 10 +- .../infrastructure/mongo/dataset_schema.go | 6 +- internal/infrastructure/mongo/layer.go | 14 +- .../infrastructure/mongo/mongodoc/layer.go | 2 +- .../mongo/mongodoc/scene_align.go | 2 +- internal/infrastructure/mongo/mongodoc/tag.go | 2 +- internal/infrastructure/mongo/plugin.go | 6 +- internal/infrastructure/mongo/project.go | 4 +- internal/infrastructure/mongo/property.go | 6 +- .../infrastructure/mongo/property_schema.go | 4 +- internal/infrastructure/mongo/scene.go | 12 +- internal/infrastructure/mongo/scene_lock.go | 2 +- internal/infrastructure/mongo/tag.go | 12 +- internal/infrastructure/mongo/team.go | 4 +- internal/infrastructure/mongo/user.go | 2 +- pkg/id/asset_gen.go | 59 +- pkg/id/asset_gen_test.go | 493 ++++++++--------- pkg/id/cluster_field_gen_test.go | 493 ++++++++--------- pkg/id/cluster_gen.go | 59 +- pkg/id/dataset_gen.go | 59 +- pkg/id/dataset_gen_test.go | 493 ++++++++--------- pkg/id/dataset_schema_field_gen.go | 59 +- pkg/id/dataset_schema_field_gen_test.go | 493 ++++++++--------- pkg/id/dataset_schema_gen.go | 59 +- pkg/id/dataset_schema_gen_test.go | 493 ++++++++--------- pkg/id/id.go | 2 +- pkg/id/id.tmpl | 59 +- pkg/id/id_test.go | 6 +- pkg/id/id_test.tmpl | 515 ++++++++---------- pkg/id/infobox_field_gen.go | 59 +- pkg/id/infobox_field_gen_test.go | 493 ++++++++--------- pkg/id/layer_gen.go | 59 +- pkg/id/layer_gen_test.go | 493 ++++++++--------- pkg/id/plugin.go | 17 +- pkg/id/plugin_test.go | 44 +- pkg/id/project_gen.go | 59 +- pkg/id/project_gen_test.go | 493 ++++++++--------- pkg/id/property_gen.go | 59 +- pkg/id/property_gen_test.go | 493 ++++++++--------- pkg/id/property_item_gen.go | 59 +- pkg/id/property_item_gen_test.go | 493 ++++++++--------- pkg/id/property_schema.go | 20 +- pkg/id/property_schema_field.go | 9 +- pkg/id/property_schema_group.go | 9 +- pkg/id/property_schema_test.go | 20 +- pkg/id/scene_gen.go | 59 +- pkg/id/scene_gen_test.go | 493 ++++++++--------- pkg/id/tag_gen.go | 59 +- pkg/id/tag_gen_test.go | 493 ++++++++--------- pkg/id/team_gen.go | 59 +- pkg/id/team_gen_test.go | 493 ++++++++--------- pkg/id/user_gen.go | 59 +- pkg/id/user_gen_test.go | 493 ++++++++--------- pkg/id/widget_gen.go | 59 +- pkg/id/widget_gen_test.go | 493 ++++++++--------- 56 files changed, 4437 insertions(+), 4636 deletions(-) diff --git a/internal/infrastructure/mongo/asset.go b/internal/infrastructure/mongo/asset.go index 2f5e93fa..cb78cc28 100644 --- a/internal/infrastructure/mongo/asset.go +++ b/internal/infrastructure/mongo/asset.go @@ -33,7 +33,7 @@ func (r *assetRepo) FindByID(ctx context.Context, id id.AssetID, teams []id.Team func (r *assetRepo) FindByIDs(ctx context.Context, ids []id.AssetID, teams []id.TeamID) ([]*asset.Asset, error) { filter := assetFilter(bson.M{ - "id": bson.M{"$in": id.AssetIDToKeys(ids)}, + "id": bson.M{"$in": id.AssetIDsToStrings(ids)}, }, teams) dst := make([]*asset.Asset, 0, len(ids)) res, err := r.find(ctx, dst, filter) @@ -112,6 +112,6 @@ func filterAssets(ids []id.AssetID, rows []*asset.Asset) []*asset.Asset { } func assetFilter(filter bson.M, teams []id.TeamID) bson.M { - filter["team"] = bson.M{"$in": id.TeamIDToKeys(teams)} + filter["team"] = bson.M{"$in": id.TeamIDsToStrings(teams)} return filter } diff --git a/internal/infrastructure/mongo/dataset.go b/internal/infrastructure/mongo/dataset.go index 1b8e1e1a..f802db5f 100644 --- a/internal/infrastructure/mongo/dataset.go +++ b/internal/infrastructure/mongo/dataset.go @@ -41,7 +41,7 @@ func (r *datasetRepo) FindByID(ctx context.Context, id2 id.DatasetID, f []id.Sce func (r *datasetRepo) FindByIDs(ctx context.Context, ids []id.DatasetID, f []id.SceneID) (dataset.List, error) { filter := r.sceneFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.DatasetIDToKeys(ids)}, + {Key: "$in", Value: id.DatasetIDsToStrings(ids)}, }}, }, f) dst := make([]*dataset.Dataset, 0, len(ids)) @@ -75,14 +75,14 @@ func (r *datasetRepo) FindGraph(ctx context.Context, did id.DatasetID, f []id.Sc return dataset.List{d}, nil } - fieldsstr := id.DatasetSchemaFieldIDToKeys(fields) + fieldsstr := id.DatasetSchemaFieldIDsToStrings(fields) firstField := fieldsstr[0] aggfilter := bson.D{} if f != nil { aggfilter = append(aggfilter, bson.E{Key: "$in", Value: []interface{}{ "$$g.scene", - id.SceneIDToKeys(f), + id.SceneIDsToStrings(f), }}) } @@ -271,7 +271,7 @@ func (r *datasetRepo) RemoveAll(ctx context.Context, ids []id.DatasetID) error { if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.DatasetIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.DatasetIDsToStrings(ids)) } func (r *datasetRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error { @@ -336,7 +336,7 @@ func (*datasetRepo) sceneFilter(filter bson.D, scenes []id.SceneID) bson.D { } filter = append(filter, bson.E{ Key: "scene", - Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(scenes)}}, + Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(scenes)}}, }) return filter } diff --git a/internal/infrastructure/mongo/dataset_schema.go b/internal/infrastructure/mongo/dataset_schema.go index e15c51e3..00860f6f 100644 --- a/internal/infrastructure/mongo/dataset_schema.go +++ b/internal/infrastructure/mongo/dataset_schema.go @@ -41,7 +41,7 @@ func (r *datasetSchemaRepo) FindByID(ctx context.Context, id2 id.DatasetSchemaID func (r *datasetSchemaRepo) FindByIDs(ctx context.Context, ids []id.DatasetSchemaID, f []id.SceneID) (dataset.SchemaList, error) { filter := r.sceneFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.DatasetSchemaIDToKeys(ids)}, + {Key: "$in", Value: id.DatasetSchemaIDsToStrings(ids)}, }}, }, f) dst := make([]*dataset.Schema, 0, len(ids)) @@ -111,7 +111,7 @@ func (r *datasetSchemaRepo) RemoveAll(ctx context.Context, ids []id.DatasetSchem if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.DatasetSchemaIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.DatasetSchemaIDsToStrings(ids)) } func (r *datasetSchemaRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error { @@ -176,7 +176,7 @@ func (*datasetSchemaRepo) sceneFilter(filter bson.D, scenes []id.SceneID) bson.D } filter = append(filter, bson.E{ Key: "scene", - Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(scenes)}}, + Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(scenes)}}, }) return filter } diff --git a/internal/infrastructure/mongo/layer.go b/internal/infrastructure/mongo/layer.go index efdf02c9..33eb7089 100644 --- a/internal/infrastructure/mongo/layer.go +++ b/internal/infrastructure/mongo/layer.go @@ -40,7 +40,7 @@ func (r *layerRepo) FindByID(ctx context.Context, id id.LayerID, f []id.SceneID) func (r *layerRepo) FindByIDs(ctx context.Context, ids []id.LayerID, f []id.SceneID) (layer.List, error) { filter := r.sceneFilterD(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.LayerIDToKeys(ids)}, + {Key: "$in", Value: id.LayerIDsToStrings(ids)}, }}, }, f) dst := make([]*layer.Layer, 0, len(ids)) @@ -68,7 +68,7 @@ func (r *layerRepo) FindItemByID(ctx context.Context, id id.LayerID, f []id.Scen func (r *layerRepo) FindItemByIDs(ctx context.Context, ids []id.LayerID, f []id.SceneID) (layer.ItemList, error) { filter := r.sceneFilterD(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.LayerIDToKeys(ids)}, + {Key: "$in", Value: id.LayerIDsToStrings(ids)}, }}, }, f) dst := make([]*layer.Item, 0, len(ids)) @@ -89,7 +89,7 @@ func (r *layerRepo) FindGroupByID(ctx context.Context, id id.LayerID, f []id.Sce func (r *layerRepo) FindGroupByIDs(ctx context.Context, ids []id.LayerID, f []id.SceneID) (layer.GroupList, error) { filter := r.sceneFilterD(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.LayerIDToKeys(ids)}, + {Key: "$in", Value: id.LayerIDsToStrings(ids)}, }}, }, f) dst := make([]*layer.Group, 0, len(ids)) @@ -154,7 +154,7 @@ func (r *layerRepo) RemoveAll(ctx context.Context, ids []id.LayerID) error { if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.LayerIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.LayerIDsToStrings(ids)) } func (r *layerRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error { @@ -170,7 +170,7 @@ func (r *layerRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error func (r *layerRepo) FindByTag(ctx context.Context, tagID id.TagID, f []id.SceneID) (layer.List, error) { ids := []id.TagID{tagID} - tags := id.TagIDToKeys(ids) + tags := id.TagIDsToStrings(ids) filter := r.sceneFilter(bson.M{ "$or": []bson.M{ {"tags.id": bson.M{"$in": tags}}, @@ -331,7 +331,7 @@ func (*layerRepo) sceneFilterD(filter bson.D, scenes []id.SceneID) bson.D { } filter = append(filter, bson.E{ Key: "scene", - Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(scenes)}}, + Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(scenes)}}, }) return filter } @@ -340,6 +340,6 @@ func (*layerRepo) sceneFilter(filter bson.M, scenes []id.SceneID) bson.M { if scenes == nil { return filter } - filter["scene"] = bson.M{"$in": id.SceneIDToKeys(scenes)} + filter["scene"] = bson.M{"$in": id.SceneIDsToStrings(scenes)} return filter } diff --git a/internal/infrastructure/mongo/mongodoc/layer.go b/internal/infrastructure/mongo/mongodoc/layer.go index 44b935a9..5483b31e 100644 --- a/internal/infrastructure/mongo/mongodoc/layer.go +++ b/internal/infrastructure/mongo/mongodoc/layer.go @@ -91,7 +91,7 @@ func NewLayer(l layer.Layer) (*LayerDocument, string) { if lg := layer.GroupFromLayer(l); lg != nil { group = &LayerGroupDocument{ - Layers: id.LayerIDToKeys(lg.Layers().Layers()), + Layers: id.LayerIDsToStrings(lg.Layers().Layers()), LinkedDatasetSchema: lg.LinkedDatasetSchema().StringRef(), Root: lg.IsRoot(), } diff --git a/internal/infrastructure/mongo/mongodoc/scene_align.go b/internal/infrastructure/mongo/mongodoc/scene_align.go index ab746b98..836ef252 100644 --- a/internal/infrastructure/mongo/mongodoc/scene_align.go +++ b/internal/infrastructure/mongo/mongodoc/scene_align.go @@ -82,7 +82,7 @@ func NewWidgetArea(a *scene.WidgetArea) *WidgetAreaDocument { } return &WidgetAreaDocument{ - WidgetIDs: id.WidgetIDToKeys(a.WidgetIDs()), + WidgetIDs: id.WidgetIDsToStrings(a.WidgetIDs()), Align: string(a.Alignment()), } } diff --git a/internal/infrastructure/mongo/mongodoc/tag.go b/internal/infrastructure/mongo/mongodoc/tag.go index d8e936f3..11550237 100644 --- a/internal/infrastructure/mongo/mongodoc/tag.go +++ b/internal/infrastructure/mongo/mongodoc/tag.go @@ -68,7 +68,7 @@ func NewTag(t tag.Tag) (*TagDocument, string) { ids := tags.Tags() group = &TagGroupDocument{ - Tags: id.TagIDToKeys(ids), + Tags: id.TagIDsToStrings(ids), } } diff --git a/internal/infrastructure/mongo/plugin.go b/internal/infrastructure/mongo/plugin.go index c9f7e79d..ff19986e 100644 --- a/internal/infrastructure/mongo/plugin.go +++ b/internal/infrastructure/mongo/plugin.go @@ -51,7 +51,7 @@ func (r *pluginRepo) FindByID(ctx context.Context, pid id.PluginID, sids []id.Sc { "id": pids, "scene": bson.M{ - "$in": id.SceneIDToKeys(sids), + "$in": id.SceneIDsToStrings(sids), }, }, }, @@ -76,7 +76,7 @@ func (r *pluginRepo) FindByIDs(ctx context.Context, ids []id.PluginID, sids []id var err error if len(ids2) > 0 { - keys := id.PluginIDToKeys(ids2) + keys := id.PluginIDsToStrings(ids2) filter := bson.M{ "$or": []bson.M{ { @@ -90,7 +90,7 @@ func (r *pluginRepo) FindByIDs(ctx context.Context, ids []id.PluginID, sids []id { "id": bson.M{"$in": keys}, "scene": bson.M{ - "$in": id.SceneIDToKeys(sids), + "$in": id.SceneIDsToStrings(sids), }, }, }, diff --git a/internal/infrastructure/mongo/project.go b/internal/infrastructure/mongo/project.go index 1ebc566d..3f81036d 100644 --- a/internal/infrastructure/mongo/project.go +++ b/internal/infrastructure/mongo/project.go @@ -34,7 +34,7 @@ func (r *projectRepo) init() { func (r *projectRepo) FindByIDs(ctx context.Context, ids []id.ProjectID, f []id.TeamID) ([]*project.Project, error) { filter := r.teamFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.ProjectIDToKeys(ids)}, + {Key: "$in", Value: id.ProjectIDsToStrings(ids)}, }}, }, f) dst := make([]*project.Project, 0, len(ids)) @@ -143,7 +143,7 @@ func (*projectRepo) teamFilter(filter bson.D, teams []id.TeamID) bson.D { } filter = append(filter, bson.E{ Key: "team", - Value: bson.D{{Key: "$in", Value: id.TeamIDToKeys(teams)}}, + Value: bson.D{{Key: "$in", Value: id.TeamIDsToStrings(teams)}}, }) return filter } diff --git a/internal/infrastructure/mongo/property.go b/internal/infrastructure/mongo/property.go index a879654b..ed40e2fa 100644 --- a/internal/infrastructure/mongo/property.go +++ b/internal/infrastructure/mongo/property.go @@ -36,7 +36,7 @@ func (r *propertyRepo) FindByID(ctx context.Context, id2 id.PropertyID, f []id.S func (r *propertyRepo) FindByIDs(ctx context.Context, ids []id.PropertyID, f []id.SceneID) (property.List, error) { filter := r.sceneFilter(bson.D{{Key: "id", Value: bson.D{{ - Key: "$in", Value: id.PropertyIDToKeys(ids), + Key: "$in", Value: id.PropertyIDsToStrings(ids), }}}}, f) dst := make(property.List, 0, len(ids)) res, err := r.find(ctx, dst, filter) @@ -99,7 +99,7 @@ func (r *propertyRepo) RemoveAll(ctx context.Context, ids []id.PropertyID) error if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.PropertyIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.PropertyIDsToStrings(ids)) } func (r *propertyRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error { @@ -164,7 +164,7 @@ func (*propertyRepo) sceneFilter(filter bson.D, scenes []id.SceneID) bson.D { } filter = append(filter, bson.E{ Key: "scene", - Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(scenes)}}, + Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(scenes)}}, }) return filter } diff --git a/internal/infrastructure/mongo/property_schema.go b/internal/infrastructure/mongo/property_schema.go index 2595bdd1..50cb7112 100644 --- a/internal/infrastructure/mongo/property_schema.go +++ b/internal/infrastructure/mongo/property_schema.go @@ -56,7 +56,7 @@ func (r *propertySchemaRepo) FindByIDs(ctx context.Context, ids []id.PropertySch if len(ids2) > 0 { filter := bson.D{{Key: "id", Value: bson.D{{ - Key: "$in", Value: id.PropertySchemaIDToKeys(ids2), + Key: "$in", Value: id.PropertySchemaIDsToStrings(ids2), }}}} dst := make(property.SchemaList, 0, len(ids2)) res, err = r.find(ctx, dst, filter) @@ -120,7 +120,7 @@ func (r *propertySchemaRepo) RemoveAll(ctx context.Context, ids []id.PropertySch if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.PropertySchemaIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.PropertySchemaIDsToStrings(ids)) } func (r *propertySchemaRepo) find(ctx context.Context, dst property.SchemaList, filter bson.D) (property.SchemaList, error) { diff --git a/internal/infrastructure/mongo/scene.go b/internal/infrastructure/mongo/scene.go index 8a599081..b27cb323 100644 --- a/internal/infrastructure/mongo/scene.go +++ b/internal/infrastructure/mongo/scene.go @@ -41,7 +41,7 @@ func (r *sceneRepo) FindByID(ctx context.Context, id id.SceneID, f []id.TeamID) func (r *sceneRepo) FindByIDs(ctx context.Context, ids []id.SceneID, f []id.TeamID) ([]*scene.Scene, error) { filter := r.teamFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.SceneIDToKeys(ids)}, + {Key: "$in", Value: id.SceneIDsToStrings(ids)}, }}, }, f) dst := make([]*scene.Scene, 0, len(ids)) @@ -62,7 +62,7 @@ func (r *sceneRepo) FindByProject(ctx context.Context, id id.ProjectID, f []id.T func (r *sceneRepo) FindIDsByTeam(ctx context.Context, teams []id.TeamID) ([]id.SceneID, error) { filter := bson.D{ {Key: "team", Value: bson.D{ - {Key: "$in", Value: id.TeamIDToKeys(teams)}, + {Key: "$in", Value: id.TeamIDsToStrings(teams)}, }}, } c := mongodoc.SceneIDConsumer{ @@ -79,7 +79,7 @@ func (r *sceneRepo) FindIDsByTeam(ctx context.Context, teams []id.TeamID) ([]id. func (r *sceneRepo) HasSceneTeam(ctx context.Context, sceneID id.SceneID, temaIDs []id.TeamID) (bool, error) { filter := bson.D{ {Key: "id", Value: sceneID.String()}, - {Key: "team", Value: bson.D{{Key: "$in", Value: id.TeamIDToKeys(temaIDs)}}}, + {Key: "team", Value: bson.D{{Key: "$in", Value: id.TeamIDsToStrings(temaIDs)}}}, } res, err2 := r.client.Collection().CountDocuments(ctx, filter) if err2 != nil { @@ -90,8 +90,8 @@ func (r *sceneRepo) HasSceneTeam(ctx context.Context, sceneID id.SceneID, temaID func (r *sceneRepo) HasScenesTeam(ctx context.Context, sceneIDs []id.SceneID, teamIDs []id.TeamID) ([]bool, error) { cursor, err2 := r.client.Collection().Find(ctx, bson.D{ - {Key: "id", Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(sceneIDs)}}}, - {Key: "team", Value: bson.D{{Key: "$in", Value: id.TeamIDToKeys(teamIDs)}}}, + {Key: "id", Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(sceneIDs)}}}, + {Key: "team", Value: bson.D{{Key: "$in", Value: id.TeamIDsToStrings(teamIDs)}}}, }, &options.FindOptions{ Projection: bson.D{{Key: "id", Value: 1}, {Key: "_id", Value: 0}}, }) @@ -181,7 +181,7 @@ func (*sceneRepo) teamFilter(filter bson.D, teams []id.TeamID) bson.D { } filter = append(filter, bson.E{ Key: "team", - Value: bson.D{{Key: "$in", Value: id.TeamIDToKeys(teams)}}, + Value: bson.D{{Key: "$in", Value: id.TeamIDsToStrings(teams)}}, }) return filter } diff --git a/internal/infrastructure/mongo/scene_lock.go b/internal/infrastructure/mongo/scene_lock.go index c41e015f..8d9f6667 100644 --- a/internal/infrastructure/mongo/scene_lock.go +++ b/internal/infrastructure/mongo/scene_lock.go @@ -39,7 +39,7 @@ func (r *sceneLockRepo) GetLock(ctx context.Context, sceneID id.SceneID) (scene. func (r *sceneLockRepo) GetAllLock(ctx context.Context, ids []id.SceneID) ([]scene.LockMode, error) { filter := bson.D{ {Key: "scene", Value: bson.D{ - {Key: "$in", Value: id.SceneIDToKeys(ids)}, + {Key: "$in", Value: id.SceneIDsToStrings(ids)}, }}, } c := mongodoc.SceneLockConsumer{ diff --git a/internal/infrastructure/mongo/tag.go b/internal/infrastructure/mongo/tag.go index f07349aa..6717cc6f 100644 --- a/internal/infrastructure/mongo/tag.go +++ b/internal/infrastructure/mongo/tag.go @@ -40,7 +40,7 @@ func (r *tagRepo) FindByID(ctx context.Context, id id.TagID, f []id.SceneID) (ta func (r *tagRepo) FindByIDs(ctx context.Context, ids []id.TagID, f []id.SceneID) ([]*tag.Tag, error) { filter := r.sceneFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.TagIDToKeys(ids)}, + {Key: "$in", Value: id.TagIDsToStrings(ids)}, }}, }, f) dst := make([]*tag.Tag, 0, len(ids)) @@ -61,7 +61,7 @@ func (r *tagRepo) FindItemByID(ctx context.Context, id id.TagID, f []id.SceneID) func (r *tagRepo) FindItemByIDs(ctx context.Context, ids []id.TagID, f []id.SceneID) ([]*tag.Item, error) { filter := r.sceneFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.TagIDToKeys(ids)}, + {Key: "$in", Value: id.TagIDsToStrings(ids)}, }}, }, f) dst := make([]*tag.Item, 0, len(ids)) @@ -82,7 +82,7 @@ func (r *tagRepo) FindGroupByID(ctx context.Context, id id.TagID, f []id.SceneID func (r *tagRepo) FindGroupByIDs(ctx context.Context, ids []id.TagID, f []id.SceneID) ([]*tag.Group, error) { filter := r.sceneFilter(bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.TagIDToKeys(ids)}, + {Key: "$in", Value: id.TagIDsToStrings(ids)}, }}, }, f) dst := make([]*tag.Group, 0, len(ids)) @@ -105,7 +105,7 @@ func (r *tagRepo) FindGroupByItem(ctx context.Context, tagID id.TagID, f []id.Sc ids := []id.TagID{tagID} filter := r.sceneFilter(bson.D{ {Key: "group.tags", Value: bson.D{ - {Key: "$in", Value: id.TagIDToKeys(ids)}, + {Key: "$in", Value: id.TagIDsToStrings(ids)}, }}, }, f) @@ -133,7 +133,7 @@ func (r *tagRepo) RemoveAll(ctx context.Context, ids []id.TagID) error { if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.TagIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.TagIDsToStrings(ids)) } func (r *tagRepo) RemoveByScene(ctx context.Context, sceneID id.SceneID) error { @@ -270,7 +270,7 @@ func (*tagRepo) sceneFilter(filter bson.D, scenes []id.SceneID) bson.D { } filter = append(filter, bson.E{ Key: "scene", - Value: bson.D{{Key: "$in", Value: id.SceneIDToKeys(scenes)}}, + Value: bson.D{{Key: "$in", Value: id.SceneIDsToStrings(scenes)}}, }) return filter } diff --git a/internal/infrastructure/mongo/team.go b/internal/infrastructure/mongo/team.go index 0ba00f9b..9249fb6d 100644 --- a/internal/infrastructure/mongo/team.go +++ b/internal/infrastructure/mongo/team.go @@ -41,7 +41,7 @@ func (r *teamRepo) FindByUser(ctx context.Context, id id.UserID) ([]*user.Team, func (r *teamRepo) FindByIDs(ctx context.Context, ids []id.TeamID) ([]*user.Team, error) { filter := bson.D{ {Key: "id", Value: bson.D{ - {Key: "$in", Value: id.TeamIDToKeys(ids)}, + {Key: "$in", Value: id.TeamIDsToStrings(ids)}, }}, } dst := make([]*user.Team, 0, len(ids)) @@ -80,7 +80,7 @@ func (r *teamRepo) RemoveAll(ctx context.Context, ids []id.TeamID) error { if len(ids) == 0 { return nil } - return r.client.RemoveAll(ctx, id.TeamIDToKeys(ids)) + return r.client.RemoveAll(ctx, id.TeamIDsToStrings(ids)) } func (r *teamRepo) find(ctx context.Context, dst []*user.Team, filter bson.D) ([]*user.Team, error) { diff --git a/internal/infrastructure/mongo/user.go b/internal/infrastructure/mongo/user.go index 1a8cf727..d553cb86 100644 --- a/internal/infrastructure/mongo/user.go +++ b/internal/infrastructure/mongo/user.go @@ -31,7 +31,7 @@ func (r *userRepo) init() { func (r *userRepo) FindByIDs(ctx context.Context, ids []id.UserID) ([]*user.User, error) { filter := bson.D{{Key: "id", Value: bson.D{ - {Key: "$in", Value: id.UserIDToKeys(ids)}, + {Key: "$in", Value: id.UserIDsToStrings(ids)}, }}} dst := make([]*user.User, 0, len(ids)) res, err := r.find(ctx, dst, filter) diff --git a/pkg/id/asset_gen.go b/pkg/id/asset_gen.go index fa061e5c..ac082c89 100644 --- a/pkg/id/asset_gen.go +++ b/pkg/id/asset_gen.go @@ -44,7 +44,7 @@ func AssetIDFromRef(i *string) *AssetID { // AssetIDFromRefID generates a new AssetID from a ref of a generic ID. func AssetIDFromRefID(i *ID) *AssetID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := AssetID(*i) @@ -58,28 +58,40 @@ func (d AssetID) ID() ID { // String returns a string representation. func (d AssetID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d AssetID) GoString() string { - return "id.AssetID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d AssetID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d AssetID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d AssetID) GoString() string { + return "AssetID(" + d.String() + ")" } // Ref returns a reference. func (d AssetID) Ref() *AssetID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d AssetID) Contains(ids []AssetID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d AssetID) Contains(ids []AssetID) bool { // CopyRef returns a copy of a reference. func (d *AssetID) CopyRef() *AssetID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *AssetID) CopyRef() *AssetID { // IDRef returns a reference of a domain id. func (d *AssetID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *AssetID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *AssetID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *AssetID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *AssetID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *AssetID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *AssetID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *AssetID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d AssetID) IsNil() bool { return ID(d).IsNil() } -// AssetIDToKeys converts IDs into a string slice. -func AssetIDToKeys(ids []AssetID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *AssetID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// AssetIDsToStrings converts IDs into a string slice. +func AssetIDsToStrings(ids []AssetID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // AssetIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *AssetIDSet) Clone() *AssetIDSet { // Merge returns a merged set func (s *AssetIDSet) Merge(s2 *AssetIDSet) *AssetIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/asset_gen_test.go b/pkg/id/asset_gen_test.go index 14d5985b..8a8d24a9 100644 --- a/pkg/id/asset_gen_test.go +++ b/pkg/id/asset_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewAssetID(t *testing.T) { id := NewAssetID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestAssetIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestAssetIDFrom(t *testing.T) { result AssetID err error }{ - AssetID{}, - ErrInvalidID, + result: AssetID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestAssetIDFrom(t *testing.T) { result AssetID err error }{ - AssetID{}, - ErrInvalidID, + result: AssetID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestAssetIDFrom(t *testing.T) { result AssetID err error }{ - AssetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: AssetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := AssetIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := AssetIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustAssetID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustAssetID(t *testing.T) { expected: AssetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustAssetID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustAssetID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestAssetIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *AssetID @@ -139,159 +135,149 @@ func TestAssetIDFromRef(t *testing.T) { expected: &AssetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := AssetIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := AssetIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestAssetIDFromRefID(t *testing.T) { id := New() - - subId := AssetIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := AssetIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, AssetIDFromRefID(nil)) + assert.Nil(t, AssetIDFromRefID(&ID{})) } func TestAssetID_ID(t *testing.T) { id := New() - subId := AssetIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := AssetIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestAssetID_String(t *testing.T) { id := New() - subId := AssetIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := AssetIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", AssetID{}.String()) } -func TestAssetID_GoString(t *testing.T) { - id := New() - subId := AssetIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.AssetID("+id.String()+")") +func TestAssetID_RefString(t *testing.T) { + id := NewAssetID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, AssetID{}.RefString()) } -func TestAssetID_RefString(t *testing.T) { +func TestAssetID_GoString(t *testing.T) { id := New() - subId := AssetIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := AssetIDFromRefID(&id) + assert.Equal(t, "AssetID("+id.String()+")", id2.GoString()) + assert.Equal(t, "AssetID()", AssetID{}.GoString()) } func TestAssetID_Ref(t *testing.T) { - id := New() - subId := AssetIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewAssetID() + assert.Equal(t, AssetID(id), *id.Ref()) + assert.Nil(t, (&AssetID{}).Ref()) } func TestAssetID_Contains(t *testing.T) { id := NewAssetID() id2 := NewAssetID() assert.True(t, id.Contains([]AssetID{id, id2})) + assert.False(t, AssetID{}.Contains([]AssetID{id, id2, {}})) assert.False(t, id.Contains([]AssetID{id2})) } func TestAssetID_CopyRef(t *testing.T) { - id := New() - subId := AssetIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewAssetID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*AssetID)(nil).CopyRef()) } func TestAssetID_IDRef(t *testing.T) { id := New() - subId := AssetIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := AssetIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&AssetID{}).IDRef()) + assert.Nil(t, (*AssetID)(nil).IDRef()) } func TestAssetID_StringRef(t *testing.T) { - id := New() - subId := AssetIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewAssetID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&AssetID{}).StringRef()) + assert.Nil(t, (*AssetID)(nil).StringRef()) } func TestAssetID_MarhsalJSON(t *testing.T) { - id := New() - subId := AssetIDFromRefID(&id) + id := NewAssetID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&AssetID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*AssetID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestAssetID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &AssetID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustAssetID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &AssetID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestAssetID_MarshalText(t *testing.T) { id := New() - subId := AssetIDFromRefID(&id) + res, err := AssetIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&AssetID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*AssetID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestAssetID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &AssetID{} - - err := subId.UnmarshalText(text) - + id2 := &AssetID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestAssetID_IsNil(t *testing.T) { - subId := AssetID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *AssetIDFromRefID(&id) + assert.True(t, AssetID{}.IsNil()) + assert.False(t, NewAssetID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestAssetID_IsNilRef(t *testing.T) { + assert.True(t, AssetID{}.Ref().IsNilRef()) + assert.True(t, (*AssetID)(nil).IsNilRef()) + assert.False(t, NewAssetID().Ref().IsNilRef()) } -func TestAssetIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestAssetIDsToStrings(t *testing.T) { + tests := []struct { name string input []AssetID expected []string @@ -321,19 +307,17 @@ func TestAssetIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, AssetIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, AssetIDsToStrings(tt.input)) }) } - } func TestAssetIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestAssetIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestAssetIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := AssetIDsFrom(tc.input) if tc.expected.err != nil { - _, err := AssetIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := AssetIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestAssetIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []AssetID @@ -449,25 +431,22 @@ func TestAssetIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := AssetIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestAssetIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []AssetID @@ -493,21 +472,18 @@ func TestAssetIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := AssetIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestAssetIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []AssetID expected []ID @@ -537,28 +513,25 @@ func TestAssetIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := AssetIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestAssetIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustAssetID(id1.String()) + id21 := MustAssetID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustAssetID(id2.String()) + id22 := MustAssetID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustAssetID(id3.String()) + id23 := MustAssetID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*AssetID expected []*ID @@ -570,39 +543,35 @@ func TestAssetIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*AssetID{&subId1}, + input: []*AssetID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*AssetID{&subId1, &subId2, &subId3}, + input: []*AssetID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := AssetIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewAssetIDSet(t *testing.T) { AssetIdSet := NewAssetIDSet() - assert.NotNil(t, AssetIdSet) assert.Empty(t, AssetIdSet.m) assert.Empty(t, AssetIdSet.s) } func TestAssetIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []AssetID expected *AssetIDSet @@ -663,24 +632,19 @@ func TestAssetIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewAssetIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestAssetIDSet_AddRef(t *testing.T) { - t.Parallel() - - AssetId := MustAssetID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *AssetID expected *AssetIDSet @@ -695,7 +659,7 @@ func TestAssetIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &AssetId, + input: MustAssetID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &AssetIDSet{ m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestAssetIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewAssetIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestAssetIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - AssetIDSet - AssetID - } + tests := []struct { + name string + target *AssetIDSet + input AssetID expected bool }{ { - name: "Empty Set", - input: struct { - AssetIDSet - AssetID - }{AssetIDSet: AssetIDSet{}, AssetID: MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &AssetIDSet{}, + input: MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - AssetIDSet - AssetID - }{AssetIDSet: AssetIDSet{ + target: &AssetIDSet{ m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, AssetID: MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - AssetIDSet - AssetID - }{AssetIDSet: AssetIDSet{ + target: &AssetIDSet{ m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, AssetID: MustAssetID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustAssetID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.AssetIDSet.Has(tc.input.AssetID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestAssetIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input AssetIDSet - expected AssetIDSet + input *AssetIDSet + expected *AssetIDSet }{ { - name: "Empty Set", - input: AssetIDSet{}, - expected: AssetIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &AssetIDSet{}, + expected: &AssetIDSet{}, }, { - name: "Set Contains the element", - input: AssetIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &AssetIDSet{ m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: AssetIDSet{ + expected: &AssetIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestAssetIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *AssetIDSet expected []AssetID }{ { - name: "Empty slice", + name: "Empty", input: &AssetIDSet{ m: map[AssetID]struct{}{}, s: nil, }, expected: make([]AssetID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &AssetIDSet{ @@ -854,20 +808,17 @@ func TestAssetIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestAssetIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *AssetIDSet expected *AssetIDSet @@ -922,21 +873,19 @@ func TestAssetIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestAssetIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *AssetIDSet @@ -944,6 +893,23 @@ func TestAssetIDSet_Merge(t *testing.T) { } expected *AssetIDSet }{ + { + name: "Nil Set", + input: struct { + a *AssetIDSet + b *AssetIDSet + }{ + a: &AssetIDSet{ + m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &AssetIDSet{ + m: map[AssetID]struct{}{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []AssetID{MustAssetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestAssetIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/cluster_field_gen_test.go b/pkg/id/cluster_field_gen_test.go index ed76808b..7fc5cd18 100644 --- a/pkg/id/cluster_field_gen_test.go +++ b/pkg/id/cluster_field_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewClusterID(t *testing.T) { id := NewClusterID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestClusterIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestClusterIDFrom(t *testing.T) { result ClusterID err error }{ - ClusterID{}, - ErrInvalidID, + result: ClusterID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestClusterIDFrom(t *testing.T) { result ClusterID err error }{ - ClusterID{}, - ErrInvalidID, + result: ClusterID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestClusterIDFrom(t *testing.T) { result ClusterID err error }{ - ClusterID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: ClusterID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := ClusterIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := ClusterIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustClusterID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustClusterID(t *testing.T) { expected: ClusterID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustClusterID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustClusterID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestClusterIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *ClusterID @@ -139,159 +135,149 @@ func TestClusterIDFromRef(t *testing.T) { expected: &ClusterID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := ClusterIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := ClusterIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestClusterIDFromRefID(t *testing.T) { id := New() - - subId := ClusterIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := ClusterIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, ClusterIDFromRefID(nil)) + assert.Nil(t, ClusterIDFromRefID(&ID{})) } func TestClusterID_ID(t *testing.T) { id := New() - subId := ClusterIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := ClusterIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestClusterID_String(t *testing.T) { id := New() - subId := ClusterIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := ClusterIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", ClusterID{}.String()) } -func TestClusterID_GoString(t *testing.T) { - id := New() - subId := ClusterIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.ClusterID("+id.String()+")") +func TestClusterID_RefString(t *testing.T) { + id := NewClusterID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, ClusterID{}.RefString()) } -func TestClusterID_RefString(t *testing.T) { +func TestClusterID_GoString(t *testing.T) { id := New() - subId := ClusterIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := ClusterIDFromRefID(&id) + assert.Equal(t, "ClusterID("+id.String()+")", id2.GoString()) + assert.Equal(t, "ClusterID()", ClusterID{}.GoString()) } func TestClusterID_Ref(t *testing.T) { - id := New() - subId := ClusterIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewClusterID() + assert.Equal(t, ClusterID(id), *id.Ref()) + assert.Nil(t, (&ClusterID{}).Ref()) } func TestClusterID_Contains(t *testing.T) { id := NewClusterID() id2 := NewClusterID() assert.True(t, id.Contains([]ClusterID{id, id2})) + assert.False(t, ClusterID{}.Contains([]ClusterID{id, id2, {}})) assert.False(t, id.Contains([]ClusterID{id2})) } func TestClusterID_CopyRef(t *testing.T) { - id := New() - subId := ClusterIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewClusterID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*ClusterID)(nil).CopyRef()) } func TestClusterID_IDRef(t *testing.T) { id := New() - subId := ClusterIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := ClusterIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&ClusterID{}).IDRef()) + assert.Nil(t, (*ClusterID)(nil).IDRef()) } func TestClusterID_StringRef(t *testing.T) { - id := New() - subId := ClusterIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewClusterID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&ClusterID{}).StringRef()) + assert.Nil(t, (*ClusterID)(nil).StringRef()) } func TestClusterID_MarhsalJSON(t *testing.T) { - id := New() - subId := ClusterIDFromRefID(&id) + id := NewClusterID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&ClusterID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*ClusterID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestClusterID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &ClusterID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustClusterID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &ClusterID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestClusterID_MarshalText(t *testing.T) { id := New() - subId := ClusterIDFromRefID(&id) + res, err := ClusterIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&ClusterID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*ClusterID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestClusterID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &ClusterID{} - - err := subId.UnmarshalText(text) - + id2 := &ClusterID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestClusterID_IsNil(t *testing.T) { - subId := ClusterID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *ClusterIDFromRefID(&id) + assert.True(t, ClusterID{}.IsNil()) + assert.False(t, NewClusterID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestClusterID_IsNilRef(t *testing.T) { + assert.True(t, ClusterID{}.Ref().IsNilRef()) + assert.True(t, (*ClusterID)(nil).IsNilRef()) + assert.False(t, NewClusterID().Ref().IsNilRef()) } -func TestClusterIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestClusterIDsToStrings(t *testing.T) { + tests := []struct { name string input []ClusterID expected []string @@ -321,19 +307,17 @@ func TestClusterIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, ClusterIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, ClusterIDsToStrings(tt.input)) }) } - } func TestClusterIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestClusterIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestClusterIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := ClusterIDsFrom(tc.input) if tc.expected.err != nil { - _, err := ClusterIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := ClusterIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestClusterIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []ClusterID @@ -449,25 +431,22 @@ func TestClusterIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ClusterIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestClusterIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []ClusterID @@ -493,21 +472,18 @@ func TestClusterIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ClusterIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestClusterIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []ClusterID expected []ID @@ -537,28 +513,25 @@ func TestClusterIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ClusterIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestClusterIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustClusterID(id1.String()) + id21 := MustClusterID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustClusterID(id2.String()) + id22 := MustClusterID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustClusterID(id3.String()) + id23 := MustClusterID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*ClusterID expected []*ID @@ -570,39 +543,35 @@ func TestClusterIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*ClusterID{&subId1}, + input: []*ClusterID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*ClusterID{&subId1, &subId2, &subId3}, + input: []*ClusterID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ClusterIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewClusterIDSet(t *testing.T) { ClusterIdSet := NewClusterIDSet() - assert.NotNil(t, ClusterIdSet) assert.Empty(t, ClusterIdSet.m) assert.Empty(t, ClusterIdSet.s) } func TestClusterIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []ClusterID expected *ClusterIDSet @@ -663,24 +632,19 @@ func TestClusterIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewClusterIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestClusterIDSet_AddRef(t *testing.T) { - t.Parallel() - - ClusterId := MustClusterID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *ClusterID expected *ClusterIDSet @@ -695,7 +659,7 @@ func TestClusterIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &ClusterId, + input: MustClusterID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &ClusterIDSet{ m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestClusterIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewClusterIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestClusterIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - ClusterIDSet - ClusterID - } + tests := []struct { + name string + target *ClusterIDSet + input ClusterID expected bool }{ { - name: "Empty Set", - input: struct { - ClusterIDSet - ClusterID - }{ClusterIDSet: ClusterIDSet{}, ClusterID: MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &ClusterIDSet{}, + input: MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - ClusterIDSet - ClusterID - }{ClusterIDSet: ClusterIDSet{ + target: &ClusterIDSet{ m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, ClusterID: MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - ClusterIDSet - ClusterID - }{ClusterIDSet: ClusterIDSet{ + target: &ClusterIDSet{ m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, ClusterID: MustClusterID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustClusterID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.ClusterIDSet.Has(tc.input.ClusterID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestClusterIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input ClusterIDSet - expected ClusterIDSet + input *ClusterIDSet + expected *ClusterIDSet }{ { - name: "Empty Set", - input: ClusterIDSet{}, - expected: ClusterIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &ClusterIDSet{}, + expected: &ClusterIDSet{}, }, { - name: "Set Contains the element", - input: ClusterIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &ClusterIDSet{ m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: ClusterIDSet{ + expected: &ClusterIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestClusterIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *ClusterIDSet expected []ClusterID }{ { - name: "Empty slice", + name: "Empty", input: &ClusterIDSet{ m: map[ClusterID]struct{}{}, s: nil, }, expected: make([]ClusterID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &ClusterIDSet{ @@ -854,20 +808,17 @@ func TestClusterIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestClusterIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *ClusterIDSet expected *ClusterIDSet @@ -922,21 +873,19 @@ func TestClusterIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestClusterIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *ClusterIDSet @@ -944,6 +893,23 @@ func TestClusterIDSet_Merge(t *testing.T) { } expected *ClusterIDSet }{ + { + name: "Nil Set", + input: struct { + a *ClusterIDSet + b *ClusterIDSet + }{ + a: &ClusterIDSet{ + m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &ClusterIDSet{ + m: map[ClusterID]struct{}{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []ClusterID{MustClusterID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestClusterIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/cluster_gen.go b/pkg/id/cluster_gen.go index 3720b1bf..03884921 100644 --- a/pkg/id/cluster_gen.go +++ b/pkg/id/cluster_gen.go @@ -44,7 +44,7 @@ func ClusterIDFromRef(i *string) *ClusterID { // ClusterIDFromRefID generates a new ClusterID from a ref of a generic ID. func ClusterIDFromRefID(i *ID) *ClusterID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := ClusterID(*i) @@ -58,28 +58,40 @@ func (d ClusterID) ID() ID { // String returns a string representation. func (d ClusterID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d ClusterID) GoString() string { - return "id.ClusterID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d ClusterID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d ClusterID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d ClusterID) GoString() string { + return "ClusterID(" + d.String() + ")" } // Ref returns a reference. func (d ClusterID) Ref() *ClusterID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d ClusterID) Contains(ids []ClusterID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d ClusterID) Contains(ids []ClusterID) bool { // CopyRef returns a copy of a reference. func (d *ClusterID) CopyRef() *ClusterID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *ClusterID) CopyRef() *ClusterID { // IDRef returns a reference of a domain id. func (d *ClusterID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *ClusterID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *ClusterID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *ClusterID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *ClusterID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *ClusterID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *ClusterID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *ClusterID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d ClusterID) IsNil() bool { return ID(d).IsNil() } -// ClusterIDToKeys converts IDs into a string slice. -func ClusterIDToKeys(ids []ClusterID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *ClusterID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// ClusterIDsToStrings converts IDs into a string slice. +func ClusterIDsToStrings(ids []ClusterID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // ClusterIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *ClusterIDSet) Clone() *ClusterIDSet { // Merge returns a merged set func (s *ClusterIDSet) Merge(s2 *ClusterIDSet) *ClusterIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/dataset_gen.go b/pkg/id/dataset_gen.go index 1e76621b..8dec9b21 100644 --- a/pkg/id/dataset_gen.go +++ b/pkg/id/dataset_gen.go @@ -44,7 +44,7 @@ func DatasetIDFromRef(i *string) *DatasetID { // DatasetIDFromRefID generates a new DatasetID from a ref of a generic ID. func DatasetIDFromRefID(i *ID) *DatasetID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := DatasetID(*i) @@ -58,28 +58,40 @@ func (d DatasetID) ID() ID { // String returns a string representation. func (d DatasetID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d DatasetID) GoString() string { - return "id.DatasetID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d DatasetID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d DatasetID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d DatasetID) GoString() string { + return "DatasetID(" + d.String() + ")" } // Ref returns a reference. func (d DatasetID) Ref() *DatasetID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d DatasetID) Contains(ids []DatasetID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d DatasetID) Contains(ids []DatasetID) bool { // CopyRef returns a copy of a reference. func (d *DatasetID) CopyRef() *DatasetID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *DatasetID) CopyRef() *DatasetID { // IDRef returns a reference of a domain id. func (d *DatasetID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *DatasetID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *DatasetID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *DatasetID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *DatasetID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *DatasetID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *DatasetID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *DatasetID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d DatasetID) IsNil() bool { return ID(d).IsNil() } -// DatasetIDToKeys converts IDs into a string slice. -func DatasetIDToKeys(ids []DatasetID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *DatasetID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// DatasetIDsToStrings converts IDs into a string slice. +func DatasetIDsToStrings(ids []DatasetID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // DatasetIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *DatasetIDSet) Clone() *DatasetIDSet { // Merge returns a merged set func (s *DatasetIDSet) Merge(s2 *DatasetIDSet) *DatasetIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/dataset_gen_test.go b/pkg/id/dataset_gen_test.go index 48c1c825..294b4526 100644 --- a/pkg/id/dataset_gen_test.go +++ b/pkg/id/dataset_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewDatasetID(t *testing.T) { id := NewDatasetID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestDatasetIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestDatasetIDFrom(t *testing.T) { result DatasetID err error }{ - DatasetID{}, - ErrInvalidID, + result: DatasetID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestDatasetIDFrom(t *testing.T) { result DatasetID err error }{ - DatasetID{}, - ErrInvalidID, + result: DatasetID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestDatasetIDFrom(t *testing.T) { result DatasetID err error }{ - DatasetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: DatasetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := DatasetIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := DatasetIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustDatasetID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustDatasetID(t *testing.T) { expected: DatasetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustDatasetID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustDatasetID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *DatasetID @@ -139,159 +135,149 @@ func TestDatasetIDFromRef(t *testing.T) { expected: &DatasetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := DatasetIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := DatasetIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetIDFromRefID(t *testing.T) { id := New() - - subId := DatasetIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := DatasetIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, DatasetIDFromRefID(nil)) + assert.Nil(t, DatasetIDFromRefID(&ID{})) } func TestDatasetID_ID(t *testing.T) { id := New() - subId := DatasetIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := DatasetIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestDatasetID_String(t *testing.T) { id := New() - subId := DatasetIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := DatasetIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", DatasetID{}.String()) } -func TestDatasetID_GoString(t *testing.T) { - id := New() - subId := DatasetIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.DatasetID("+id.String()+")") +func TestDatasetID_RefString(t *testing.T) { + id := NewDatasetID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, DatasetID{}.RefString()) } -func TestDatasetID_RefString(t *testing.T) { +func TestDatasetID_GoString(t *testing.T) { id := New() - subId := DatasetIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := DatasetIDFromRefID(&id) + assert.Equal(t, "DatasetID("+id.String()+")", id2.GoString()) + assert.Equal(t, "DatasetID()", DatasetID{}.GoString()) } func TestDatasetID_Ref(t *testing.T) { - id := New() - subId := DatasetIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewDatasetID() + assert.Equal(t, DatasetID(id), *id.Ref()) + assert.Nil(t, (&DatasetID{}).Ref()) } func TestDatasetID_Contains(t *testing.T) { id := NewDatasetID() id2 := NewDatasetID() assert.True(t, id.Contains([]DatasetID{id, id2})) + assert.False(t, DatasetID{}.Contains([]DatasetID{id, id2, {}})) assert.False(t, id.Contains([]DatasetID{id2})) } func TestDatasetID_CopyRef(t *testing.T) { - id := New() - subId := DatasetIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewDatasetID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*DatasetID)(nil).CopyRef()) } func TestDatasetID_IDRef(t *testing.T) { id := New() - subId := DatasetIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := DatasetIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&DatasetID{}).IDRef()) + assert.Nil(t, (*DatasetID)(nil).IDRef()) } func TestDatasetID_StringRef(t *testing.T) { - id := New() - subId := DatasetIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewDatasetID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&DatasetID{}).StringRef()) + assert.Nil(t, (*DatasetID)(nil).StringRef()) } func TestDatasetID_MarhsalJSON(t *testing.T) { - id := New() - subId := DatasetIDFromRefID(&id) + id := NewDatasetID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&DatasetID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestDatasetID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &DatasetID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustDatasetID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &DatasetID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestDatasetID_MarshalText(t *testing.T) { id := New() - subId := DatasetIDFromRefID(&id) + res, err := DatasetIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&DatasetID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestDatasetID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &DatasetID{} - - err := subId.UnmarshalText(text) - + id2 := &DatasetID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestDatasetID_IsNil(t *testing.T) { - subId := DatasetID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *DatasetIDFromRefID(&id) + assert.True(t, DatasetID{}.IsNil()) + assert.False(t, NewDatasetID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestDatasetID_IsNilRef(t *testing.T) { + assert.True(t, DatasetID{}.Ref().IsNilRef()) + assert.True(t, (*DatasetID)(nil).IsNilRef()) + assert.False(t, NewDatasetID().Ref().IsNilRef()) } -func TestDatasetIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestDatasetIDsToStrings(t *testing.T) { + tests := []struct { name string input []DatasetID expected []string @@ -321,19 +307,17 @@ func TestDatasetIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, DatasetIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, DatasetIDsToStrings(tt.input)) }) } - } func TestDatasetIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestDatasetIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestDatasetIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := DatasetIDsFrom(tc.input) if tc.expected.err != nil { - _, err := DatasetIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := DatasetIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestDatasetIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []DatasetID @@ -449,25 +431,22 @@ func TestDatasetIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []DatasetID @@ -493,21 +472,18 @@ func TestDatasetIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetID expected []ID @@ -537,28 +513,25 @@ func TestDatasetIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustDatasetID(id1.String()) + id21 := MustDatasetID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustDatasetID(id2.String()) + id22 := MustDatasetID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustDatasetID(id3.String()) + id23 := MustDatasetID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*DatasetID expected []*ID @@ -570,39 +543,35 @@ func TestDatasetIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*DatasetID{&subId1}, + input: []*DatasetID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*DatasetID{&subId1, &subId2, &subId3}, + input: []*DatasetID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewDatasetIDSet(t *testing.T) { DatasetIdSet := NewDatasetIDSet() - assert.NotNil(t, DatasetIdSet) assert.Empty(t, DatasetIdSet.m) assert.Empty(t, DatasetIdSet.s) } func TestDatasetIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetID expected *DatasetIDSet @@ -663,24 +632,19 @@ func TestDatasetIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetIDSet_AddRef(t *testing.T) { - t.Parallel() - - DatasetId := MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *DatasetID expected *DatasetIDSet @@ -695,7 +659,7 @@ func TestDatasetIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &DatasetId, + input: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &DatasetIDSet{ m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestDatasetIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - DatasetIDSet - DatasetID - } + tests := []struct { + name string + target *DatasetIDSet + input DatasetID expected bool }{ { - name: "Empty Set", - input: struct { - DatasetIDSet - DatasetID - }{DatasetIDSet: DatasetIDSet{}, DatasetID: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &DatasetIDSet{}, + input: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - DatasetIDSet - DatasetID - }{DatasetIDSet: DatasetIDSet{ + target: &DatasetIDSet{ m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetID: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - DatasetIDSet - DatasetID - }{DatasetIDSet: DatasetIDSet{ + target: &DatasetIDSet{ m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetID: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustDatasetID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.DatasetIDSet.Has(tc.input.DatasetID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestDatasetIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input DatasetIDSet - expected DatasetIDSet + input *DatasetIDSet + expected *DatasetIDSet }{ { - name: "Empty Set", - input: DatasetIDSet{}, - expected: DatasetIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &DatasetIDSet{}, + expected: &DatasetIDSet{}, }, { - name: "Set Contains the element", - input: DatasetIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &DatasetIDSet{ m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: DatasetIDSet{ + expected: &DatasetIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestDatasetIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetIDSet expected []DatasetID }{ { - name: "Empty slice", + name: "Empty", input: &DatasetIDSet{ m: map[DatasetID]struct{}{}, s: nil, }, expected: make([]DatasetID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &DatasetIDSet{ @@ -854,20 +808,17 @@ func TestDatasetIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestDatasetIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetIDSet expected *DatasetIDSet @@ -922,21 +873,19 @@ func TestDatasetIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestDatasetIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *DatasetIDSet @@ -944,6 +893,23 @@ func TestDatasetIDSet_Merge(t *testing.T) { } expected *DatasetIDSet }{ + { + name: "Nil Set", + input: struct { + a *DatasetIDSet + b *DatasetIDSet + }{ + a: &DatasetIDSet{ + m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &DatasetIDSet{ + m: map[DatasetID]struct{}{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetID{MustDatasetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestDatasetIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/dataset_schema_field_gen.go b/pkg/id/dataset_schema_field_gen.go index b26c073e..c607fb68 100644 --- a/pkg/id/dataset_schema_field_gen.go +++ b/pkg/id/dataset_schema_field_gen.go @@ -44,7 +44,7 @@ func DatasetSchemaFieldIDFromRef(i *string) *DatasetSchemaFieldID { // DatasetSchemaFieldIDFromRefID generates a new DatasetSchemaFieldID from a ref of a generic ID. func DatasetSchemaFieldIDFromRefID(i *ID) *DatasetSchemaFieldID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := DatasetSchemaFieldID(*i) @@ -58,28 +58,40 @@ func (d DatasetSchemaFieldID) ID() ID { // String returns a string representation. func (d DatasetSchemaFieldID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d DatasetSchemaFieldID) GoString() string { - return "id.DatasetSchemaFieldID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d DatasetSchemaFieldID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d DatasetSchemaFieldID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d DatasetSchemaFieldID) GoString() string { + return "DatasetSchemaFieldID(" + d.String() + ")" } // Ref returns a reference. func (d DatasetSchemaFieldID) Ref() *DatasetSchemaFieldID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d DatasetSchemaFieldID) Contains(ids []DatasetSchemaFieldID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d DatasetSchemaFieldID) Contains(ids []DatasetSchemaFieldID) bool { // CopyRef returns a copy of a reference. func (d *DatasetSchemaFieldID) CopyRef() *DatasetSchemaFieldID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *DatasetSchemaFieldID) CopyRef() *DatasetSchemaFieldID { // IDRef returns a reference of a domain id. func (d *DatasetSchemaFieldID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *DatasetSchemaFieldID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *DatasetSchemaFieldID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *DatasetSchemaFieldID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *DatasetSchemaFieldID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *DatasetSchemaFieldID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *DatasetSchemaFieldID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *DatasetSchemaFieldID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d DatasetSchemaFieldID) IsNil() bool { return ID(d).IsNil() } -// DatasetSchemaFieldIDToKeys converts IDs into a string slice. -func DatasetSchemaFieldIDToKeys(ids []DatasetSchemaFieldID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *DatasetSchemaFieldID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// DatasetSchemaFieldIDsToStrings converts IDs into a string slice. +func DatasetSchemaFieldIDsToStrings(ids []DatasetSchemaFieldID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // DatasetSchemaFieldIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *DatasetSchemaFieldIDSet) Clone() *DatasetSchemaFieldIDSet { // Merge returns a merged set func (s *DatasetSchemaFieldIDSet) Merge(s2 *DatasetSchemaFieldIDSet) *DatasetSchemaFieldIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/dataset_schema_field_gen_test.go b/pkg/id/dataset_schema_field_gen_test.go index bd1926f1..9f4f2075 100644 --- a/pkg/id/dataset_schema_field_gen_test.go +++ b/pkg/id/dataset_schema_field_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewDatasetSchemaFieldID(t *testing.T) { id := NewDatasetSchemaFieldID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestDatasetSchemaFieldIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestDatasetSchemaFieldIDFrom(t *testing.T) { result DatasetSchemaFieldID err error }{ - DatasetSchemaFieldID{}, - ErrInvalidID, + result: DatasetSchemaFieldID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestDatasetSchemaFieldIDFrom(t *testing.T) { result DatasetSchemaFieldID err error }{ - DatasetSchemaFieldID{}, - ErrInvalidID, + result: DatasetSchemaFieldID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestDatasetSchemaFieldIDFrom(t *testing.T) { result DatasetSchemaFieldID err error }{ - DatasetSchemaFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: DatasetSchemaFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := DatasetSchemaFieldIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := DatasetSchemaFieldIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustDatasetSchemaFieldID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustDatasetSchemaFieldID(t *testing.T) { expected: DatasetSchemaFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustDatasetSchemaFieldID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustDatasetSchemaFieldID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetSchemaFieldIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *DatasetSchemaFieldID @@ -139,159 +135,149 @@ func TestDatasetSchemaFieldIDFromRef(t *testing.T) { expected: &DatasetSchemaFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := DatasetSchemaFieldIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := DatasetSchemaFieldIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetSchemaFieldIDFromRefID(t *testing.T) { id := New() - - subId := DatasetSchemaFieldIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := DatasetSchemaFieldIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, DatasetSchemaFieldIDFromRefID(nil)) + assert.Nil(t, DatasetSchemaFieldIDFromRefID(&ID{})) } func TestDatasetSchemaFieldID_ID(t *testing.T) { id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := DatasetSchemaFieldIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestDatasetSchemaFieldID_String(t *testing.T) { id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := DatasetSchemaFieldIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", DatasetSchemaFieldID{}.String()) } -func TestDatasetSchemaFieldID_GoString(t *testing.T) { - id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.DatasetSchemaFieldID("+id.String()+")") +func TestDatasetSchemaFieldID_RefString(t *testing.T) { + id := NewDatasetSchemaFieldID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, DatasetSchemaFieldID{}.RefString()) } -func TestDatasetSchemaFieldID_RefString(t *testing.T) { +func TestDatasetSchemaFieldID_GoString(t *testing.T) { id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := DatasetSchemaFieldIDFromRefID(&id) + assert.Equal(t, "DatasetSchemaFieldID("+id.String()+")", id2.GoString()) + assert.Equal(t, "DatasetSchemaFieldID()", DatasetSchemaFieldID{}.GoString()) } func TestDatasetSchemaFieldID_Ref(t *testing.T) { - id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewDatasetSchemaFieldID() + assert.Equal(t, DatasetSchemaFieldID(id), *id.Ref()) + assert.Nil(t, (&DatasetSchemaFieldID{}).Ref()) } func TestDatasetSchemaFieldID_Contains(t *testing.T) { id := NewDatasetSchemaFieldID() id2 := NewDatasetSchemaFieldID() assert.True(t, id.Contains([]DatasetSchemaFieldID{id, id2})) + assert.False(t, DatasetSchemaFieldID{}.Contains([]DatasetSchemaFieldID{id, id2, {}})) assert.False(t, id.Contains([]DatasetSchemaFieldID{id2})) } func TestDatasetSchemaFieldID_CopyRef(t *testing.T) { - id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewDatasetSchemaFieldID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*DatasetSchemaFieldID)(nil).CopyRef()) } func TestDatasetSchemaFieldID_IDRef(t *testing.T) { id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := DatasetSchemaFieldIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&DatasetSchemaFieldID{}).IDRef()) + assert.Nil(t, (*DatasetSchemaFieldID)(nil).IDRef()) } func TestDatasetSchemaFieldID_StringRef(t *testing.T) { - id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewDatasetSchemaFieldID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&DatasetSchemaFieldID{}).StringRef()) + assert.Nil(t, (*DatasetSchemaFieldID)(nil).StringRef()) } func TestDatasetSchemaFieldID_MarhsalJSON(t *testing.T) { - id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) + id := NewDatasetSchemaFieldID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&DatasetSchemaFieldID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetSchemaFieldID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestDatasetSchemaFieldID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &DatasetSchemaFieldID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustDatasetSchemaFieldID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &DatasetSchemaFieldID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestDatasetSchemaFieldID_MarshalText(t *testing.T) { id := New() - subId := DatasetSchemaFieldIDFromRefID(&id) + res, err := DatasetSchemaFieldIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&DatasetSchemaFieldID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetSchemaFieldID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestDatasetSchemaFieldID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &DatasetSchemaFieldID{} - - err := subId.UnmarshalText(text) - + id2 := &DatasetSchemaFieldID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestDatasetSchemaFieldID_IsNil(t *testing.T) { - subId := DatasetSchemaFieldID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *DatasetSchemaFieldIDFromRefID(&id) + assert.True(t, DatasetSchemaFieldID{}.IsNil()) + assert.False(t, NewDatasetSchemaFieldID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestDatasetSchemaFieldID_IsNilRef(t *testing.T) { + assert.True(t, DatasetSchemaFieldID{}.Ref().IsNilRef()) + assert.True(t, (*DatasetSchemaFieldID)(nil).IsNilRef()) + assert.False(t, NewDatasetSchemaFieldID().Ref().IsNilRef()) } -func TestDatasetSchemaFieldIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestDatasetSchemaFieldIDsToStrings(t *testing.T) { + tests := []struct { name string input []DatasetSchemaFieldID expected []string @@ -321,19 +307,17 @@ func TestDatasetSchemaFieldIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, DatasetSchemaFieldIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, DatasetSchemaFieldIDsToStrings(tt.input)) }) } - } func TestDatasetSchemaFieldIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestDatasetSchemaFieldIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestDatasetSchemaFieldIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := DatasetSchemaFieldIDsFrom(tc.input) if tc.expected.err != nil { - _, err := DatasetSchemaFieldIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := DatasetSchemaFieldIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestDatasetSchemaFieldIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []DatasetSchemaFieldID @@ -449,25 +431,22 @@ func TestDatasetSchemaFieldIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaFieldIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaFieldIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []DatasetSchemaFieldID @@ -493,21 +472,18 @@ func TestDatasetSchemaFieldIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaFieldIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaFieldIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetSchemaFieldID expected []ID @@ -537,28 +513,25 @@ func TestDatasetSchemaFieldIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaFieldIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaFieldIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustDatasetSchemaFieldID(id1.String()) + id21 := MustDatasetSchemaFieldID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustDatasetSchemaFieldID(id2.String()) + id22 := MustDatasetSchemaFieldID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustDatasetSchemaFieldID(id3.String()) + id23 := MustDatasetSchemaFieldID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*DatasetSchemaFieldID expected []*ID @@ -570,39 +543,35 @@ func TestDatasetSchemaFieldIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*DatasetSchemaFieldID{&subId1}, + input: []*DatasetSchemaFieldID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*DatasetSchemaFieldID{&subId1, &subId2, &subId3}, + input: []*DatasetSchemaFieldID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaFieldIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewDatasetSchemaFieldIDSet(t *testing.T) { DatasetSchemaFieldIdSet := NewDatasetSchemaFieldIDSet() - assert.NotNil(t, DatasetSchemaFieldIdSet) assert.Empty(t, DatasetSchemaFieldIdSet.m) assert.Empty(t, DatasetSchemaFieldIdSet.s) } func TestDatasetSchemaFieldIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetSchemaFieldID expected *DatasetSchemaFieldIDSet @@ -663,24 +632,19 @@ func TestDatasetSchemaFieldIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetSchemaFieldIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetSchemaFieldIDSet_AddRef(t *testing.T) { - t.Parallel() - - DatasetSchemaFieldId := MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaFieldID expected *DatasetSchemaFieldIDSet @@ -695,7 +659,7 @@ func TestDatasetSchemaFieldIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &DatasetSchemaFieldId, + input: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &DatasetSchemaFieldIDSet{ m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestDatasetSchemaFieldIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetSchemaFieldIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetSchemaFieldIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - DatasetSchemaFieldIDSet - DatasetSchemaFieldID - } + tests := []struct { + name string + target *DatasetSchemaFieldIDSet + input DatasetSchemaFieldID expected bool }{ { - name: "Empty Set", - input: struct { - DatasetSchemaFieldIDSet - DatasetSchemaFieldID - }{DatasetSchemaFieldIDSet: DatasetSchemaFieldIDSet{}, DatasetSchemaFieldID: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &DatasetSchemaFieldIDSet{}, + input: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - DatasetSchemaFieldIDSet - DatasetSchemaFieldID - }{DatasetSchemaFieldIDSet: DatasetSchemaFieldIDSet{ + target: &DatasetSchemaFieldIDSet{ m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetSchemaFieldID: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - DatasetSchemaFieldIDSet - DatasetSchemaFieldID - }{DatasetSchemaFieldIDSet: DatasetSchemaFieldIDSet{ + target: &DatasetSchemaFieldIDSet{ m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetSchemaFieldID: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.DatasetSchemaFieldIDSet.Has(tc.input.DatasetSchemaFieldID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestDatasetSchemaFieldIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input DatasetSchemaFieldIDSet - expected DatasetSchemaFieldIDSet + input *DatasetSchemaFieldIDSet + expected *DatasetSchemaFieldIDSet }{ { - name: "Empty Set", - input: DatasetSchemaFieldIDSet{}, - expected: DatasetSchemaFieldIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &DatasetSchemaFieldIDSet{}, + expected: &DatasetSchemaFieldIDSet{}, }, { - name: "Set Contains the element", - input: DatasetSchemaFieldIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &DatasetSchemaFieldIDSet{ m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: DatasetSchemaFieldIDSet{ + expected: &DatasetSchemaFieldIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestDatasetSchemaFieldIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaFieldIDSet expected []DatasetSchemaFieldID }{ { - name: "Empty slice", + name: "Empty", input: &DatasetSchemaFieldIDSet{ m: map[DatasetSchemaFieldID]struct{}{}, s: nil, }, expected: make([]DatasetSchemaFieldID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &DatasetSchemaFieldIDSet{ @@ -854,20 +808,17 @@ func TestDatasetSchemaFieldIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestDatasetSchemaFieldIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaFieldIDSet expected *DatasetSchemaFieldIDSet @@ -922,21 +873,19 @@ func TestDatasetSchemaFieldIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestDatasetSchemaFieldIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *DatasetSchemaFieldIDSet @@ -944,6 +893,23 @@ func TestDatasetSchemaFieldIDSet_Merge(t *testing.T) { } expected *DatasetSchemaFieldIDSet }{ + { + name: "Nil Set", + input: struct { + a *DatasetSchemaFieldIDSet + b *DatasetSchemaFieldIDSet + }{ + a: &DatasetSchemaFieldIDSet{ + m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &DatasetSchemaFieldIDSet{ + m: map[DatasetSchemaFieldID]struct{}{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetSchemaFieldID{MustDatasetSchemaFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestDatasetSchemaFieldIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/dataset_schema_gen.go b/pkg/id/dataset_schema_gen.go index 2c47eeb7..66efb0a3 100644 --- a/pkg/id/dataset_schema_gen.go +++ b/pkg/id/dataset_schema_gen.go @@ -44,7 +44,7 @@ func DatasetSchemaIDFromRef(i *string) *DatasetSchemaID { // DatasetSchemaIDFromRefID generates a new DatasetSchemaID from a ref of a generic ID. func DatasetSchemaIDFromRefID(i *ID) *DatasetSchemaID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := DatasetSchemaID(*i) @@ -58,28 +58,40 @@ func (d DatasetSchemaID) ID() ID { // String returns a string representation. func (d DatasetSchemaID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d DatasetSchemaID) GoString() string { - return "id.DatasetSchemaID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d DatasetSchemaID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d DatasetSchemaID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d DatasetSchemaID) GoString() string { + return "DatasetSchemaID(" + d.String() + ")" } // Ref returns a reference. func (d DatasetSchemaID) Ref() *DatasetSchemaID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d DatasetSchemaID) Contains(ids []DatasetSchemaID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d DatasetSchemaID) Contains(ids []DatasetSchemaID) bool { // CopyRef returns a copy of a reference. func (d *DatasetSchemaID) CopyRef() *DatasetSchemaID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *DatasetSchemaID) CopyRef() *DatasetSchemaID { // IDRef returns a reference of a domain id. func (d *DatasetSchemaID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *DatasetSchemaID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *DatasetSchemaID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *DatasetSchemaID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *DatasetSchemaID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *DatasetSchemaID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *DatasetSchemaID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *DatasetSchemaID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d DatasetSchemaID) IsNil() bool { return ID(d).IsNil() } -// DatasetSchemaIDToKeys converts IDs into a string slice. -func DatasetSchemaIDToKeys(ids []DatasetSchemaID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *DatasetSchemaID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// DatasetSchemaIDsToStrings converts IDs into a string slice. +func DatasetSchemaIDsToStrings(ids []DatasetSchemaID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // DatasetSchemaIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *DatasetSchemaIDSet) Clone() *DatasetSchemaIDSet { // Merge returns a merged set func (s *DatasetSchemaIDSet) Merge(s2 *DatasetSchemaIDSet) *DatasetSchemaIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/dataset_schema_gen_test.go b/pkg/id/dataset_schema_gen_test.go index c3b8910b..257c78f0 100644 --- a/pkg/id/dataset_schema_gen_test.go +++ b/pkg/id/dataset_schema_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewDatasetSchemaID(t *testing.T) { id := NewDatasetSchemaID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestDatasetSchemaIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestDatasetSchemaIDFrom(t *testing.T) { result DatasetSchemaID err error }{ - DatasetSchemaID{}, - ErrInvalidID, + result: DatasetSchemaID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestDatasetSchemaIDFrom(t *testing.T) { result DatasetSchemaID err error }{ - DatasetSchemaID{}, - ErrInvalidID, + result: DatasetSchemaID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestDatasetSchemaIDFrom(t *testing.T) { result DatasetSchemaID err error }{ - DatasetSchemaID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: DatasetSchemaID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := DatasetSchemaIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := DatasetSchemaIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustDatasetSchemaID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustDatasetSchemaID(t *testing.T) { expected: DatasetSchemaID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustDatasetSchemaID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustDatasetSchemaID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetSchemaIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *DatasetSchemaID @@ -139,159 +135,149 @@ func TestDatasetSchemaIDFromRef(t *testing.T) { expected: &DatasetSchemaID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := DatasetSchemaIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := DatasetSchemaIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestDatasetSchemaIDFromRefID(t *testing.T) { id := New() - - subId := DatasetSchemaIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := DatasetSchemaIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, DatasetSchemaIDFromRefID(nil)) + assert.Nil(t, DatasetSchemaIDFromRefID(&ID{})) } func TestDatasetSchemaID_ID(t *testing.T) { id := New() - subId := DatasetSchemaIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := DatasetSchemaIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestDatasetSchemaID_String(t *testing.T) { id := New() - subId := DatasetSchemaIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := DatasetSchemaIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", DatasetSchemaID{}.String()) } -func TestDatasetSchemaID_GoString(t *testing.T) { - id := New() - subId := DatasetSchemaIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.DatasetSchemaID("+id.String()+")") +func TestDatasetSchemaID_RefString(t *testing.T) { + id := NewDatasetSchemaID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, DatasetSchemaID{}.RefString()) } -func TestDatasetSchemaID_RefString(t *testing.T) { +func TestDatasetSchemaID_GoString(t *testing.T) { id := New() - subId := DatasetSchemaIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := DatasetSchemaIDFromRefID(&id) + assert.Equal(t, "DatasetSchemaID("+id.String()+")", id2.GoString()) + assert.Equal(t, "DatasetSchemaID()", DatasetSchemaID{}.GoString()) } func TestDatasetSchemaID_Ref(t *testing.T) { - id := New() - subId := DatasetSchemaIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewDatasetSchemaID() + assert.Equal(t, DatasetSchemaID(id), *id.Ref()) + assert.Nil(t, (&DatasetSchemaID{}).Ref()) } func TestDatasetSchemaID_Contains(t *testing.T) { id := NewDatasetSchemaID() id2 := NewDatasetSchemaID() assert.True(t, id.Contains([]DatasetSchemaID{id, id2})) + assert.False(t, DatasetSchemaID{}.Contains([]DatasetSchemaID{id, id2, {}})) assert.False(t, id.Contains([]DatasetSchemaID{id2})) } func TestDatasetSchemaID_CopyRef(t *testing.T) { - id := New() - subId := DatasetSchemaIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewDatasetSchemaID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*DatasetSchemaID)(nil).CopyRef()) } func TestDatasetSchemaID_IDRef(t *testing.T) { id := New() - subId := DatasetSchemaIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := DatasetSchemaIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&DatasetSchemaID{}).IDRef()) + assert.Nil(t, (*DatasetSchemaID)(nil).IDRef()) } func TestDatasetSchemaID_StringRef(t *testing.T) { - id := New() - subId := DatasetSchemaIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewDatasetSchemaID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&DatasetSchemaID{}).StringRef()) + assert.Nil(t, (*DatasetSchemaID)(nil).StringRef()) } func TestDatasetSchemaID_MarhsalJSON(t *testing.T) { - id := New() - subId := DatasetSchemaIDFromRefID(&id) + id := NewDatasetSchemaID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&DatasetSchemaID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetSchemaID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestDatasetSchemaID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &DatasetSchemaID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustDatasetSchemaID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &DatasetSchemaID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestDatasetSchemaID_MarshalText(t *testing.T) { id := New() - subId := DatasetSchemaIDFromRefID(&id) + res, err := DatasetSchemaIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&DatasetSchemaID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*DatasetSchemaID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestDatasetSchemaID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &DatasetSchemaID{} - - err := subId.UnmarshalText(text) - + id2 := &DatasetSchemaID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestDatasetSchemaID_IsNil(t *testing.T) { - subId := DatasetSchemaID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *DatasetSchemaIDFromRefID(&id) + assert.True(t, DatasetSchemaID{}.IsNil()) + assert.False(t, NewDatasetSchemaID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestDatasetSchemaID_IsNilRef(t *testing.T) { + assert.True(t, DatasetSchemaID{}.Ref().IsNilRef()) + assert.True(t, (*DatasetSchemaID)(nil).IsNilRef()) + assert.False(t, NewDatasetSchemaID().Ref().IsNilRef()) } -func TestDatasetSchemaIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestDatasetSchemaIDsToStrings(t *testing.T) { + tests := []struct { name string input []DatasetSchemaID expected []string @@ -321,19 +307,17 @@ func TestDatasetSchemaIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, DatasetSchemaIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, DatasetSchemaIDsToStrings(tt.input)) }) } - } func TestDatasetSchemaIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestDatasetSchemaIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestDatasetSchemaIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := DatasetSchemaIDsFrom(tc.input) if tc.expected.err != nil { - _, err := DatasetSchemaIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := DatasetSchemaIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestDatasetSchemaIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []DatasetSchemaID @@ -449,25 +431,22 @@ func TestDatasetSchemaIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []DatasetSchemaID @@ -493,21 +472,18 @@ func TestDatasetSchemaIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetSchemaID expected []ID @@ -537,28 +513,25 @@ func TestDatasetSchemaIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestDatasetSchemaIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustDatasetSchemaID(id1.String()) + id21 := MustDatasetSchemaID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustDatasetSchemaID(id2.String()) + id22 := MustDatasetSchemaID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustDatasetSchemaID(id3.String()) + id23 := MustDatasetSchemaID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*DatasetSchemaID expected []*ID @@ -570,39 +543,35 @@ func TestDatasetSchemaIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*DatasetSchemaID{&subId1}, + input: []*DatasetSchemaID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*DatasetSchemaID{&subId1, &subId2, &subId3}, + input: []*DatasetSchemaID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := DatasetSchemaIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewDatasetSchemaIDSet(t *testing.T) { DatasetSchemaIdSet := NewDatasetSchemaIDSet() - assert.NotNil(t, DatasetSchemaIdSet) assert.Empty(t, DatasetSchemaIdSet.m) assert.Empty(t, DatasetSchemaIdSet.s) } func TestDatasetSchemaIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []DatasetSchemaID expected *DatasetSchemaIDSet @@ -663,24 +632,19 @@ func TestDatasetSchemaIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetSchemaIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetSchemaIDSet_AddRef(t *testing.T) { - t.Parallel() - - DatasetSchemaId := MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaID expected *DatasetSchemaIDSet @@ -695,7 +659,7 @@ func TestDatasetSchemaIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &DatasetSchemaId, + input: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &DatasetSchemaIDSet{ m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestDatasetSchemaIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewDatasetSchemaIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestDatasetSchemaIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - DatasetSchemaIDSet - DatasetSchemaID - } + tests := []struct { + name string + target *DatasetSchemaIDSet + input DatasetSchemaID expected bool }{ { - name: "Empty Set", - input: struct { - DatasetSchemaIDSet - DatasetSchemaID - }{DatasetSchemaIDSet: DatasetSchemaIDSet{}, DatasetSchemaID: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &DatasetSchemaIDSet{}, + input: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - DatasetSchemaIDSet - DatasetSchemaID - }{DatasetSchemaIDSet: DatasetSchemaIDSet{ + target: &DatasetSchemaIDSet{ m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetSchemaID: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - DatasetSchemaIDSet - DatasetSchemaID - }{DatasetSchemaIDSet: DatasetSchemaIDSet{ + target: &DatasetSchemaIDSet{ m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, DatasetSchemaID: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.DatasetSchemaIDSet.Has(tc.input.DatasetSchemaID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestDatasetSchemaIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input DatasetSchemaIDSet - expected DatasetSchemaIDSet + input *DatasetSchemaIDSet + expected *DatasetSchemaIDSet }{ { - name: "Empty Set", - input: DatasetSchemaIDSet{}, - expected: DatasetSchemaIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &DatasetSchemaIDSet{}, + expected: &DatasetSchemaIDSet{}, }, { - name: "Set Contains the element", - input: DatasetSchemaIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &DatasetSchemaIDSet{ m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: DatasetSchemaIDSet{ + expected: &DatasetSchemaIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestDatasetSchemaIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaIDSet expected []DatasetSchemaID }{ { - name: "Empty slice", + name: "Empty", input: &DatasetSchemaIDSet{ m: map[DatasetSchemaID]struct{}{}, s: nil, }, expected: make([]DatasetSchemaID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &DatasetSchemaIDSet{ @@ -854,20 +808,17 @@ func TestDatasetSchemaIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestDatasetSchemaIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *DatasetSchemaIDSet expected *DatasetSchemaIDSet @@ -922,21 +873,19 @@ func TestDatasetSchemaIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestDatasetSchemaIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *DatasetSchemaIDSet @@ -944,6 +893,23 @@ func TestDatasetSchemaIDSet_Merge(t *testing.T) { } expected *DatasetSchemaIDSet }{ + { + name: "Nil Set", + input: struct { + a *DatasetSchemaIDSet + b *DatasetSchemaIDSet + }{ + a: &DatasetSchemaIDSet{ + m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &DatasetSchemaIDSet{ + m: map[DatasetSchemaID]struct{}{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []DatasetSchemaID{MustDatasetSchemaID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestDatasetSchemaIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/id.go b/pkg/id/id.go index 8645ad07..c821a30e 100644 --- a/pkg/id/id.go +++ b/pkg/id/id.go @@ -53,7 +53,7 @@ func FromID(id string) (ID, error) { } func FromIDRef(id *string) *ID { - if id == nil { + if id == nil || *id == "" { return nil } parsedID, err := parseID(*id) diff --git a/pkg/id/id.tmpl b/pkg/id/id.tmpl index aad5207d..f20661ee 100644 --- a/pkg/id/id.tmpl +++ b/pkg/id/id.tmpl @@ -44,7 +44,7 @@ func {{$name}}IDFromRef(i *string) *{{$name}}ID { // {{$name}}IDFromRefID generates a new {{$name}}ID from a ref of a generic ID. func {{$name}}IDFromRefID(i *ID) *{{$name}}ID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := {{$name}}ID(*i) @@ -58,28 +58,40 @@ func (d {{$name}}ID) ID() ID { // String returns a string representation. func (d {{$name}}ID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d {{$name}}ID) GoString() string { - return "id.{{$name}}ID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d {{$name}}ID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d {{$name}}ID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d {{$name}}ID) GoString() string { + return "{{$name}}ID(" + d.String() + ")" } // Ref returns a reference. func (d {{$name}}ID) Ref() *{{$name}}ID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d {{$name}}ID) Contains(ids []{{$name}}ID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d {{$name}}ID) Contains(ids []{{$name}}ID) bool { // CopyRef returns a copy of a reference. func (d *{{$name}}ID) CopyRef() *{{$name}}ID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *{{$name}}ID) CopyRef() *{{$name}}ID { // IDRef returns a reference of a domain id. func (d *{{$name}}ID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *{{$name}}ID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *{{$name}}ID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *{{$name}}ID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *{{$name}}ID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *{{$name}}ID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *{{$name}}ID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *{{$name}}ID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d {{$name}}ID) IsNil() bool { return ID(d).IsNil() } -// {{$name}}IDToKeys converts IDs into a string slice. -func {{$name}}IDToKeys(ids []{{$name}}ID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *{{$name}}ID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// {{$name}}IDsToStrings converts IDs into a string slice. +func {{$name}}IDsToStrings(ids []{{$name}}ID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // {{$name}}IDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *{{$name}}IDSet) Clone() *{{$name}}IDSet { // Merge returns a merged set func (s *{{$name}}IDSet) Merge(s2 *{{$name}}IDSet) *{{$name}}IDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/id_test.go b/pkg/id/id_test.go index 2becc4dc..0b90dada 100644 --- a/pkg/id/id_test.go +++ b/pkg/id/id_test.go @@ -331,13 +331,11 @@ func TestID_generateAllID(t *testing.T) { func TestID_parseID(t *testing.T) { _, err := parseID("") - - assert.True(t, errors.As(ErrInvalidID, &err)) + assert.Error(t, err) id, err := parseID("01f2r7kg1fvvffp0gmexgy5hxy") - assert.Nil(t, err) - assert.EqualValues(t, strings.ToLower(id.String()), "01f2r7kg1fvvffp0gmexgy5hxy") + assert.Equal(t, strings.ToLower(id.String()), "01f2r7kg1fvvffp0gmexgy5hxy") } func TestID_includeUpperCase(t *testing.T) { diff --git a/pkg/id/id_test.tmpl b/pkg/id/id_test.tmpl index c8f57ec6..6778786a 100644 --- a/pkg/id/id_test.tmpl +++ b/pkg/id/id_test.tmpl @@ -12,19 +12,16 @@ import ( "github.com/stretchr/testify/assert" ) - func TestNew{{$name}}ID(t *testing.T) { id := New{{$name}}ID() - assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) - assert.Nil(t, err) + assert.NotNil(t, id) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) + assert.Nil(t, err) } func Test{{$name}}IDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -39,8 +36,8 @@ func Test{{$name}}IDFrom(t *testing.T) { result {{$name}}ID err error }{ - {{$name}}ID{}, - ErrInvalidID, + result: {{$name}}ID{}, + err: ErrInvalidID, }, }, { @@ -50,8 +47,8 @@ func Test{{$name}}IDFrom(t *testing.T) { result {{$name}}ID err error }{ - {{$name}}ID{}, - ErrInvalidID, + result: {{$name}}ID{}, + err: ErrInvalidID, }, }, { @@ -61,27 +58,26 @@ func Test{{$name}}IDFrom(t *testing.T) { result {{$name}}ID err error }{ - {{$name}}ID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: {{$name}}ID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := {{$name}}IDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := {{$name}}IDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMust{{$name}}ID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -104,23 +100,23 @@ func TestMust{{$name}}ID(t *testing.T) { expected: {{$name}}ID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := Must{{$name}}ID(tc.input) - assert.Equal(tt, tc.expected, result) + result := Must{{$name}}ID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func Test{{$name}}IDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *{{$name}}ID @@ -141,159 +137,149 @@ func Test{{$name}}IDFromRef(t *testing.T) { expected: &{{$name}}ID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := {{$name}}IDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := {{$name}}IDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func Test{{$name}}IDFromRefID(t *testing.T) { id := New() - - subId := {{$name}}IDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := {{$name}}IDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, {{$name}}IDFromRefID(nil)) + assert.Nil(t, {{$name}}IDFromRefID(&ID{})) } func Test{{$name}}ID_ID(t *testing.T) { id := New() - subId := {{$name}}IDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := {{$name}}IDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func Test{{$name}}ID_String(t *testing.T) { id := New() - subId := {{$name}}IDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := {{$name}}IDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", {{$name}}ID{}.String()) } -func Test{{$name}}ID_GoString(t *testing.T) { - id := New() - subId := {{$name}}IDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.{{$name}}ID(" + id.String() + ")") +func Test{{$name}}ID_RefString(t *testing.T) { + id := New{{$name}}ID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, {{$name}}ID{}.RefString()) } -func Test{{$name}}ID_RefString(t *testing.T) { +func Test{{$name}}ID_GoString(t *testing.T) { id := New() - subId := {{$name}}IDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := {{$name}}IDFromRefID(&id) + assert.Equal(t, "{{$name}}ID(" + id.String() + ")", id2.GoString()) + assert.Equal(t, "{{$name}}ID()", {{$name}}ID{}.GoString()) } func Test{{$name}}ID_Ref(t *testing.T) { - id := New() - subId := {{$name}}IDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := New{{$name}}ID() + assert.Equal(t, {{$name}}ID(id), *id.Ref()) + assert.Nil(t, (&{{$name}}ID{}).Ref()) } func Test{{$name}}ID_Contains(t *testing.T) { id := New{{$name}}ID() id2 := New{{$name}}ID() assert.True(t, id.Contains([]{{$name}}ID{id, id2})) + assert.False(t, {{$name}}ID{}.Contains([]{{$name}}ID{id, id2, {}})) assert.False(t, id.Contains([]{{$name}}ID{id2})) } func Test{{$name}}ID_CopyRef(t *testing.T) { - id := New() - subId := {{$name}}IDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := New{{$name}}ID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*{{$name}}ID)(nil).CopyRef()) } func Test{{$name}}ID_IDRef(t *testing.T) { id := New() - subId := {{$name}}IDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := {{$name}}IDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&{{$name}}ID{}).IDRef()) + assert.Nil(t, (*{{$name}}ID)(nil).IDRef()) } func Test{{$name}}ID_StringRef(t *testing.T) { - id := New() - subId := {{$name}}IDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := New{{$name}}ID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&{{$name}}ID{}).StringRef()) + assert.Nil(t, (*{{$name}}ID)(nil).StringRef()) } func Test{{$name}}ID_MarhsalJSON(t *testing.T) { - id := New() - subId := {{$name}}IDFromRefID(&id) + id := New{{$name}}ID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&{{$name}}ID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*{{$name}}ID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func Test{{$name}}ID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &{{$name}}ID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := Must{{$name}}ID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &{{$name}}ID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func Test{{$name}}ID_MarshalText(t *testing.T) { id := New() - subId := {{$name}}IDFromRefID(&id) + res, err := {{$name}}IDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&{{$name}}ID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*{{$name}}ID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func Test{{$name}}ID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &{{$name}}ID{} - - err := subId.UnmarshalText(text) - + id2 := &{{$name}}ID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func Test{{$name}}ID_IsNil(t *testing.T) { - subId := {{$name}}ID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *{{$name}}IDFromRefID(&id) + assert.True(t, {{$name}}ID{}.IsNil()) + assert.False(t, New{{$name}}ID().IsNil()) +} - assert.False(t, subId.IsNil()) +func Test{{$name}}ID_IsNilRef(t *testing.T) { + assert.True(t, {{$name}}ID{}.Ref().IsNilRef()) + assert.True(t, (*{{$name}}ID)(nil).IsNilRef()) + assert.False(t, New{{$name}}ID().Ref().IsNilRef()) } -func Test{{$name}}IDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func Test{{$name}}IDsToStrings(t *testing.T) { + tests := []struct { name string input []{{$name}}ID expected []string @@ -323,19 +309,17 @@ func Test{{$name}}IDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, {{$name}}IDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, {{$name}}IDsToStrings(tt.input)) }) } - } func Test{{$name}}IDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -344,7 +328,7 @@ func Test{{$name}}IDsFrom(t *testing.T) { } }{ { - name: "Empty slice", + name: "Empty slice", input: make([]string, 0), expected: struct { res []{{$name}}ID @@ -355,7 +339,7 @@ func Test{{$name}}IDsFrom(t *testing.T) { }, }, { - name: "1 element", + name: "1 element", input: []string{"01f3zhcaq35403zdjnd6dcm0t2"}, expected: struct { res []{{$name}}ID @@ -385,10 +369,10 @@ func Test{{$name}}IDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -401,27 +385,25 @@ func Test{{$name}}IDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := {{$name}}IDsFrom(tc.input) if tc.expected.err != nil { - _, err := {{$name}}IDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := {{$name}}IDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func Test{{$name}}IDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []{{$name}}ID @@ -451,25 +433,22 @@ func Test{{$name}}IDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := {{$name}}IDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func Test{{$name}}IDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []{{$name}}ID @@ -495,21 +474,18 @@ func Test{{$name}}IDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := {{$name}}IDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func Test{{$name}}IDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []{{$name}}ID expected []ID @@ -539,28 +515,25 @@ func Test{{$name}}IDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := {{$name}}IDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func Test{{$name}}IDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := Must{{$name}}ID(id1.String()) + id21 := Must{{$name}}ID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := Must{{$name}}ID(id2.String()) + id22 := Must{{$name}}ID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := Must{{$name}}ID(id3.String()) + id23 := Must{{$name}}ID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*{{$name}}ID expected []*ID @@ -572,54 +545,50 @@ func Test{{$name}}IDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*{{$name}}ID{&subId1}, + input: []*{{$name}}ID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*{{$name}}ID{&subId1, &subId2, &subId3}, + input: []*{{$name}}ID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := {{$name}}IDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNew{{$name}}IDSet(t *testing.T) { {{$name}}IdSet := New{{$name}}IDSet() - assert.NotNil(t, {{$name}}IdSet) assert.Empty(t, {{$name}}IdSet.m) assert.Empty(t, {{$name}}IdSet.s) } func Test{{$name}}IDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []{{$name}}ID expected *{{$name}}IDSet }{ { - name: "Empty slice", - input: make([]{{$name}}ID, 0), + name: "Empty slice", + input: make([]{{$name}}ID, 0), expected: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{}, s: nil, }, }, { - name: "1 element", - input: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "1 element", + input: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, expected: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -646,7 +615,7 @@ func Test{{$name}}IDSet_Add(t *testing.T) { }, }, { - name: "multiple elements with duplication", + name: "multiple elements with duplication", input: []{{$name}}ID{ Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"), Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"), @@ -665,31 +634,26 @@ func Test{{$name}}IDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := New{{$name}}IDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func Test{{$name}}IDSet_AddRef(t *testing.T) { - t.Parallel() - - {{$name}}Id := Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *{{$name}}ID expected *{{$name}}IDSet }{ { - name: "Empty slice", - input: nil, + name: "Empty slice", + input: nil, expected: &{{$name}}IDSet{ m: nil, s: nil, @@ -697,7 +661,7 @@ func Test{{$name}}IDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &{{$name}}Id, + input: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -705,127 +669,117 @@ func Test{{$name}}IDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := New{{$name}}IDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func Test{{$name}}IDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input struct { - {{$name}}IDSet - {{$name}}ID - } + target *{{$name}}IDSet + input {{$name}}ID expected bool }{ { - name: "Empty Set", - input: struct { - {{$name}}IDSet - {{$name}}ID - }{ {{$name}}IDSet: {{$name}}IDSet{}, {{$name}}ID: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &{{$name}}IDSet{}, + input: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { - name: "Set Contains the element", - input: struct { - {{$name}}IDSet - {{$name}}ID - }{ {{$name}}IDSet: {{$name}}IDSet{ + name: "Set Contains the element", + target: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, {{$name}}ID: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - {{$name}}IDSet - {{$name}}ID - }{ {{$name}}IDSet: {{$name}}IDSet{ + target: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, {{$name}}ID: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.{{$name}}IDSet.Has(tc.input.{{$name}}ID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func Test{{$name}}IDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input {{$name}}IDSet - expected {{$name}}IDSet + input *{{$name}}IDSet + expected *{{$name}}IDSet }{ { - name: "Empty Set", - input: {{$name}}IDSet{}, - expected: {{$name}}IDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &{{$name}}IDSet{}, + expected: &{{$name}}IDSet{}, }, { - name: "Set Contains the element", - input: {{$name}}IDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: {{$name}}IDSet{ + expected: &{{$name}}IDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func Test{{$name}}IDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *{{$name}}IDSet expected []{{$name}}ID }{ { - name: "Empty slice", + name: "Empty", input: &{{$name}}IDSet{ m: map[{{$name}}ID]struct{}{}, s: nil, }, expected: make([]{{$name}}ID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &{{$name}}IDSet{ @@ -856,20 +810,17 @@ func Test{{$name}}IDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func Test{{$name}}IDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *{{$name}}IDSet expected *{{$name}}IDSet @@ -924,21 +875,19 @@ func Test{{$name}}IDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func Test{{$name}}IDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *{{$name}}IDSet @@ -946,6 +895,23 @@ func Test{{$name}}IDSet_Merge(t *testing.T) { } expected *{{$name}}IDSet }{ + { + name: "Nil Set", + input: struct { + a *{{$name}}IDSet + b *{{$name}}IDSet + }{ + a: &{{$name}}IDSet{ + m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &{{$name}}IDSet{ + m: map[{{$name}}ID]struct{}{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []{{$name}}ID{Must{{$name}}ID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1002,12 +968,11 @@ func Test{{$name}}IDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/infobox_field_gen.go b/pkg/id/infobox_field_gen.go index 40758876..fed9630c 100644 --- a/pkg/id/infobox_field_gen.go +++ b/pkg/id/infobox_field_gen.go @@ -44,7 +44,7 @@ func InfoboxFieldIDFromRef(i *string) *InfoboxFieldID { // InfoboxFieldIDFromRefID generates a new InfoboxFieldID from a ref of a generic ID. func InfoboxFieldIDFromRefID(i *ID) *InfoboxFieldID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := InfoboxFieldID(*i) @@ -58,28 +58,40 @@ func (d InfoboxFieldID) ID() ID { // String returns a string representation. func (d InfoboxFieldID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d InfoboxFieldID) GoString() string { - return "id.InfoboxFieldID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d InfoboxFieldID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d InfoboxFieldID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d InfoboxFieldID) GoString() string { + return "InfoboxFieldID(" + d.String() + ")" } // Ref returns a reference. func (d InfoboxFieldID) Ref() *InfoboxFieldID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d InfoboxFieldID) Contains(ids []InfoboxFieldID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d InfoboxFieldID) Contains(ids []InfoboxFieldID) bool { // CopyRef returns a copy of a reference. func (d *InfoboxFieldID) CopyRef() *InfoboxFieldID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *InfoboxFieldID) CopyRef() *InfoboxFieldID { // IDRef returns a reference of a domain id. func (d *InfoboxFieldID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *InfoboxFieldID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *InfoboxFieldID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *InfoboxFieldID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *InfoboxFieldID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *InfoboxFieldID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *InfoboxFieldID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *InfoboxFieldID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d InfoboxFieldID) IsNil() bool { return ID(d).IsNil() } -// InfoboxFieldIDToKeys converts IDs into a string slice. -func InfoboxFieldIDToKeys(ids []InfoboxFieldID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *InfoboxFieldID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// InfoboxFieldIDsToStrings converts IDs into a string slice. +func InfoboxFieldIDsToStrings(ids []InfoboxFieldID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // InfoboxFieldIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *InfoboxFieldIDSet) Clone() *InfoboxFieldIDSet { // Merge returns a merged set func (s *InfoboxFieldIDSet) Merge(s2 *InfoboxFieldIDSet) *InfoboxFieldIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/infobox_field_gen_test.go b/pkg/id/infobox_field_gen_test.go index 8c1fd074..3f2050c9 100644 --- a/pkg/id/infobox_field_gen_test.go +++ b/pkg/id/infobox_field_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewInfoboxFieldID(t *testing.T) { id := NewInfoboxFieldID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestInfoboxFieldIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestInfoboxFieldIDFrom(t *testing.T) { result InfoboxFieldID err error }{ - InfoboxFieldID{}, - ErrInvalidID, + result: InfoboxFieldID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestInfoboxFieldIDFrom(t *testing.T) { result InfoboxFieldID err error }{ - InfoboxFieldID{}, - ErrInvalidID, + result: InfoboxFieldID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestInfoboxFieldIDFrom(t *testing.T) { result InfoboxFieldID err error }{ - InfoboxFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: InfoboxFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := InfoboxFieldIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := InfoboxFieldIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustInfoboxFieldID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustInfoboxFieldID(t *testing.T) { expected: InfoboxFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustInfoboxFieldID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustInfoboxFieldID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestInfoboxFieldIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *InfoboxFieldID @@ -139,159 +135,149 @@ func TestInfoboxFieldIDFromRef(t *testing.T) { expected: &InfoboxFieldID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := InfoboxFieldIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := InfoboxFieldIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestInfoboxFieldIDFromRefID(t *testing.T) { id := New() - - subId := InfoboxFieldIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := InfoboxFieldIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, InfoboxFieldIDFromRefID(nil)) + assert.Nil(t, InfoboxFieldIDFromRefID(&ID{})) } func TestInfoboxFieldID_ID(t *testing.T) { id := New() - subId := InfoboxFieldIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := InfoboxFieldIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestInfoboxFieldID_String(t *testing.T) { id := New() - subId := InfoboxFieldIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := InfoboxFieldIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", InfoboxFieldID{}.String()) } -func TestInfoboxFieldID_GoString(t *testing.T) { - id := New() - subId := InfoboxFieldIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.InfoboxFieldID("+id.String()+")") +func TestInfoboxFieldID_RefString(t *testing.T) { + id := NewInfoboxFieldID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, InfoboxFieldID{}.RefString()) } -func TestInfoboxFieldID_RefString(t *testing.T) { +func TestInfoboxFieldID_GoString(t *testing.T) { id := New() - subId := InfoboxFieldIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := InfoboxFieldIDFromRefID(&id) + assert.Equal(t, "InfoboxFieldID("+id.String()+")", id2.GoString()) + assert.Equal(t, "InfoboxFieldID()", InfoboxFieldID{}.GoString()) } func TestInfoboxFieldID_Ref(t *testing.T) { - id := New() - subId := InfoboxFieldIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewInfoboxFieldID() + assert.Equal(t, InfoboxFieldID(id), *id.Ref()) + assert.Nil(t, (&InfoboxFieldID{}).Ref()) } func TestInfoboxFieldID_Contains(t *testing.T) { id := NewInfoboxFieldID() id2 := NewInfoboxFieldID() assert.True(t, id.Contains([]InfoboxFieldID{id, id2})) + assert.False(t, InfoboxFieldID{}.Contains([]InfoboxFieldID{id, id2, {}})) assert.False(t, id.Contains([]InfoboxFieldID{id2})) } func TestInfoboxFieldID_CopyRef(t *testing.T) { - id := New() - subId := InfoboxFieldIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewInfoboxFieldID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*InfoboxFieldID)(nil).CopyRef()) } func TestInfoboxFieldID_IDRef(t *testing.T) { id := New() - subId := InfoboxFieldIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := InfoboxFieldIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&InfoboxFieldID{}).IDRef()) + assert.Nil(t, (*InfoboxFieldID)(nil).IDRef()) } func TestInfoboxFieldID_StringRef(t *testing.T) { - id := New() - subId := InfoboxFieldIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewInfoboxFieldID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&InfoboxFieldID{}).StringRef()) + assert.Nil(t, (*InfoboxFieldID)(nil).StringRef()) } func TestInfoboxFieldID_MarhsalJSON(t *testing.T) { - id := New() - subId := InfoboxFieldIDFromRefID(&id) + id := NewInfoboxFieldID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&InfoboxFieldID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*InfoboxFieldID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestInfoboxFieldID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &InfoboxFieldID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustInfoboxFieldID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &InfoboxFieldID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestInfoboxFieldID_MarshalText(t *testing.T) { id := New() - subId := InfoboxFieldIDFromRefID(&id) + res, err := InfoboxFieldIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&InfoboxFieldID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*InfoboxFieldID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestInfoboxFieldID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &InfoboxFieldID{} - - err := subId.UnmarshalText(text) - + id2 := &InfoboxFieldID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestInfoboxFieldID_IsNil(t *testing.T) { - subId := InfoboxFieldID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *InfoboxFieldIDFromRefID(&id) + assert.True(t, InfoboxFieldID{}.IsNil()) + assert.False(t, NewInfoboxFieldID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestInfoboxFieldID_IsNilRef(t *testing.T) { + assert.True(t, InfoboxFieldID{}.Ref().IsNilRef()) + assert.True(t, (*InfoboxFieldID)(nil).IsNilRef()) + assert.False(t, NewInfoboxFieldID().Ref().IsNilRef()) } -func TestInfoboxFieldIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestInfoboxFieldIDsToStrings(t *testing.T) { + tests := []struct { name string input []InfoboxFieldID expected []string @@ -321,19 +307,17 @@ func TestInfoboxFieldIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, InfoboxFieldIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, InfoboxFieldIDsToStrings(tt.input)) }) } - } func TestInfoboxFieldIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestInfoboxFieldIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestInfoboxFieldIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := InfoboxFieldIDsFrom(tc.input) if tc.expected.err != nil { - _, err := InfoboxFieldIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := InfoboxFieldIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestInfoboxFieldIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []InfoboxFieldID @@ -449,25 +431,22 @@ func TestInfoboxFieldIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := InfoboxFieldIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestInfoboxFieldIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []InfoboxFieldID @@ -493,21 +472,18 @@ func TestInfoboxFieldIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := InfoboxFieldIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestInfoboxFieldIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []InfoboxFieldID expected []ID @@ -537,28 +513,25 @@ func TestInfoboxFieldIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := InfoboxFieldIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestInfoboxFieldIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustInfoboxFieldID(id1.String()) + id21 := MustInfoboxFieldID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustInfoboxFieldID(id2.String()) + id22 := MustInfoboxFieldID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustInfoboxFieldID(id3.String()) + id23 := MustInfoboxFieldID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*InfoboxFieldID expected []*ID @@ -570,39 +543,35 @@ func TestInfoboxFieldIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*InfoboxFieldID{&subId1}, + input: []*InfoboxFieldID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*InfoboxFieldID{&subId1, &subId2, &subId3}, + input: []*InfoboxFieldID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := InfoboxFieldIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewInfoboxFieldIDSet(t *testing.T) { InfoboxFieldIdSet := NewInfoboxFieldIDSet() - assert.NotNil(t, InfoboxFieldIdSet) assert.Empty(t, InfoboxFieldIdSet.m) assert.Empty(t, InfoboxFieldIdSet.s) } func TestInfoboxFieldIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []InfoboxFieldID expected *InfoboxFieldIDSet @@ -663,24 +632,19 @@ func TestInfoboxFieldIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewInfoboxFieldIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestInfoboxFieldIDSet_AddRef(t *testing.T) { - t.Parallel() - - InfoboxFieldId := MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *InfoboxFieldID expected *InfoboxFieldIDSet @@ -695,7 +659,7 @@ func TestInfoboxFieldIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &InfoboxFieldId, + input: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &InfoboxFieldIDSet{ m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestInfoboxFieldIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewInfoboxFieldIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestInfoboxFieldIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - InfoboxFieldIDSet - InfoboxFieldID - } + tests := []struct { + name string + target *InfoboxFieldIDSet + input InfoboxFieldID expected bool }{ { - name: "Empty Set", - input: struct { - InfoboxFieldIDSet - InfoboxFieldID - }{InfoboxFieldIDSet: InfoboxFieldIDSet{}, InfoboxFieldID: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &InfoboxFieldIDSet{}, + input: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - InfoboxFieldIDSet - InfoboxFieldID - }{InfoboxFieldIDSet: InfoboxFieldIDSet{ + target: &InfoboxFieldIDSet{ m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, InfoboxFieldID: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - InfoboxFieldIDSet - InfoboxFieldID - }{InfoboxFieldIDSet: InfoboxFieldIDSet{ + target: &InfoboxFieldIDSet{ m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, InfoboxFieldID: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.InfoboxFieldIDSet.Has(tc.input.InfoboxFieldID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestInfoboxFieldIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input InfoboxFieldIDSet - expected InfoboxFieldIDSet + input *InfoboxFieldIDSet + expected *InfoboxFieldIDSet }{ { - name: "Empty Set", - input: InfoboxFieldIDSet{}, - expected: InfoboxFieldIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &InfoboxFieldIDSet{}, + expected: &InfoboxFieldIDSet{}, }, { - name: "Set Contains the element", - input: InfoboxFieldIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &InfoboxFieldIDSet{ m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: InfoboxFieldIDSet{ + expected: &InfoboxFieldIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestInfoboxFieldIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *InfoboxFieldIDSet expected []InfoboxFieldID }{ { - name: "Empty slice", + name: "Empty", input: &InfoboxFieldIDSet{ m: map[InfoboxFieldID]struct{}{}, s: nil, }, expected: make([]InfoboxFieldID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &InfoboxFieldIDSet{ @@ -854,20 +808,17 @@ func TestInfoboxFieldIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestInfoboxFieldIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *InfoboxFieldIDSet expected *InfoboxFieldIDSet @@ -922,21 +873,19 @@ func TestInfoboxFieldIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestInfoboxFieldIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *InfoboxFieldIDSet @@ -944,6 +893,23 @@ func TestInfoboxFieldIDSet_Merge(t *testing.T) { } expected *InfoboxFieldIDSet }{ + { + name: "Nil Set", + input: struct { + a *InfoboxFieldIDSet + b *InfoboxFieldIDSet + }{ + a: &InfoboxFieldIDSet{ + m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &InfoboxFieldIDSet{ + m: map[InfoboxFieldID]struct{}{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []InfoboxFieldID{MustInfoboxFieldID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestInfoboxFieldIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/layer_gen.go b/pkg/id/layer_gen.go index d49abdcf..1c22b32d 100644 --- a/pkg/id/layer_gen.go +++ b/pkg/id/layer_gen.go @@ -44,7 +44,7 @@ func LayerIDFromRef(i *string) *LayerID { // LayerIDFromRefID generates a new LayerID from a ref of a generic ID. func LayerIDFromRefID(i *ID) *LayerID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := LayerID(*i) @@ -58,28 +58,40 @@ func (d LayerID) ID() ID { // String returns a string representation. func (d LayerID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d LayerID) GoString() string { - return "id.LayerID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d LayerID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d LayerID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d LayerID) GoString() string { + return "LayerID(" + d.String() + ")" } // Ref returns a reference. func (d LayerID) Ref() *LayerID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d LayerID) Contains(ids []LayerID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d LayerID) Contains(ids []LayerID) bool { // CopyRef returns a copy of a reference. func (d *LayerID) CopyRef() *LayerID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *LayerID) CopyRef() *LayerID { // IDRef returns a reference of a domain id. func (d *LayerID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *LayerID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *LayerID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *LayerID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *LayerID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *LayerID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *LayerID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *LayerID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d LayerID) IsNil() bool { return ID(d).IsNil() } -// LayerIDToKeys converts IDs into a string slice. -func LayerIDToKeys(ids []LayerID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *LayerID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// LayerIDsToStrings converts IDs into a string slice. +func LayerIDsToStrings(ids []LayerID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // LayerIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *LayerIDSet) Clone() *LayerIDSet { // Merge returns a merged set func (s *LayerIDSet) Merge(s2 *LayerIDSet) *LayerIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/layer_gen_test.go b/pkg/id/layer_gen_test.go index bfc9218e..c68fd3fb 100644 --- a/pkg/id/layer_gen_test.go +++ b/pkg/id/layer_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewLayerID(t *testing.T) { id := NewLayerID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestLayerIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestLayerIDFrom(t *testing.T) { result LayerID err error }{ - LayerID{}, - ErrInvalidID, + result: LayerID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestLayerIDFrom(t *testing.T) { result LayerID err error }{ - LayerID{}, - ErrInvalidID, + result: LayerID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestLayerIDFrom(t *testing.T) { result LayerID err error }{ - LayerID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: LayerID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := LayerIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := LayerIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustLayerID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustLayerID(t *testing.T) { expected: LayerID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustLayerID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustLayerID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestLayerIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *LayerID @@ -139,159 +135,149 @@ func TestLayerIDFromRef(t *testing.T) { expected: &LayerID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := LayerIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := LayerIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestLayerIDFromRefID(t *testing.T) { id := New() - - subId := LayerIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := LayerIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, LayerIDFromRefID(nil)) + assert.Nil(t, LayerIDFromRefID(&ID{})) } func TestLayerID_ID(t *testing.T) { id := New() - subId := LayerIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := LayerIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestLayerID_String(t *testing.T) { id := New() - subId := LayerIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := LayerIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", LayerID{}.String()) } -func TestLayerID_GoString(t *testing.T) { - id := New() - subId := LayerIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.LayerID("+id.String()+")") +func TestLayerID_RefString(t *testing.T) { + id := NewLayerID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, LayerID{}.RefString()) } -func TestLayerID_RefString(t *testing.T) { +func TestLayerID_GoString(t *testing.T) { id := New() - subId := LayerIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := LayerIDFromRefID(&id) + assert.Equal(t, "LayerID("+id.String()+")", id2.GoString()) + assert.Equal(t, "LayerID()", LayerID{}.GoString()) } func TestLayerID_Ref(t *testing.T) { - id := New() - subId := LayerIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewLayerID() + assert.Equal(t, LayerID(id), *id.Ref()) + assert.Nil(t, (&LayerID{}).Ref()) } func TestLayerID_Contains(t *testing.T) { id := NewLayerID() id2 := NewLayerID() assert.True(t, id.Contains([]LayerID{id, id2})) + assert.False(t, LayerID{}.Contains([]LayerID{id, id2, {}})) assert.False(t, id.Contains([]LayerID{id2})) } func TestLayerID_CopyRef(t *testing.T) { - id := New() - subId := LayerIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewLayerID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*LayerID)(nil).CopyRef()) } func TestLayerID_IDRef(t *testing.T) { id := New() - subId := LayerIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := LayerIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&LayerID{}).IDRef()) + assert.Nil(t, (*LayerID)(nil).IDRef()) } func TestLayerID_StringRef(t *testing.T) { - id := New() - subId := LayerIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewLayerID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&LayerID{}).StringRef()) + assert.Nil(t, (*LayerID)(nil).StringRef()) } func TestLayerID_MarhsalJSON(t *testing.T) { - id := New() - subId := LayerIDFromRefID(&id) + id := NewLayerID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&LayerID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*LayerID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestLayerID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &LayerID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustLayerID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &LayerID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestLayerID_MarshalText(t *testing.T) { id := New() - subId := LayerIDFromRefID(&id) + res, err := LayerIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&LayerID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*LayerID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestLayerID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &LayerID{} - - err := subId.UnmarshalText(text) - + id2 := &LayerID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestLayerID_IsNil(t *testing.T) { - subId := LayerID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *LayerIDFromRefID(&id) + assert.True(t, LayerID{}.IsNil()) + assert.False(t, NewLayerID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestLayerID_IsNilRef(t *testing.T) { + assert.True(t, LayerID{}.Ref().IsNilRef()) + assert.True(t, (*LayerID)(nil).IsNilRef()) + assert.False(t, NewLayerID().Ref().IsNilRef()) } -func TestLayerIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestLayerIDsToStrings(t *testing.T) { + tests := []struct { name string input []LayerID expected []string @@ -321,19 +307,17 @@ func TestLayerIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, LayerIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, LayerIDsToStrings(tt.input)) }) } - } func TestLayerIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestLayerIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestLayerIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := LayerIDsFrom(tc.input) if tc.expected.err != nil { - _, err := LayerIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := LayerIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestLayerIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []LayerID @@ -449,25 +431,22 @@ func TestLayerIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := LayerIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestLayerIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []LayerID @@ -493,21 +472,18 @@ func TestLayerIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := LayerIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestLayerIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []LayerID expected []ID @@ -537,28 +513,25 @@ func TestLayerIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := LayerIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestLayerIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustLayerID(id1.String()) + id21 := MustLayerID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustLayerID(id2.String()) + id22 := MustLayerID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustLayerID(id3.String()) + id23 := MustLayerID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*LayerID expected []*ID @@ -570,39 +543,35 @@ func TestLayerIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*LayerID{&subId1}, + input: []*LayerID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*LayerID{&subId1, &subId2, &subId3}, + input: []*LayerID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := LayerIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewLayerIDSet(t *testing.T) { LayerIdSet := NewLayerIDSet() - assert.NotNil(t, LayerIdSet) assert.Empty(t, LayerIdSet.m) assert.Empty(t, LayerIdSet.s) } func TestLayerIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []LayerID expected *LayerIDSet @@ -663,24 +632,19 @@ func TestLayerIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewLayerIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestLayerIDSet_AddRef(t *testing.T) { - t.Parallel() - - LayerId := MustLayerID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *LayerID expected *LayerIDSet @@ -695,7 +659,7 @@ func TestLayerIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &LayerId, + input: MustLayerID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &LayerIDSet{ m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestLayerIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewLayerIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestLayerIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - LayerIDSet - LayerID - } + tests := []struct { + name string + target *LayerIDSet + input LayerID expected bool }{ { - name: "Empty Set", - input: struct { - LayerIDSet - LayerID - }{LayerIDSet: LayerIDSet{}, LayerID: MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &LayerIDSet{}, + input: MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - LayerIDSet - LayerID - }{LayerIDSet: LayerIDSet{ + target: &LayerIDSet{ m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, LayerID: MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - LayerIDSet - LayerID - }{LayerIDSet: LayerIDSet{ + target: &LayerIDSet{ m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, LayerID: MustLayerID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustLayerID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.LayerIDSet.Has(tc.input.LayerID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestLayerIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input LayerIDSet - expected LayerIDSet + input *LayerIDSet + expected *LayerIDSet }{ { - name: "Empty Set", - input: LayerIDSet{}, - expected: LayerIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &LayerIDSet{}, + expected: &LayerIDSet{}, }, { - name: "Set Contains the element", - input: LayerIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &LayerIDSet{ m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: LayerIDSet{ + expected: &LayerIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestLayerIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *LayerIDSet expected []LayerID }{ { - name: "Empty slice", + name: "Empty", input: &LayerIDSet{ m: map[LayerID]struct{}{}, s: nil, }, expected: make([]LayerID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &LayerIDSet{ @@ -854,20 +808,17 @@ func TestLayerIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestLayerIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *LayerIDSet expected *LayerIDSet @@ -922,21 +873,19 @@ func TestLayerIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestLayerIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *LayerIDSet @@ -944,6 +893,23 @@ func TestLayerIDSet_Merge(t *testing.T) { } expected *LayerIDSet }{ + { + name: "Nil Set", + input: struct { + a *LayerIDSet + b *LayerIDSet + }{ + a: &LayerIDSet{ + m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &LayerIDSet{ + m: map[LayerID]struct{}{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []LayerID{MustLayerID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestLayerIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/plugin.go b/pkg/id/plugin.go index d13ed808..8de5c59a 100644 --- a/pkg/id/plugin.go +++ b/pkg/id/plugin.go @@ -105,6 +105,21 @@ func PluginIDFromRef(id *string) *PluginID { return &did } +// Clone duplicates the PluginID +func (d PluginID) Clone() PluginID { + return PluginID{ + name: d.name, + version: d.version, + sys: d.sys, + scene: d.scene.CopyRef(), + } +} + +// IsNil checks if ID is empty or not. +func (d PluginID) IsNil() bool { + return d.name == "" && d.version == "" && d.scene == nil && !d.sys +} + // Name returns a name. func (d PluginID) Name() string { return d.name @@ -201,7 +216,7 @@ func (d *PluginID) UnmarshalText(text []byte) (err error) { } // PluginIDToKeys converts IDs into a string slice. -func PluginIDToKeys(ids []PluginID) []string { +func PluginIDsToStrings(ids []PluginID) []string { keys := make([]string, 0, len(ids)) for _, id := range ids { keys = append(keys, id.String()) diff --git a/pkg/id/plugin_test.go b/pkg/id/plugin_test.go index 49a8b937..5df599d8 100644 --- a/pkg/id/plugin_test.go +++ b/pkg/id/plugin_test.go @@ -330,6 +330,19 @@ func TestPluginIDFromRef(t *testing.T) { } } +func TestPluginID_Clone(t *testing.T) { + p := PluginID{ + name: "aaa", + version: "1.0.0", + sys: false, + scene: NewSceneID().Ref(), + } + c := p.Clone() + + assert.Equal(t, p, c) + assert.NotSame(t, p, c) +} + func TestPluginID_Name(t *testing.T) { plugin := MustPluginID("MyPlugin~1.0.0") @@ -564,7 +577,7 @@ func TestPluginID_UnmarshalText(t *testing.T) { } -func TestPluginIDToKeys(t *testing.T) { +func TestPluginIDsToStrings(t *testing.T) { t.Parallel() testCases := []struct { name string @@ -600,7 +613,7 @@ func TestPluginIDToKeys(t *testing.T) { tc := tc t.Run(tc.name, func(tt *testing.T) { tt.Parallel() - assert.Equal(tt, tc.expected, PluginIDToKeys(tc.input)) + assert.Equal(tt, tc.expected, PluginIDsToStrings(tc.input)) }) } @@ -690,3 +703,30 @@ func TestPluginIDsFrom(t *testing.T) { }) } } + +func TestPluginID_IsNil(t *testing.T) { + tests := []struct { + name string + target PluginID + want bool + }{ + { + name: "present", + target: PluginID{name: "a"}, + want: false, + }, + { + name: "empty", + target: PluginID{}, + want: true, + }, + } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, tt.target.IsNil()) + }) + } +} diff --git a/pkg/id/project_gen.go b/pkg/id/project_gen.go index 883d8c1a..aa29ab43 100644 --- a/pkg/id/project_gen.go +++ b/pkg/id/project_gen.go @@ -44,7 +44,7 @@ func ProjectIDFromRef(i *string) *ProjectID { // ProjectIDFromRefID generates a new ProjectID from a ref of a generic ID. func ProjectIDFromRefID(i *ID) *ProjectID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := ProjectID(*i) @@ -58,28 +58,40 @@ func (d ProjectID) ID() ID { // String returns a string representation. func (d ProjectID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d ProjectID) GoString() string { - return "id.ProjectID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d ProjectID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d ProjectID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d ProjectID) GoString() string { + return "ProjectID(" + d.String() + ")" } // Ref returns a reference. func (d ProjectID) Ref() *ProjectID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d ProjectID) Contains(ids []ProjectID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d ProjectID) Contains(ids []ProjectID) bool { // CopyRef returns a copy of a reference. func (d *ProjectID) CopyRef() *ProjectID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *ProjectID) CopyRef() *ProjectID { // IDRef returns a reference of a domain id. func (d *ProjectID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *ProjectID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *ProjectID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *ProjectID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *ProjectID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *ProjectID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *ProjectID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *ProjectID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d ProjectID) IsNil() bool { return ID(d).IsNil() } -// ProjectIDToKeys converts IDs into a string slice. -func ProjectIDToKeys(ids []ProjectID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *ProjectID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// ProjectIDsToStrings converts IDs into a string slice. +func ProjectIDsToStrings(ids []ProjectID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // ProjectIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *ProjectIDSet) Clone() *ProjectIDSet { // Merge returns a merged set func (s *ProjectIDSet) Merge(s2 *ProjectIDSet) *ProjectIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/project_gen_test.go b/pkg/id/project_gen_test.go index fa8eed3f..22869ed1 100644 --- a/pkg/id/project_gen_test.go +++ b/pkg/id/project_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewProjectID(t *testing.T) { id := NewProjectID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestProjectIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestProjectIDFrom(t *testing.T) { result ProjectID err error }{ - ProjectID{}, - ErrInvalidID, + result: ProjectID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestProjectIDFrom(t *testing.T) { result ProjectID err error }{ - ProjectID{}, - ErrInvalidID, + result: ProjectID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestProjectIDFrom(t *testing.T) { result ProjectID err error }{ - ProjectID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: ProjectID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := ProjectIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := ProjectIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustProjectID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustProjectID(t *testing.T) { expected: ProjectID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustProjectID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustProjectID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestProjectIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *ProjectID @@ -139,159 +135,149 @@ func TestProjectIDFromRef(t *testing.T) { expected: &ProjectID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := ProjectIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := ProjectIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestProjectIDFromRefID(t *testing.T) { id := New() - - subId := ProjectIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := ProjectIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, ProjectIDFromRefID(nil)) + assert.Nil(t, ProjectIDFromRefID(&ID{})) } func TestProjectID_ID(t *testing.T) { id := New() - subId := ProjectIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := ProjectIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestProjectID_String(t *testing.T) { id := New() - subId := ProjectIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := ProjectIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", ProjectID{}.String()) } -func TestProjectID_GoString(t *testing.T) { - id := New() - subId := ProjectIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.ProjectID("+id.String()+")") +func TestProjectID_RefString(t *testing.T) { + id := NewProjectID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, ProjectID{}.RefString()) } -func TestProjectID_RefString(t *testing.T) { +func TestProjectID_GoString(t *testing.T) { id := New() - subId := ProjectIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := ProjectIDFromRefID(&id) + assert.Equal(t, "ProjectID("+id.String()+")", id2.GoString()) + assert.Equal(t, "ProjectID()", ProjectID{}.GoString()) } func TestProjectID_Ref(t *testing.T) { - id := New() - subId := ProjectIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewProjectID() + assert.Equal(t, ProjectID(id), *id.Ref()) + assert.Nil(t, (&ProjectID{}).Ref()) } func TestProjectID_Contains(t *testing.T) { id := NewProjectID() id2 := NewProjectID() assert.True(t, id.Contains([]ProjectID{id, id2})) + assert.False(t, ProjectID{}.Contains([]ProjectID{id, id2, {}})) assert.False(t, id.Contains([]ProjectID{id2})) } func TestProjectID_CopyRef(t *testing.T) { - id := New() - subId := ProjectIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewProjectID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*ProjectID)(nil).CopyRef()) } func TestProjectID_IDRef(t *testing.T) { id := New() - subId := ProjectIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := ProjectIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&ProjectID{}).IDRef()) + assert.Nil(t, (*ProjectID)(nil).IDRef()) } func TestProjectID_StringRef(t *testing.T) { - id := New() - subId := ProjectIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewProjectID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&ProjectID{}).StringRef()) + assert.Nil(t, (*ProjectID)(nil).StringRef()) } func TestProjectID_MarhsalJSON(t *testing.T) { - id := New() - subId := ProjectIDFromRefID(&id) + id := NewProjectID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&ProjectID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*ProjectID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestProjectID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &ProjectID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustProjectID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &ProjectID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestProjectID_MarshalText(t *testing.T) { id := New() - subId := ProjectIDFromRefID(&id) + res, err := ProjectIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&ProjectID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*ProjectID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestProjectID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &ProjectID{} - - err := subId.UnmarshalText(text) - + id2 := &ProjectID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestProjectID_IsNil(t *testing.T) { - subId := ProjectID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *ProjectIDFromRefID(&id) + assert.True(t, ProjectID{}.IsNil()) + assert.False(t, NewProjectID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestProjectID_IsNilRef(t *testing.T) { + assert.True(t, ProjectID{}.Ref().IsNilRef()) + assert.True(t, (*ProjectID)(nil).IsNilRef()) + assert.False(t, NewProjectID().Ref().IsNilRef()) } -func TestProjectIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestProjectIDsToStrings(t *testing.T) { + tests := []struct { name string input []ProjectID expected []string @@ -321,19 +307,17 @@ func TestProjectIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, ProjectIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, ProjectIDsToStrings(tt.input)) }) } - } func TestProjectIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestProjectIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestProjectIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := ProjectIDsFrom(tc.input) if tc.expected.err != nil { - _, err := ProjectIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := ProjectIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestProjectIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []ProjectID @@ -449,25 +431,22 @@ func TestProjectIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ProjectIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestProjectIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []ProjectID @@ -493,21 +472,18 @@ func TestProjectIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ProjectIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestProjectIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []ProjectID expected []ID @@ -537,28 +513,25 @@ func TestProjectIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ProjectIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestProjectIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustProjectID(id1.String()) + id21 := MustProjectID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustProjectID(id2.String()) + id22 := MustProjectID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustProjectID(id3.String()) + id23 := MustProjectID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*ProjectID expected []*ID @@ -570,39 +543,35 @@ func TestProjectIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*ProjectID{&subId1}, + input: []*ProjectID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*ProjectID{&subId1, &subId2, &subId3}, + input: []*ProjectID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := ProjectIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewProjectIDSet(t *testing.T) { ProjectIdSet := NewProjectIDSet() - assert.NotNil(t, ProjectIdSet) assert.Empty(t, ProjectIdSet.m) assert.Empty(t, ProjectIdSet.s) } func TestProjectIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []ProjectID expected *ProjectIDSet @@ -663,24 +632,19 @@ func TestProjectIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewProjectIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestProjectIDSet_AddRef(t *testing.T) { - t.Parallel() - - ProjectId := MustProjectID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *ProjectID expected *ProjectIDSet @@ -695,7 +659,7 @@ func TestProjectIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &ProjectId, + input: MustProjectID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &ProjectIDSet{ m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestProjectIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewProjectIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestProjectIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - ProjectIDSet - ProjectID - } + tests := []struct { + name string + target *ProjectIDSet + input ProjectID expected bool }{ { - name: "Empty Set", - input: struct { - ProjectIDSet - ProjectID - }{ProjectIDSet: ProjectIDSet{}, ProjectID: MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &ProjectIDSet{}, + input: MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - ProjectIDSet - ProjectID - }{ProjectIDSet: ProjectIDSet{ + target: &ProjectIDSet{ m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, ProjectID: MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - ProjectIDSet - ProjectID - }{ProjectIDSet: ProjectIDSet{ + target: &ProjectIDSet{ m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, ProjectID: MustProjectID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustProjectID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.ProjectIDSet.Has(tc.input.ProjectID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestProjectIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input ProjectIDSet - expected ProjectIDSet + input *ProjectIDSet + expected *ProjectIDSet }{ { - name: "Empty Set", - input: ProjectIDSet{}, - expected: ProjectIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &ProjectIDSet{}, + expected: &ProjectIDSet{}, }, { - name: "Set Contains the element", - input: ProjectIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &ProjectIDSet{ m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: ProjectIDSet{ + expected: &ProjectIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestProjectIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *ProjectIDSet expected []ProjectID }{ { - name: "Empty slice", + name: "Empty", input: &ProjectIDSet{ m: map[ProjectID]struct{}{}, s: nil, }, expected: make([]ProjectID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &ProjectIDSet{ @@ -854,20 +808,17 @@ func TestProjectIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestProjectIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *ProjectIDSet expected *ProjectIDSet @@ -922,21 +873,19 @@ func TestProjectIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestProjectIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *ProjectIDSet @@ -944,6 +893,23 @@ func TestProjectIDSet_Merge(t *testing.T) { } expected *ProjectIDSet }{ + { + name: "Nil Set", + input: struct { + a *ProjectIDSet + b *ProjectIDSet + }{ + a: &ProjectIDSet{ + m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &ProjectIDSet{ + m: map[ProjectID]struct{}{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []ProjectID{MustProjectID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestProjectIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/property_gen.go b/pkg/id/property_gen.go index f0cfdbf2..dfd762aa 100644 --- a/pkg/id/property_gen.go +++ b/pkg/id/property_gen.go @@ -44,7 +44,7 @@ func PropertyIDFromRef(i *string) *PropertyID { // PropertyIDFromRefID generates a new PropertyID from a ref of a generic ID. func PropertyIDFromRefID(i *ID) *PropertyID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := PropertyID(*i) @@ -58,28 +58,40 @@ func (d PropertyID) ID() ID { // String returns a string representation. func (d PropertyID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d PropertyID) GoString() string { - return "id.PropertyID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d PropertyID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d PropertyID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d PropertyID) GoString() string { + return "PropertyID(" + d.String() + ")" } // Ref returns a reference. func (d PropertyID) Ref() *PropertyID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d PropertyID) Contains(ids []PropertyID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d PropertyID) Contains(ids []PropertyID) bool { // CopyRef returns a copy of a reference. func (d *PropertyID) CopyRef() *PropertyID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *PropertyID) CopyRef() *PropertyID { // IDRef returns a reference of a domain id. func (d *PropertyID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *PropertyID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *PropertyID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *PropertyID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *PropertyID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *PropertyID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *PropertyID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *PropertyID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d PropertyID) IsNil() bool { return ID(d).IsNil() } -// PropertyIDToKeys converts IDs into a string slice. -func PropertyIDToKeys(ids []PropertyID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *PropertyID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// PropertyIDsToStrings converts IDs into a string slice. +func PropertyIDsToStrings(ids []PropertyID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // PropertyIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *PropertyIDSet) Clone() *PropertyIDSet { // Merge returns a merged set func (s *PropertyIDSet) Merge(s2 *PropertyIDSet) *PropertyIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/property_gen_test.go b/pkg/id/property_gen_test.go index 1c9ea59c..552b62f1 100644 --- a/pkg/id/property_gen_test.go +++ b/pkg/id/property_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewPropertyID(t *testing.T) { id := NewPropertyID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestPropertyIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestPropertyIDFrom(t *testing.T) { result PropertyID err error }{ - PropertyID{}, - ErrInvalidID, + result: PropertyID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestPropertyIDFrom(t *testing.T) { result PropertyID err error }{ - PropertyID{}, - ErrInvalidID, + result: PropertyID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestPropertyIDFrom(t *testing.T) { result PropertyID err error }{ - PropertyID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: PropertyID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := PropertyIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := PropertyIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustPropertyID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustPropertyID(t *testing.T) { expected: PropertyID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustPropertyID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustPropertyID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestPropertyIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *PropertyID @@ -139,159 +135,149 @@ func TestPropertyIDFromRef(t *testing.T) { expected: &PropertyID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := PropertyIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := PropertyIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestPropertyIDFromRefID(t *testing.T) { id := New() - - subId := PropertyIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := PropertyIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, PropertyIDFromRefID(nil)) + assert.Nil(t, PropertyIDFromRefID(&ID{})) } func TestPropertyID_ID(t *testing.T) { id := New() - subId := PropertyIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := PropertyIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestPropertyID_String(t *testing.T) { id := New() - subId := PropertyIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := PropertyIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", PropertyID{}.String()) } -func TestPropertyID_GoString(t *testing.T) { - id := New() - subId := PropertyIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.PropertyID("+id.String()+")") +func TestPropertyID_RefString(t *testing.T) { + id := NewPropertyID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, PropertyID{}.RefString()) } -func TestPropertyID_RefString(t *testing.T) { +func TestPropertyID_GoString(t *testing.T) { id := New() - subId := PropertyIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := PropertyIDFromRefID(&id) + assert.Equal(t, "PropertyID("+id.String()+")", id2.GoString()) + assert.Equal(t, "PropertyID()", PropertyID{}.GoString()) } func TestPropertyID_Ref(t *testing.T) { - id := New() - subId := PropertyIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewPropertyID() + assert.Equal(t, PropertyID(id), *id.Ref()) + assert.Nil(t, (&PropertyID{}).Ref()) } func TestPropertyID_Contains(t *testing.T) { id := NewPropertyID() id2 := NewPropertyID() assert.True(t, id.Contains([]PropertyID{id, id2})) + assert.False(t, PropertyID{}.Contains([]PropertyID{id, id2, {}})) assert.False(t, id.Contains([]PropertyID{id2})) } func TestPropertyID_CopyRef(t *testing.T) { - id := New() - subId := PropertyIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewPropertyID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*PropertyID)(nil).CopyRef()) } func TestPropertyID_IDRef(t *testing.T) { id := New() - subId := PropertyIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := PropertyIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&PropertyID{}).IDRef()) + assert.Nil(t, (*PropertyID)(nil).IDRef()) } func TestPropertyID_StringRef(t *testing.T) { - id := New() - subId := PropertyIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewPropertyID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&PropertyID{}).StringRef()) + assert.Nil(t, (*PropertyID)(nil).StringRef()) } func TestPropertyID_MarhsalJSON(t *testing.T) { - id := New() - subId := PropertyIDFromRefID(&id) + id := NewPropertyID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&PropertyID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*PropertyID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestPropertyID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &PropertyID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustPropertyID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &PropertyID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestPropertyID_MarshalText(t *testing.T) { id := New() - subId := PropertyIDFromRefID(&id) + res, err := PropertyIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&PropertyID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*PropertyID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestPropertyID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &PropertyID{} - - err := subId.UnmarshalText(text) - + id2 := &PropertyID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestPropertyID_IsNil(t *testing.T) { - subId := PropertyID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *PropertyIDFromRefID(&id) + assert.True(t, PropertyID{}.IsNil()) + assert.False(t, NewPropertyID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestPropertyID_IsNilRef(t *testing.T) { + assert.True(t, PropertyID{}.Ref().IsNilRef()) + assert.True(t, (*PropertyID)(nil).IsNilRef()) + assert.False(t, NewPropertyID().Ref().IsNilRef()) } -func TestPropertyIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestPropertyIDsToStrings(t *testing.T) { + tests := []struct { name string input []PropertyID expected []string @@ -321,19 +307,17 @@ func TestPropertyIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, PropertyIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, PropertyIDsToStrings(tt.input)) }) } - } func TestPropertyIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestPropertyIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestPropertyIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := PropertyIDsFrom(tc.input) if tc.expected.err != nil { - _, err := PropertyIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := PropertyIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestPropertyIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []PropertyID @@ -449,25 +431,22 @@ func TestPropertyIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []PropertyID @@ -493,21 +472,18 @@ func TestPropertyIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []PropertyID expected []ID @@ -537,28 +513,25 @@ func TestPropertyIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustPropertyID(id1.String()) + id21 := MustPropertyID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustPropertyID(id2.String()) + id22 := MustPropertyID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustPropertyID(id3.String()) + id23 := MustPropertyID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*PropertyID expected []*ID @@ -570,39 +543,35 @@ func TestPropertyIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*PropertyID{&subId1}, + input: []*PropertyID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*PropertyID{&subId1, &subId2, &subId3}, + input: []*PropertyID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewPropertyIDSet(t *testing.T) { PropertyIdSet := NewPropertyIDSet() - assert.NotNil(t, PropertyIdSet) assert.Empty(t, PropertyIdSet.m) assert.Empty(t, PropertyIdSet.s) } func TestPropertyIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []PropertyID expected *PropertyIDSet @@ -663,24 +632,19 @@ func TestPropertyIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewPropertyIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestPropertyIDSet_AddRef(t *testing.T) { - t.Parallel() - - PropertyId := MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *PropertyID expected *PropertyIDSet @@ -695,7 +659,7 @@ func TestPropertyIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &PropertyId, + input: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &PropertyIDSet{ m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestPropertyIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewPropertyIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestPropertyIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - PropertyIDSet - PropertyID - } + tests := []struct { + name string + target *PropertyIDSet + input PropertyID expected bool }{ { - name: "Empty Set", - input: struct { - PropertyIDSet - PropertyID - }{PropertyIDSet: PropertyIDSet{}, PropertyID: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &PropertyIDSet{}, + input: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - PropertyIDSet - PropertyID - }{PropertyIDSet: PropertyIDSet{ + target: &PropertyIDSet{ m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, PropertyID: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - PropertyIDSet - PropertyID - }{PropertyIDSet: PropertyIDSet{ + target: &PropertyIDSet{ m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, PropertyID: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustPropertyID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.PropertyIDSet.Has(tc.input.PropertyID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestPropertyIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input PropertyIDSet - expected PropertyIDSet + input *PropertyIDSet + expected *PropertyIDSet }{ { - name: "Empty Set", - input: PropertyIDSet{}, - expected: PropertyIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &PropertyIDSet{}, + expected: &PropertyIDSet{}, }, { - name: "Set Contains the element", - input: PropertyIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &PropertyIDSet{ m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: PropertyIDSet{ + expected: &PropertyIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestPropertyIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *PropertyIDSet expected []PropertyID }{ { - name: "Empty slice", + name: "Empty", input: &PropertyIDSet{ m: map[PropertyID]struct{}{}, s: nil, }, expected: make([]PropertyID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &PropertyIDSet{ @@ -854,20 +808,17 @@ func TestPropertyIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestPropertyIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *PropertyIDSet expected *PropertyIDSet @@ -922,21 +873,19 @@ func TestPropertyIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestPropertyIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *PropertyIDSet @@ -944,6 +893,23 @@ func TestPropertyIDSet_Merge(t *testing.T) { } expected *PropertyIDSet }{ + { + name: "Nil Set", + input: struct { + a *PropertyIDSet + b *PropertyIDSet + }{ + a: &PropertyIDSet{ + m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &PropertyIDSet{ + m: map[PropertyID]struct{}{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []PropertyID{MustPropertyID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestPropertyIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/property_item_gen.go b/pkg/id/property_item_gen.go index 122e9b1a..c749aaab 100644 --- a/pkg/id/property_item_gen.go +++ b/pkg/id/property_item_gen.go @@ -44,7 +44,7 @@ func PropertyItemIDFromRef(i *string) *PropertyItemID { // PropertyItemIDFromRefID generates a new PropertyItemID from a ref of a generic ID. func PropertyItemIDFromRefID(i *ID) *PropertyItemID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := PropertyItemID(*i) @@ -58,28 +58,40 @@ func (d PropertyItemID) ID() ID { // String returns a string representation. func (d PropertyItemID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d PropertyItemID) GoString() string { - return "id.PropertyItemID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d PropertyItemID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d PropertyItemID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d PropertyItemID) GoString() string { + return "PropertyItemID(" + d.String() + ")" } // Ref returns a reference. func (d PropertyItemID) Ref() *PropertyItemID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d PropertyItemID) Contains(ids []PropertyItemID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d PropertyItemID) Contains(ids []PropertyItemID) bool { // CopyRef returns a copy of a reference. func (d *PropertyItemID) CopyRef() *PropertyItemID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *PropertyItemID) CopyRef() *PropertyItemID { // IDRef returns a reference of a domain id. func (d *PropertyItemID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *PropertyItemID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *PropertyItemID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *PropertyItemID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *PropertyItemID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *PropertyItemID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *PropertyItemID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *PropertyItemID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d PropertyItemID) IsNil() bool { return ID(d).IsNil() } -// PropertyItemIDToKeys converts IDs into a string slice. -func PropertyItemIDToKeys(ids []PropertyItemID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *PropertyItemID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// PropertyItemIDsToStrings converts IDs into a string slice. +func PropertyItemIDsToStrings(ids []PropertyItemID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // PropertyItemIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *PropertyItemIDSet) Clone() *PropertyItemIDSet { // Merge returns a merged set func (s *PropertyItemIDSet) Merge(s2 *PropertyItemIDSet) *PropertyItemIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/property_item_gen_test.go b/pkg/id/property_item_gen_test.go index 680c3169..c60703a0 100644 --- a/pkg/id/property_item_gen_test.go +++ b/pkg/id/property_item_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewPropertyItemID(t *testing.T) { id := NewPropertyItemID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestPropertyItemIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestPropertyItemIDFrom(t *testing.T) { result PropertyItemID err error }{ - PropertyItemID{}, - ErrInvalidID, + result: PropertyItemID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestPropertyItemIDFrom(t *testing.T) { result PropertyItemID err error }{ - PropertyItemID{}, - ErrInvalidID, + result: PropertyItemID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestPropertyItemIDFrom(t *testing.T) { result PropertyItemID err error }{ - PropertyItemID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: PropertyItemID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := PropertyItemIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := PropertyItemIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustPropertyItemID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustPropertyItemID(t *testing.T) { expected: PropertyItemID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustPropertyItemID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustPropertyItemID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestPropertyItemIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *PropertyItemID @@ -139,159 +135,149 @@ func TestPropertyItemIDFromRef(t *testing.T) { expected: &PropertyItemID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := PropertyItemIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := PropertyItemIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestPropertyItemIDFromRefID(t *testing.T) { id := New() - - subId := PropertyItemIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := PropertyItemIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, PropertyItemIDFromRefID(nil)) + assert.Nil(t, PropertyItemIDFromRefID(&ID{})) } func TestPropertyItemID_ID(t *testing.T) { id := New() - subId := PropertyItemIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := PropertyItemIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestPropertyItemID_String(t *testing.T) { id := New() - subId := PropertyItemIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := PropertyItemIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", PropertyItemID{}.String()) } -func TestPropertyItemID_GoString(t *testing.T) { - id := New() - subId := PropertyItemIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.PropertyItemID("+id.String()+")") +func TestPropertyItemID_RefString(t *testing.T) { + id := NewPropertyItemID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, PropertyItemID{}.RefString()) } -func TestPropertyItemID_RefString(t *testing.T) { +func TestPropertyItemID_GoString(t *testing.T) { id := New() - subId := PropertyItemIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := PropertyItemIDFromRefID(&id) + assert.Equal(t, "PropertyItemID("+id.String()+")", id2.GoString()) + assert.Equal(t, "PropertyItemID()", PropertyItemID{}.GoString()) } func TestPropertyItemID_Ref(t *testing.T) { - id := New() - subId := PropertyItemIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewPropertyItemID() + assert.Equal(t, PropertyItemID(id), *id.Ref()) + assert.Nil(t, (&PropertyItemID{}).Ref()) } func TestPropertyItemID_Contains(t *testing.T) { id := NewPropertyItemID() id2 := NewPropertyItemID() assert.True(t, id.Contains([]PropertyItemID{id, id2})) + assert.False(t, PropertyItemID{}.Contains([]PropertyItemID{id, id2, {}})) assert.False(t, id.Contains([]PropertyItemID{id2})) } func TestPropertyItemID_CopyRef(t *testing.T) { - id := New() - subId := PropertyItemIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewPropertyItemID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*PropertyItemID)(nil).CopyRef()) } func TestPropertyItemID_IDRef(t *testing.T) { id := New() - subId := PropertyItemIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := PropertyItemIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&PropertyItemID{}).IDRef()) + assert.Nil(t, (*PropertyItemID)(nil).IDRef()) } func TestPropertyItemID_StringRef(t *testing.T) { - id := New() - subId := PropertyItemIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewPropertyItemID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&PropertyItemID{}).StringRef()) + assert.Nil(t, (*PropertyItemID)(nil).StringRef()) } func TestPropertyItemID_MarhsalJSON(t *testing.T) { - id := New() - subId := PropertyItemIDFromRefID(&id) + id := NewPropertyItemID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&PropertyItemID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*PropertyItemID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestPropertyItemID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &PropertyItemID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustPropertyItemID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &PropertyItemID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestPropertyItemID_MarshalText(t *testing.T) { id := New() - subId := PropertyItemIDFromRefID(&id) + res, err := PropertyItemIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&PropertyItemID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*PropertyItemID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestPropertyItemID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &PropertyItemID{} - - err := subId.UnmarshalText(text) - + id2 := &PropertyItemID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestPropertyItemID_IsNil(t *testing.T) { - subId := PropertyItemID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *PropertyItemIDFromRefID(&id) + assert.True(t, PropertyItemID{}.IsNil()) + assert.False(t, NewPropertyItemID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestPropertyItemID_IsNilRef(t *testing.T) { + assert.True(t, PropertyItemID{}.Ref().IsNilRef()) + assert.True(t, (*PropertyItemID)(nil).IsNilRef()) + assert.False(t, NewPropertyItemID().Ref().IsNilRef()) } -func TestPropertyItemIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestPropertyItemIDsToStrings(t *testing.T) { + tests := []struct { name string input []PropertyItemID expected []string @@ -321,19 +307,17 @@ func TestPropertyItemIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, PropertyItemIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, PropertyItemIDsToStrings(tt.input)) }) } - } func TestPropertyItemIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestPropertyItemIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestPropertyItemIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := PropertyItemIDsFrom(tc.input) if tc.expected.err != nil { - _, err := PropertyItemIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := PropertyItemIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestPropertyItemIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []PropertyItemID @@ -449,25 +431,22 @@ func TestPropertyItemIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyItemIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyItemIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []PropertyItemID @@ -493,21 +472,18 @@ func TestPropertyItemIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyItemIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyItemIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []PropertyItemID expected []ID @@ -537,28 +513,25 @@ func TestPropertyItemIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyItemIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestPropertyItemIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustPropertyItemID(id1.String()) + id21 := MustPropertyItemID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustPropertyItemID(id2.String()) + id22 := MustPropertyItemID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustPropertyItemID(id3.String()) + id23 := MustPropertyItemID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*PropertyItemID expected []*ID @@ -570,39 +543,35 @@ func TestPropertyItemIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*PropertyItemID{&subId1}, + input: []*PropertyItemID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*PropertyItemID{&subId1, &subId2, &subId3}, + input: []*PropertyItemID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := PropertyItemIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewPropertyItemIDSet(t *testing.T) { PropertyItemIdSet := NewPropertyItemIDSet() - assert.NotNil(t, PropertyItemIdSet) assert.Empty(t, PropertyItemIdSet.m) assert.Empty(t, PropertyItemIdSet.s) } func TestPropertyItemIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []PropertyItemID expected *PropertyItemIDSet @@ -663,24 +632,19 @@ func TestPropertyItemIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewPropertyItemIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestPropertyItemIDSet_AddRef(t *testing.T) { - t.Parallel() - - PropertyItemId := MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *PropertyItemID expected *PropertyItemIDSet @@ -695,7 +659,7 @@ func TestPropertyItemIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &PropertyItemId, + input: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &PropertyItemIDSet{ m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestPropertyItemIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewPropertyItemIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestPropertyItemIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - PropertyItemIDSet - PropertyItemID - } + tests := []struct { + name string + target *PropertyItemIDSet + input PropertyItemID expected bool }{ { - name: "Empty Set", - input: struct { - PropertyItemIDSet - PropertyItemID - }{PropertyItemIDSet: PropertyItemIDSet{}, PropertyItemID: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &PropertyItemIDSet{}, + input: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - PropertyItemIDSet - PropertyItemID - }{PropertyItemIDSet: PropertyItemIDSet{ + target: &PropertyItemIDSet{ m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, PropertyItemID: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - PropertyItemIDSet - PropertyItemID - }{PropertyItemIDSet: PropertyItemIDSet{ + target: &PropertyItemIDSet{ m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, PropertyItemID: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.PropertyItemIDSet.Has(tc.input.PropertyItemID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestPropertyItemIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input PropertyItemIDSet - expected PropertyItemIDSet + input *PropertyItemIDSet + expected *PropertyItemIDSet }{ { - name: "Empty Set", - input: PropertyItemIDSet{}, - expected: PropertyItemIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &PropertyItemIDSet{}, + expected: &PropertyItemIDSet{}, }, { - name: "Set Contains the element", - input: PropertyItemIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &PropertyItemIDSet{ m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: PropertyItemIDSet{ + expected: &PropertyItemIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestPropertyItemIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *PropertyItemIDSet expected []PropertyItemID }{ { - name: "Empty slice", + name: "Empty", input: &PropertyItemIDSet{ m: map[PropertyItemID]struct{}{}, s: nil, }, expected: make([]PropertyItemID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &PropertyItemIDSet{ @@ -854,20 +808,17 @@ func TestPropertyItemIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestPropertyItemIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *PropertyItemIDSet expected *PropertyItemIDSet @@ -922,21 +873,19 @@ func TestPropertyItemIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestPropertyItemIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *PropertyItemIDSet @@ -944,6 +893,23 @@ func TestPropertyItemIDSet_Merge(t *testing.T) { } expected *PropertyItemIDSet }{ + { + name: "Nil Set", + input: struct { + a *PropertyItemIDSet + b *PropertyItemIDSet + }{ + a: &PropertyItemIDSet{ + m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &PropertyItemIDSet{ + m: map[PropertyItemID]struct{}{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []PropertyItemID{MustPropertyItemID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestPropertyItemIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/property_schema.go b/pkg/id/property_schema.go index 6530825b..91795e25 100644 --- a/pkg/id/property_schema.go +++ b/pkg/id/property_schema.go @@ -63,6 +63,14 @@ func PropertySchemaIDFromRef(id *string) *PropertySchemaID { return &did } +// Clone duplicates the PropertySchemaID +func (d PropertySchemaID) Clone() PropertySchemaID { + return PropertySchemaID{ + plugin: d.plugin.Clone(), + id: d.id, + } +} + // ID returns a fragment of just ID. func (d PropertySchemaID) ID() string { return d.id @@ -80,18 +88,24 @@ func (d PropertySchemaID) System() bool { // String returns a string representation. func (d PropertySchemaID) String() string { + if d.IsNil() { + return "" + } return d.plugin.String() + "/" + d.id } // Ref returns a reference. func (d PropertySchemaID) Ref() *PropertySchemaID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // CopyRef returns a copy of a reference. func (d *PropertySchemaID) CopyRef() *PropertySchemaID { - if d == nil { + if d == nil || d.IsNil() { return nil } d2 := *d @@ -100,7 +114,7 @@ func (d *PropertySchemaID) CopyRef() *PropertySchemaID { // IsNil checks if ID is empty or not. func (d PropertySchemaID) IsNil() bool { - return d.plugin == PluginID{} && d.id == "" + return d.plugin.IsNil() && d.id == "" } // Equal returns true if two IDs are equal. @@ -129,7 +143,7 @@ func (d *PropertySchemaID) UnmarshalText(text []byte) (err error) { } // PropertySchemaIDToKeys converts IDs into a string slice. -func PropertySchemaIDToKeys(ids []PropertySchemaID) []string { +func PropertySchemaIDsToStrings(ids []PropertySchemaID) []string { keys := make([]string, 0, len(ids)) for _, id := range ids { keys = append(keys, id.String()) diff --git a/pkg/id/property_schema_field.go b/pkg/id/property_schema_field.go index aaa986e9..b8b9f6d2 100644 --- a/pkg/id/property_schema_field.go +++ b/pkg/id/property_schema_field.go @@ -3,7 +3,7 @@ package id type PropertySchemaFieldID string func PropertySchemaFieldIDFrom(str *string) *PropertySchemaFieldID { - if str == nil { + if str == nil || *str == "" { return nil } id := PropertySchemaFieldID(*str) @@ -11,12 +11,15 @@ func PropertySchemaFieldIDFrom(str *string) *PropertySchemaFieldID { } func (id PropertySchemaFieldID) Ref() *PropertySchemaFieldID { + if id == "" { + return nil + } id2 := id return &id2 } func (id *PropertySchemaFieldID) CopyRef() *PropertySchemaFieldID { - if id == nil { + if id == nil || *id == "" { return nil } id2 := *id @@ -28,7 +31,7 @@ func (id PropertySchemaFieldID) String() string { } func (id *PropertySchemaFieldID) StringRef() *string { - if id == nil { + if id == nil || *id == "" { return nil } str := string(*id) diff --git a/pkg/id/property_schema_group.go b/pkg/id/property_schema_group.go index d0556e05..cfba5c32 100644 --- a/pkg/id/property_schema_group.go +++ b/pkg/id/property_schema_group.go @@ -3,7 +3,7 @@ package id type PropertySchemaGroupID string func PropertySchemaGroupIDFrom(str *string) *PropertySchemaGroupID { - if str == nil { + if str == nil || *str == "" { return nil } id := PropertySchemaGroupID(*str) @@ -11,12 +11,15 @@ func PropertySchemaGroupIDFrom(str *string) *PropertySchemaGroupID { } func (id PropertySchemaGroupID) Ref() *PropertySchemaGroupID { + if id == "" { + return nil + } id2 := id return &id2 } func (id *PropertySchemaGroupID) CopyRef() *PropertySchemaGroupID { - if id == nil { + if id == nil || *id == "" { return nil } id2 := *id @@ -28,7 +31,7 @@ func (id PropertySchemaGroupID) String() string { } func (id *PropertySchemaGroupID) StringRef() *string { - if id == nil { + if id == nil || *id == "" { return nil } str := string(*id) diff --git a/pkg/id/property_schema_test.go b/pkg/id/property_schema_test.go index 7adcb856..918dc164 100644 --- a/pkg/id/property_schema_test.go +++ b/pkg/id/property_schema_test.go @@ -215,6 +215,22 @@ func TestPropertySchemaIDFromRef(t *testing.T) { } } +func TestPropertySchemaID_Clone(t *testing.T) { + p := PropertySchemaID{ + id: "xxx", + plugin: PluginID{ + name: "aaa", + version: "1.0.0", + sys: false, + scene: NewSceneID().Ref(), + }, + } + c := p.Clone() + + assert.Equal(t, p, c) + assert.NotSame(t, p, c) +} + func TestPropertySchemaID_ID(t *testing.T) { propertySchemaID := MustPropertySchemaID("Test~2.0.0/test") assert.Equal(t, propertySchemaID.ID(), "test") @@ -287,7 +303,7 @@ func TestPropertySchemaID_UnmarshalText(t *testing.T) { assert.Equal(t, "test~2.0.0/test", propertySchemaID.String()) } -func TestPropertySchemaIDToKeys(t *testing.T) { +func TestPropertySchemaIDsToStrings(t *testing.T) { t.Parallel() testCases := []struct { name string @@ -323,7 +339,7 @@ func TestPropertySchemaIDToKeys(t *testing.T) { tc := tc t.Run(tc.name, func(tt *testing.T) { tt.Parallel() - assert.Equal(tt, tc.expected, PropertySchemaIDToKeys(tc.input)) + assert.Equal(tt, tc.expected, PropertySchemaIDsToStrings(tc.input)) }) } diff --git a/pkg/id/scene_gen.go b/pkg/id/scene_gen.go index bc8d2c37..cd2c6d0b 100644 --- a/pkg/id/scene_gen.go +++ b/pkg/id/scene_gen.go @@ -44,7 +44,7 @@ func SceneIDFromRef(i *string) *SceneID { // SceneIDFromRefID generates a new SceneID from a ref of a generic ID. func SceneIDFromRefID(i *ID) *SceneID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := SceneID(*i) @@ -58,28 +58,40 @@ func (d SceneID) ID() ID { // String returns a string representation. func (d SceneID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d SceneID) GoString() string { - return "id.SceneID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d SceneID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d SceneID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d SceneID) GoString() string { + return "SceneID(" + d.String() + ")" } // Ref returns a reference. func (d SceneID) Ref() *SceneID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d SceneID) Contains(ids []SceneID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d SceneID) Contains(ids []SceneID) bool { // CopyRef returns a copy of a reference. func (d *SceneID) CopyRef() *SceneID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *SceneID) CopyRef() *SceneID { // IDRef returns a reference of a domain id. func (d *SceneID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *SceneID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *SceneID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *SceneID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *SceneID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *SceneID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *SceneID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *SceneID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d SceneID) IsNil() bool { return ID(d).IsNil() } -// SceneIDToKeys converts IDs into a string slice. -func SceneIDToKeys(ids []SceneID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *SceneID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// SceneIDsToStrings converts IDs into a string slice. +func SceneIDsToStrings(ids []SceneID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // SceneIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *SceneIDSet) Clone() *SceneIDSet { // Merge returns a merged set func (s *SceneIDSet) Merge(s2 *SceneIDSet) *SceneIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/scene_gen_test.go b/pkg/id/scene_gen_test.go index cec67920..0bf3cffa 100644 --- a/pkg/id/scene_gen_test.go +++ b/pkg/id/scene_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewSceneID(t *testing.T) { id := NewSceneID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestSceneIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestSceneIDFrom(t *testing.T) { result SceneID err error }{ - SceneID{}, - ErrInvalidID, + result: SceneID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestSceneIDFrom(t *testing.T) { result SceneID err error }{ - SceneID{}, - ErrInvalidID, + result: SceneID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestSceneIDFrom(t *testing.T) { result SceneID err error }{ - SceneID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: SceneID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := SceneIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := SceneIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustSceneID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustSceneID(t *testing.T) { expected: SceneID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustSceneID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustSceneID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestSceneIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *SceneID @@ -139,159 +135,149 @@ func TestSceneIDFromRef(t *testing.T) { expected: &SceneID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := SceneIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := SceneIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestSceneIDFromRefID(t *testing.T) { id := New() - - subId := SceneIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := SceneIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, SceneIDFromRefID(nil)) + assert.Nil(t, SceneIDFromRefID(&ID{})) } func TestSceneID_ID(t *testing.T) { id := New() - subId := SceneIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := SceneIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestSceneID_String(t *testing.T) { id := New() - subId := SceneIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := SceneIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", SceneID{}.String()) } -func TestSceneID_GoString(t *testing.T) { - id := New() - subId := SceneIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.SceneID("+id.String()+")") +func TestSceneID_RefString(t *testing.T) { + id := NewSceneID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, SceneID{}.RefString()) } -func TestSceneID_RefString(t *testing.T) { +func TestSceneID_GoString(t *testing.T) { id := New() - subId := SceneIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := SceneIDFromRefID(&id) + assert.Equal(t, "SceneID("+id.String()+")", id2.GoString()) + assert.Equal(t, "SceneID()", SceneID{}.GoString()) } func TestSceneID_Ref(t *testing.T) { - id := New() - subId := SceneIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewSceneID() + assert.Equal(t, SceneID(id), *id.Ref()) + assert.Nil(t, (&SceneID{}).Ref()) } func TestSceneID_Contains(t *testing.T) { id := NewSceneID() id2 := NewSceneID() assert.True(t, id.Contains([]SceneID{id, id2})) + assert.False(t, SceneID{}.Contains([]SceneID{id, id2, {}})) assert.False(t, id.Contains([]SceneID{id2})) } func TestSceneID_CopyRef(t *testing.T) { - id := New() - subId := SceneIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewSceneID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*SceneID)(nil).CopyRef()) } func TestSceneID_IDRef(t *testing.T) { id := New() - subId := SceneIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := SceneIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&SceneID{}).IDRef()) + assert.Nil(t, (*SceneID)(nil).IDRef()) } func TestSceneID_StringRef(t *testing.T) { - id := New() - subId := SceneIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewSceneID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&SceneID{}).StringRef()) + assert.Nil(t, (*SceneID)(nil).StringRef()) } func TestSceneID_MarhsalJSON(t *testing.T) { - id := New() - subId := SceneIDFromRefID(&id) + id := NewSceneID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&SceneID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*SceneID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestSceneID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &SceneID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustSceneID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &SceneID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestSceneID_MarshalText(t *testing.T) { id := New() - subId := SceneIDFromRefID(&id) + res, err := SceneIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&SceneID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*SceneID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestSceneID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &SceneID{} - - err := subId.UnmarshalText(text) - + id2 := &SceneID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestSceneID_IsNil(t *testing.T) { - subId := SceneID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *SceneIDFromRefID(&id) + assert.True(t, SceneID{}.IsNil()) + assert.False(t, NewSceneID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestSceneID_IsNilRef(t *testing.T) { + assert.True(t, SceneID{}.Ref().IsNilRef()) + assert.True(t, (*SceneID)(nil).IsNilRef()) + assert.False(t, NewSceneID().Ref().IsNilRef()) } -func TestSceneIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestSceneIDsToStrings(t *testing.T) { + tests := []struct { name string input []SceneID expected []string @@ -321,19 +307,17 @@ func TestSceneIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, SceneIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, SceneIDsToStrings(tt.input)) }) } - } func TestSceneIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestSceneIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestSceneIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := SceneIDsFrom(tc.input) if tc.expected.err != nil { - _, err := SceneIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := SceneIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestSceneIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []SceneID @@ -449,25 +431,22 @@ func TestSceneIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := SceneIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestSceneIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []SceneID @@ -493,21 +472,18 @@ func TestSceneIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := SceneIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestSceneIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []SceneID expected []ID @@ -537,28 +513,25 @@ func TestSceneIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := SceneIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestSceneIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustSceneID(id1.String()) + id21 := MustSceneID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustSceneID(id2.String()) + id22 := MustSceneID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustSceneID(id3.String()) + id23 := MustSceneID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*SceneID expected []*ID @@ -570,39 +543,35 @@ func TestSceneIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*SceneID{&subId1}, + input: []*SceneID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*SceneID{&subId1, &subId2, &subId3}, + input: []*SceneID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := SceneIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewSceneIDSet(t *testing.T) { SceneIdSet := NewSceneIDSet() - assert.NotNil(t, SceneIdSet) assert.Empty(t, SceneIdSet.m) assert.Empty(t, SceneIdSet.s) } func TestSceneIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []SceneID expected *SceneIDSet @@ -663,24 +632,19 @@ func TestSceneIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewSceneIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestSceneIDSet_AddRef(t *testing.T) { - t.Parallel() - - SceneId := MustSceneID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *SceneID expected *SceneIDSet @@ -695,7 +659,7 @@ func TestSceneIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &SceneId, + input: MustSceneID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &SceneIDSet{ m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestSceneIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewSceneIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestSceneIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - SceneIDSet - SceneID - } + tests := []struct { + name string + target *SceneIDSet + input SceneID expected bool }{ { - name: "Empty Set", - input: struct { - SceneIDSet - SceneID - }{SceneIDSet: SceneIDSet{}, SceneID: MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &SceneIDSet{}, + input: MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - SceneIDSet - SceneID - }{SceneIDSet: SceneIDSet{ + target: &SceneIDSet{ m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, SceneID: MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - SceneIDSet - SceneID - }{SceneIDSet: SceneIDSet{ + target: &SceneIDSet{ m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, SceneID: MustSceneID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustSceneID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.SceneIDSet.Has(tc.input.SceneID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestSceneIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input SceneIDSet - expected SceneIDSet + input *SceneIDSet + expected *SceneIDSet }{ { - name: "Empty Set", - input: SceneIDSet{}, - expected: SceneIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &SceneIDSet{}, + expected: &SceneIDSet{}, }, { - name: "Set Contains the element", - input: SceneIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &SceneIDSet{ m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: SceneIDSet{ + expected: &SceneIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestSceneIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *SceneIDSet expected []SceneID }{ { - name: "Empty slice", + name: "Empty", input: &SceneIDSet{ m: map[SceneID]struct{}{}, s: nil, }, expected: make([]SceneID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &SceneIDSet{ @@ -854,20 +808,17 @@ func TestSceneIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestSceneIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *SceneIDSet expected *SceneIDSet @@ -922,21 +873,19 @@ func TestSceneIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestSceneIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *SceneIDSet @@ -944,6 +893,23 @@ func TestSceneIDSet_Merge(t *testing.T) { } expected *SceneIDSet }{ + { + name: "Nil Set", + input: struct { + a *SceneIDSet + b *SceneIDSet + }{ + a: &SceneIDSet{ + m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &SceneIDSet{ + m: map[SceneID]struct{}{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []SceneID{MustSceneID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestSceneIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/tag_gen.go b/pkg/id/tag_gen.go index 1e2df781..27e34057 100644 --- a/pkg/id/tag_gen.go +++ b/pkg/id/tag_gen.go @@ -44,7 +44,7 @@ func TagIDFromRef(i *string) *TagID { // TagIDFromRefID generates a new TagID from a ref of a generic ID. func TagIDFromRefID(i *ID) *TagID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := TagID(*i) @@ -58,28 +58,40 @@ func (d TagID) ID() ID { // String returns a string representation. func (d TagID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d TagID) GoString() string { - return "id.TagID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d TagID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d TagID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d TagID) GoString() string { + return "TagID(" + d.String() + ")" } // Ref returns a reference. func (d TagID) Ref() *TagID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d TagID) Contains(ids []TagID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d TagID) Contains(ids []TagID) bool { // CopyRef returns a copy of a reference. func (d *TagID) CopyRef() *TagID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *TagID) CopyRef() *TagID { // IDRef returns a reference of a domain id. func (d *TagID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *TagID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *TagID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *TagID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *TagID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *TagID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *TagID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *TagID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d TagID) IsNil() bool { return ID(d).IsNil() } -// TagIDToKeys converts IDs into a string slice. -func TagIDToKeys(ids []TagID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *TagID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// TagIDsToStrings converts IDs into a string slice. +func TagIDsToStrings(ids []TagID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // TagIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *TagIDSet) Clone() *TagIDSet { // Merge returns a merged set func (s *TagIDSet) Merge(s2 *TagIDSet) *TagIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/tag_gen_test.go b/pkg/id/tag_gen_test.go index 0620cf8b..bef35da4 100644 --- a/pkg/id/tag_gen_test.go +++ b/pkg/id/tag_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewTagID(t *testing.T) { id := NewTagID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestTagIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestTagIDFrom(t *testing.T) { result TagID err error }{ - TagID{}, - ErrInvalidID, + result: TagID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestTagIDFrom(t *testing.T) { result TagID err error }{ - TagID{}, - ErrInvalidID, + result: TagID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestTagIDFrom(t *testing.T) { result TagID err error }{ - TagID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: TagID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := TagIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := TagIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustTagID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustTagID(t *testing.T) { expected: TagID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustTagID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustTagID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestTagIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *TagID @@ -139,159 +135,149 @@ func TestTagIDFromRef(t *testing.T) { expected: &TagID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := TagIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := TagIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestTagIDFromRefID(t *testing.T) { id := New() - - subId := TagIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := TagIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, TagIDFromRefID(nil)) + assert.Nil(t, TagIDFromRefID(&ID{})) } func TestTagID_ID(t *testing.T) { id := New() - subId := TagIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := TagIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestTagID_String(t *testing.T) { id := New() - subId := TagIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := TagIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", TagID{}.String()) } -func TestTagID_GoString(t *testing.T) { - id := New() - subId := TagIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.TagID("+id.String()+")") +func TestTagID_RefString(t *testing.T) { + id := NewTagID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, TagID{}.RefString()) } -func TestTagID_RefString(t *testing.T) { +func TestTagID_GoString(t *testing.T) { id := New() - subId := TagIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := TagIDFromRefID(&id) + assert.Equal(t, "TagID("+id.String()+")", id2.GoString()) + assert.Equal(t, "TagID()", TagID{}.GoString()) } func TestTagID_Ref(t *testing.T) { - id := New() - subId := TagIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewTagID() + assert.Equal(t, TagID(id), *id.Ref()) + assert.Nil(t, (&TagID{}).Ref()) } func TestTagID_Contains(t *testing.T) { id := NewTagID() id2 := NewTagID() assert.True(t, id.Contains([]TagID{id, id2})) + assert.False(t, TagID{}.Contains([]TagID{id, id2, {}})) assert.False(t, id.Contains([]TagID{id2})) } func TestTagID_CopyRef(t *testing.T) { - id := New() - subId := TagIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewTagID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*TagID)(nil).CopyRef()) } func TestTagID_IDRef(t *testing.T) { id := New() - subId := TagIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := TagIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&TagID{}).IDRef()) + assert.Nil(t, (*TagID)(nil).IDRef()) } func TestTagID_StringRef(t *testing.T) { - id := New() - subId := TagIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewTagID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&TagID{}).StringRef()) + assert.Nil(t, (*TagID)(nil).StringRef()) } func TestTagID_MarhsalJSON(t *testing.T) { - id := New() - subId := TagIDFromRefID(&id) + id := NewTagID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&TagID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*TagID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestTagID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &TagID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustTagID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &TagID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestTagID_MarshalText(t *testing.T) { id := New() - subId := TagIDFromRefID(&id) + res, err := TagIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&TagID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*TagID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestTagID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &TagID{} - - err := subId.UnmarshalText(text) - + id2 := &TagID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestTagID_IsNil(t *testing.T) { - subId := TagID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *TagIDFromRefID(&id) + assert.True(t, TagID{}.IsNil()) + assert.False(t, NewTagID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestTagID_IsNilRef(t *testing.T) { + assert.True(t, TagID{}.Ref().IsNilRef()) + assert.True(t, (*TagID)(nil).IsNilRef()) + assert.False(t, NewTagID().Ref().IsNilRef()) } -func TestTagIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestTagIDsToStrings(t *testing.T) { + tests := []struct { name string input []TagID expected []string @@ -321,19 +307,17 @@ func TestTagIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, TagIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, TagIDsToStrings(tt.input)) }) } - } func TestTagIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestTagIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestTagIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := TagIDsFrom(tc.input) if tc.expected.err != nil { - _, err := TagIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := TagIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestTagIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []TagID @@ -449,25 +431,22 @@ func TestTagIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TagIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTagIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []TagID @@ -493,21 +472,18 @@ func TestTagIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TagIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTagIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []TagID expected []ID @@ -537,28 +513,25 @@ func TestTagIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TagIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTagIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustTagID(id1.String()) + id21 := MustTagID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustTagID(id2.String()) + id22 := MustTagID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustTagID(id3.String()) + id23 := MustTagID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*TagID expected []*ID @@ -570,39 +543,35 @@ func TestTagIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*TagID{&subId1}, + input: []*TagID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*TagID{&subId1, &subId2, &subId3}, + input: []*TagID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TagIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewTagIDSet(t *testing.T) { TagIdSet := NewTagIDSet() - assert.NotNil(t, TagIdSet) assert.Empty(t, TagIdSet.m) assert.Empty(t, TagIdSet.s) } func TestTagIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []TagID expected *TagIDSet @@ -663,24 +632,19 @@ func TestTagIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewTagIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestTagIDSet_AddRef(t *testing.T) { - t.Parallel() - - TagId := MustTagID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *TagID expected *TagIDSet @@ -695,7 +659,7 @@ func TestTagIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &TagId, + input: MustTagID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &TagIDSet{ m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestTagIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewTagIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestTagIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - TagIDSet - TagID - } + tests := []struct { + name string + target *TagIDSet + input TagID expected bool }{ { - name: "Empty Set", - input: struct { - TagIDSet - TagID - }{TagIDSet: TagIDSet{}, TagID: MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &TagIDSet{}, + input: MustTagID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - TagIDSet - TagID - }{TagIDSet: TagIDSet{ + target: &TagIDSet{ m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, TagID: MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustTagID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - TagIDSet - TagID - }{TagIDSet: TagIDSet{ + target: &TagIDSet{ m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, TagID: MustTagID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustTagID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.TagIDSet.Has(tc.input.TagID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestTagIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input TagIDSet - expected TagIDSet + input *TagIDSet + expected *TagIDSet }{ { - name: "Empty Set", - input: TagIDSet{}, - expected: TagIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &TagIDSet{}, + expected: &TagIDSet{}, }, { - name: "Set Contains the element", - input: TagIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &TagIDSet{ m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: TagIDSet{ + expected: &TagIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestTagIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *TagIDSet expected []TagID }{ { - name: "Empty slice", + name: "Empty", input: &TagIDSet{ m: map[TagID]struct{}{}, s: nil, }, expected: make([]TagID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &TagIDSet{ @@ -854,20 +808,17 @@ func TestTagIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestTagIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *TagIDSet expected *TagIDSet @@ -922,21 +873,19 @@ func TestTagIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestTagIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *TagIDSet @@ -944,6 +893,23 @@ func TestTagIDSet_Merge(t *testing.T) { } expected *TagIDSet }{ + { + name: "Nil Set", + input: struct { + a *TagIDSet + b *TagIDSet + }{ + a: &TagIDSet{ + m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &TagIDSet{ + m: map[TagID]struct{}{MustTagID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []TagID{MustTagID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestTagIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/team_gen.go b/pkg/id/team_gen.go index fa5fbc25..c4d0cf4c 100644 --- a/pkg/id/team_gen.go +++ b/pkg/id/team_gen.go @@ -44,7 +44,7 @@ func TeamIDFromRef(i *string) *TeamID { // TeamIDFromRefID generates a new TeamID from a ref of a generic ID. func TeamIDFromRefID(i *ID) *TeamID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := TeamID(*i) @@ -58,28 +58,40 @@ func (d TeamID) ID() ID { // String returns a string representation. func (d TeamID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d TeamID) GoString() string { - return "id.TeamID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d TeamID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d TeamID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d TeamID) GoString() string { + return "TeamID(" + d.String() + ")" } // Ref returns a reference. func (d TeamID) Ref() *TeamID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d TeamID) Contains(ids []TeamID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d TeamID) Contains(ids []TeamID) bool { // CopyRef returns a copy of a reference. func (d *TeamID) CopyRef() *TeamID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *TeamID) CopyRef() *TeamID { // IDRef returns a reference of a domain id. func (d *TeamID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *TeamID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *TeamID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *TeamID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *TeamID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *TeamID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *TeamID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *TeamID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d TeamID) IsNil() bool { return ID(d).IsNil() } -// TeamIDToKeys converts IDs into a string slice. -func TeamIDToKeys(ids []TeamID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *TeamID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// TeamIDsToStrings converts IDs into a string slice. +func TeamIDsToStrings(ids []TeamID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // TeamIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *TeamIDSet) Clone() *TeamIDSet { // Merge returns a merged set func (s *TeamIDSet) Merge(s2 *TeamIDSet) *TeamIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/team_gen_test.go b/pkg/id/team_gen_test.go index 952e26a3..db29cf9b 100644 --- a/pkg/id/team_gen_test.go +++ b/pkg/id/team_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewTeamID(t *testing.T) { id := NewTeamID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestTeamIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestTeamIDFrom(t *testing.T) { result TeamID err error }{ - TeamID{}, - ErrInvalidID, + result: TeamID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestTeamIDFrom(t *testing.T) { result TeamID err error }{ - TeamID{}, - ErrInvalidID, + result: TeamID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestTeamIDFrom(t *testing.T) { result TeamID err error }{ - TeamID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: TeamID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := TeamIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := TeamIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustTeamID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustTeamID(t *testing.T) { expected: TeamID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustTeamID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustTeamID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestTeamIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *TeamID @@ -139,159 +135,149 @@ func TestTeamIDFromRef(t *testing.T) { expected: &TeamID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := TeamIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := TeamIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestTeamIDFromRefID(t *testing.T) { id := New() - - subId := TeamIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := TeamIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, TeamIDFromRefID(nil)) + assert.Nil(t, TeamIDFromRefID(&ID{})) } func TestTeamID_ID(t *testing.T) { id := New() - subId := TeamIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := TeamIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestTeamID_String(t *testing.T) { id := New() - subId := TeamIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := TeamIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", TeamID{}.String()) } -func TestTeamID_GoString(t *testing.T) { - id := New() - subId := TeamIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.TeamID("+id.String()+")") +func TestTeamID_RefString(t *testing.T) { + id := NewTeamID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, TeamID{}.RefString()) } -func TestTeamID_RefString(t *testing.T) { +func TestTeamID_GoString(t *testing.T) { id := New() - subId := TeamIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := TeamIDFromRefID(&id) + assert.Equal(t, "TeamID("+id.String()+")", id2.GoString()) + assert.Equal(t, "TeamID()", TeamID{}.GoString()) } func TestTeamID_Ref(t *testing.T) { - id := New() - subId := TeamIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewTeamID() + assert.Equal(t, TeamID(id), *id.Ref()) + assert.Nil(t, (&TeamID{}).Ref()) } func TestTeamID_Contains(t *testing.T) { id := NewTeamID() id2 := NewTeamID() assert.True(t, id.Contains([]TeamID{id, id2})) + assert.False(t, TeamID{}.Contains([]TeamID{id, id2, {}})) assert.False(t, id.Contains([]TeamID{id2})) } func TestTeamID_CopyRef(t *testing.T) { - id := New() - subId := TeamIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewTeamID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*TeamID)(nil).CopyRef()) } func TestTeamID_IDRef(t *testing.T) { id := New() - subId := TeamIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := TeamIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&TeamID{}).IDRef()) + assert.Nil(t, (*TeamID)(nil).IDRef()) } func TestTeamID_StringRef(t *testing.T) { - id := New() - subId := TeamIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewTeamID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&TeamID{}).StringRef()) + assert.Nil(t, (*TeamID)(nil).StringRef()) } func TestTeamID_MarhsalJSON(t *testing.T) { - id := New() - subId := TeamIDFromRefID(&id) + id := NewTeamID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&TeamID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*TeamID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestTeamID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &TeamID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustTeamID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &TeamID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestTeamID_MarshalText(t *testing.T) { id := New() - subId := TeamIDFromRefID(&id) + res, err := TeamIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&TeamID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*TeamID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestTeamID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &TeamID{} - - err := subId.UnmarshalText(text) - + id2 := &TeamID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestTeamID_IsNil(t *testing.T) { - subId := TeamID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *TeamIDFromRefID(&id) + assert.True(t, TeamID{}.IsNil()) + assert.False(t, NewTeamID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestTeamID_IsNilRef(t *testing.T) { + assert.True(t, TeamID{}.Ref().IsNilRef()) + assert.True(t, (*TeamID)(nil).IsNilRef()) + assert.False(t, NewTeamID().Ref().IsNilRef()) } -func TestTeamIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestTeamIDsToStrings(t *testing.T) { + tests := []struct { name string input []TeamID expected []string @@ -321,19 +307,17 @@ func TestTeamIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, TeamIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, TeamIDsToStrings(tt.input)) }) } - } func TestTeamIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestTeamIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestTeamIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := TeamIDsFrom(tc.input) if tc.expected.err != nil { - _, err := TeamIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := TeamIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestTeamIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []TeamID @@ -449,25 +431,22 @@ func TestTeamIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TeamIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTeamIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []TeamID @@ -493,21 +472,18 @@ func TestTeamIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TeamIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTeamIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []TeamID expected []ID @@ -537,28 +513,25 @@ func TestTeamIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TeamIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestTeamIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustTeamID(id1.String()) + id21 := MustTeamID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustTeamID(id2.String()) + id22 := MustTeamID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustTeamID(id3.String()) + id23 := MustTeamID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*TeamID expected []*ID @@ -570,39 +543,35 @@ func TestTeamIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*TeamID{&subId1}, + input: []*TeamID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*TeamID{&subId1, &subId2, &subId3}, + input: []*TeamID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := TeamIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewTeamIDSet(t *testing.T) { TeamIdSet := NewTeamIDSet() - assert.NotNil(t, TeamIdSet) assert.Empty(t, TeamIdSet.m) assert.Empty(t, TeamIdSet.s) } func TestTeamIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []TeamID expected *TeamIDSet @@ -663,24 +632,19 @@ func TestTeamIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewTeamIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestTeamIDSet_AddRef(t *testing.T) { - t.Parallel() - - TeamId := MustTeamID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *TeamID expected *TeamIDSet @@ -695,7 +659,7 @@ func TestTeamIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &TeamId, + input: MustTeamID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &TeamIDSet{ m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestTeamIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewTeamIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestTeamIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - TeamIDSet - TeamID - } + tests := []struct { + name string + target *TeamIDSet + input TeamID expected bool }{ { - name: "Empty Set", - input: struct { - TeamIDSet - TeamID - }{TeamIDSet: TeamIDSet{}, TeamID: MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &TeamIDSet{}, + input: MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - TeamIDSet - TeamID - }{TeamIDSet: TeamIDSet{ + target: &TeamIDSet{ m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, TeamID: MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - TeamIDSet - TeamID - }{TeamIDSet: TeamIDSet{ + target: &TeamIDSet{ m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, TeamID: MustTeamID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustTeamID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.TeamIDSet.Has(tc.input.TeamID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestTeamIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input TeamIDSet - expected TeamIDSet + input *TeamIDSet + expected *TeamIDSet }{ { - name: "Empty Set", - input: TeamIDSet{}, - expected: TeamIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &TeamIDSet{}, + expected: &TeamIDSet{}, }, { - name: "Set Contains the element", - input: TeamIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &TeamIDSet{ m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: TeamIDSet{ + expected: &TeamIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestTeamIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *TeamIDSet expected []TeamID }{ { - name: "Empty slice", + name: "Empty", input: &TeamIDSet{ m: map[TeamID]struct{}{}, s: nil, }, expected: make([]TeamID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &TeamIDSet{ @@ -854,20 +808,17 @@ func TestTeamIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestTeamIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *TeamIDSet expected *TeamIDSet @@ -922,21 +873,19 @@ func TestTeamIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestTeamIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *TeamIDSet @@ -944,6 +893,23 @@ func TestTeamIDSet_Merge(t *testing.T) { } expected *TeamIDSet }{ + { + name: "Nil Set", + input: struct { + a *TeamIDSet + b *TeamIDSet + }{ + a: &TeamIDSet{ + m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &TeamIDSet{ + m: map[TeamID]struct{}{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []TeamID{MustTeamID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestTeamIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/user_gen.go b/pkg/id/user_gen.go index 830d5f53..bb2eb0b3 100644 --- a/pkg/id/user_gen.go +++ b/pkg/id/user_gen.go @@ -44,7 +44,7 @@ func UserIDFromRef(i *string) *UserID { // UserIDFromRefID generates a new UserID from a ref of a generic ID. func UserIDFromRefID(i *ID) *UserID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := UserID(*i) @@ -58,28 +58,40 @@ func (d UserID) ID() ID { // String returns a string representation. func (d UserID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d UserID) GoString() string { - return "id.UserID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d UserID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d UserID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d UserID) GoString() string { + return "UserID(" + d.String() + ")" } // Ref returns a reference. func (d UserID) Ref() *UserID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d UserID) Contains(ids []UserID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d UserID) Contains(ids []UserID) bool { // CopyRef returns a copy of a reference. func (d *UserID) CopyRef() *UserID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *UserID) CopyRef() *UserID { // IDRef returns a reference of a domain id. func (d *UserID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *UserID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *UserID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *UserID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *UserID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *UserID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *UserID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *UserID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d UserID) IsNil() bool { return ID(d).IsNil() } -// UserIDToKeys converts IDs into a string slice. -func UserIDToKeys(ids []UserID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *UserID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// UserIDsToStrings converts IDs into a string slice. +func UserIDsToStrings(ids []UserID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // UserIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *UserIDSet) Clone() *UserIDSet { // Merge returns a merged set func (s *UserIDSet) Merge(s2 *UserIDSet) *UserIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/user_gen_test.go b/pkg/id/user_gen_test.go index 3d074a4d..0dae4566 100644 --- a/pkg/id/user_gen_test.go +++ b/pkg/id/user_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewUserID(t *testing.T) { id := NewUserID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestUserIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestUserIDFrom(t *testing.T) { result UserID err error }{ - UserID{}, - ErrInvalidID, + result: UserID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestUserIDFrom(t *testing.T) { result UserID err error }{ - UserID{}, - ErrInvalidID, + result: UserID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestUserIDFrom(t *testing.T) { result UserID err error }{ - UserID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: UserID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := UserIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := UserIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustUserID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustUserID(t *testing.T) { expected: UserID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustUserID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustUserID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestUserIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *UserID @@ -139,159 +135,149 @@ func TestUserIDFromRef(t *testing.T) { expected: &UserID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := UserIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := UserIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestUserIDFromRefID(t *testing.T) { id := New() - - subId := UserIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := UserIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, UserIDFromRefID(nil)) + assert.Nil(t, UserIDFromRefID(&ID{})) } func TestUserID_ID(t *testing.T) { id := New() - subId := UserIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := UserIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestUserID_String(t *testing.T) { id := New() - subId := UserIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := UserIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", UserID{}.String()) } -func TestUserID_GoString(t *testing.T) { - id := New() - subId := UserIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.UserID("+id.String()+")") +func TestUserID_RefString(t *testing.T) { + id := NewUserID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, UserID{}.RefString()) } -func TestUserID_RefString(t *testing.T) { +func TestUserID_GoString(t *testing.T) { id := New() - subId := UserIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := UserIDFromRefID(&id) + assert.Equal(t, "UserID("+id.String()+")", id2.GoString()) + assert.Equal(t, "UserID()", UserID{}.GoString()) } func TestUserID_Ref(t *testing.T) { - id := New() - subId := UserIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewUserID() + assert.Equal(t, UserID(id), *id.Ref()) + assert.Nil(t, (&UserID{}).Ref()) } func TestUserID_Contains(t *testing.T) { id := NewUserID() id2 := NewUserID() assert.True(t, id.Contains([]UserID{id, id2})) + assert.False(t, UserID{}.Contains([]UserID{id, id2, {}})) assert.False(t, id.Contains([]UserID{id2})) } func TestUserID_CopyRef(t *testing.T) { - id := New() - subId := UserIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewUserID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*UserID)(nil).CopyRef()) } func TestUserID_IDRef(t *testing.T) { id := New() - subId := UserIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := UserIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&UserID{}).IDRef()) + assert.Nil(t, (*UserID)(nil).IDRef()) } func TestUserID_StringRef(t *testing.T) { - id := New() - subId := UserIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewUserID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&UserID{}).StringRef()) + assert.Nil(t, (*UserID)(nil).StringRef()) } func TestUserID_MarhsalJSON(t *testing.T) { - id := New() - subId := UserIDFromRefID(&id) + id := NewUserID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&UserID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*UserID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestUserID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &UserID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustUserID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &UserID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestUserID_MarshalText(t *testing.T) { id := New() - subId := UserIDFromRefID(&id) + res, err := UserIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&UserID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*UserID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestUserID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &UserID{} - - err := subId.UnmarshalText(text) - + id2 := &UserID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestUserID_IsNil(t *testing.T) { - subId := UserID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *UserIDFromRefID(&id) + assert.True(t, UserID{}.IsNil()) + assert.False(t, NewUserID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestUserID_IsNilRef(t *testing.T) { + assert.True(t, UserID{}.Ref().IsNilRef()) + assert.True(t, (*UserID)(nil).IsNilRef()) + assert.False(t, NewUserID().Ref().IsNilRef()) } -func TestUserIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestUserIDsToStrings(t *testing.T) { + tests := []struct { name string input []UserID expected []string @@ -321,19 +307,17 @@ func TestUserIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, UserIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, UserIDsToStrings(tt.input)) }) } - } func TestUserIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestUserIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestUserIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := UserIDsFrom(tc.input) if tc.expected.err != nil { - _, err := UserIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := UserIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestUserIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []UserID @@ -449,25 +431,22 @@ func TestUserIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := UserIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestUserIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []UserID @@ -493,21 +472,18 @@ func TestUserIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := UserIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestUserIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []UserID expected []ID @@ -537,28 +513,25 @@ func TestUserIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := UserIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestUserIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustUserID(id1.String()) + id21 := MustUserID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustUserID(id2.String()) + id22 := MustUserID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustUserID(id3.String()) + id23 := MustUserID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*UserID expected []*ID @@ -570,39 +543,35 @@ func TestUserIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*UserID{&subId1}, + input: []*UserID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*UserID{&subId1, &subId2, &subId3}, + input: []*UserID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := UserIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewUserIDSet(t *testing.T) { UserIdSet := NewUserIDSet() - assert.NotNil(t, UserIdSet) assert.Empty(t, UserIdSet.m) assert.Empty(t, UserIdSet.s) } func TestUserIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []UserID expected *UserIDSet @@ -663,24 +632,19 @@ func TestUserIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewUserIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestUserIDSet_AddRef(t *testing.T) { - t.Parallel() - - UserId := MustUserID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *UserID expected *UserIDSet @@ -695,7 +659,7 @@ func TestUserIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &UserId, + input: MustUserID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &UserIDSet{ m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestUserIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewUserIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestUserIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - UserIDSet - UserID - } + tests := []struct { + name string + target *UserIDSet + input UserID expected bool }{ { - name: "Empty Set", - input: struct { - UserIDSet - UserID - }{UserIDSet: UserIDSet{}, UserID: MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &UserIDSet{}, + input: MustUserID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - UserIDSet - UserID - }{UserIDSet: UserIDSet{ + target: &UserIDSet{ m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, UserID: MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustUserID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - UserIDSet - UserID - }{UserIDSet: UserIDSet{ + target: &UserIDSet{ m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, UserID: MustUserID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustUserID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.UserIDSet.Has(tc.input.UserID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestUserIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input UserIDSet - expected UserIDSet + input *UserIDSet + expected *UserIDSet }{ { - name: "Empty Set", - input: UserIDSet{}, - expected: UserIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &UserIDSet{}, + expected: &UserIDSet{}, }, { - name: "Set Contains the element", - input: UserIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &UserIDSet{ m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: UserIDSet{ + expected: &UserIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestUserIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *UserIDSet expected []UserID }{ { - name: "Empty slice", + name: "Empty", input: &UserIDSet{ m: map[UserID]struct{}{}, s: nil, }, expected: make([]UserID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &UserIDSet{ @@ -854,20 +808,17 @@ func TestUserIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestUserIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *UserIDSet expected *UserIDSet @@ -922,21 +873,19 @@ func TestUserIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestUserIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *UserIDSet @@ -944,6 +893,23 @@ func TestUserIDSet_Merge(t *testing.T) { } expected *UserIDSet }{ + { + name: "Nil Set", + input: struct { + a *UserIDSet + b *UserIDSet + }{ + a: &UserIDSet{ + m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &UserIDSet{ + m: map[UserID]struct{}{MustUserID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []UserID{MustUserID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestUserIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } diff --git a/pkg/id/widget_gen.go b/pkg/id/widget_gen.go index 52028e49..01ed6875 100644 --- a/pkg/id/widget_gen.go +++ b/pkg/id/widget_gen.go @@ -44,7 +44,7 @@ func WidgetIDFromRef(i *string) *WidgetID { // WidgetIDFromRefID generates a new WidgetID from a ref of a generic ID. func WidgetIDFromRefID(i *ID) *WidgetID { - if i == nil { + if i == nil || i.IsNil() { return nil } nid := WidgetID(*i) @@ -58,28 +58,40 @@ func (d WidgetID) ID() ID { // String returns a string representation. func (d WidgetID) String() string { + if d.IsNil() { + return "" + } return ID(d).String() } -// GoString implements fmt.GoStringer interface. -func (d WidgetID) GoString() string { - return "id.WidgetID(" + d.String() + ")" +// StringRef returns a reference of the string representation. +func (d WidgetID) RefString() *string { + if d.IsNil() { + return nil + } + str := d.String() + return &str } -// RefString returns a reference of string representation. -func (d WidgetID) RefString() *string { - id := ID(d).String() - return &id +// GoString implements fmt.GoStringer interface. +func (d WidgetID) GoString() string { + return "WidgetID(" + d.String() + ")" } // Ref returns a reference. func (d WidgetID) Ref() *WidgetID { + if d.IsNil() { + return nil + } d2 := d return &d2 } // Contains returns whether the id is contained in the slice. func (d WidgetID) Contains(ids []WidgetID) bool { + if d.IsNil() { + return false + } for _, i := range ids { if d.ID().Equal(i.ID()) { return true @@ -90,7 +102,7 @@ func (d WidgetID) Contains(ids []WidgetID) bool { // CopyRef returns a copy of a reference. func (d *WidgetID) CopyRef() *WidgetID { - if d == nil { + if d.IsNilRef() { return nil } d2 := *d @@ -99,7 +111,7 @@ func (d *WidgetID) CopyRef() *WidgetID { // IDRef returns a reference of a domain id. func (d *WidgetID) IDRef() *ID { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d) @@ -108,7 +120,7 @@ func (d *WidgetID) IDRef() *ID { // StringRef returns a reference of a string representation. func (d *WidgetID) StringRef() *string { - if d == nil { + if d.IsNilRef() { return nil } id := ID(*d).String() @@ -117,6 +129,9 @@ func (d *WidgetID) StringRef() *string { // MarhsalJSON implements json.Marhsaler interface func (d *WidgetID) MarhsalJSON() ([]byte, error) { + if d.IsNilRef() { + return nil, nil + } return json.Marshal(d.String()) } @@ -132,7 +147,7 @@ func (d *WidgetID) UnmarhsalJSON(bs []byte) (err error) { // MarshalText implements encoding.TextMarshaler interface func (d *WidgetID) MarshalText() ([]byte, error) { - if d == nil { + if d.IsNilRef() { return nil, nil } return []byte(d.String()), nil @@ -144,18 +159,23 @@ func (d *WidgetID) UnmarshalText(text []byte) (err error) { return } -// Ref returns true if a ID is nil or zero-value +// IsNil returns true if a ID is zero-value func (d WidgetID) IsNil() bool { return ID(d).IsNil() } -// WidgetIDToKeys converts IDs into a string slice. -func WidgetIDToKeys(ids []WidgetID) []string { - keys := make([]string, 0, len(ids)) +// IsNilRef returns true if a ID is nil or zero-value +func (d *WidgetID) IsNilRef() bool { + return d == nil || ID(*d).IsNil() +} + +// WidgetIDsToStrings converts IDs into a string slice. +func WidgetIDsToStrings(ids []WidgetID) []string { + strs := make([]string, 0, len(ids)) for _, i := range ids { - keys = append(keys, i.String()) + strs = append(strs, i.String()) } - return keys + return strs } // WidgetIDsFrom converts a string slice into a ID slice. @@ -285,9 +305,6 @@ func (s *WidgetIDSet) Clone() *WidgetIDSet { // Merge returns a merged set func (s *WidgetIDSet) Merge(s2 *WidgetIDSet) *WidgetIDSet { - if s == nil { - return nil - } s3 := s.Clone() if s2 == nil { return s3 diff --git a/pkg/id/widget_gen_test.go b/pkg/id/widget_gen_test.go index 32215f0d..9dfa8d42 100644 --- a/pkg/id/widget_gen_test.go +++ b/pkg/id/widget_gen_test.go @@ -4,7 +4,6 @@ package id import ( "encoding/json" - "errors" "testing" "github.com/oklog/ulid" @@ -14,15 +13,13 @@ import ( func TestNewWidgetID(t *testing.T) { id := NewWidgetID() assert.NotNil(t, id) - ulID, err := ulid.Parse(id.String()) - - assert.NotNil(t, ulID) + u, err := ulid.Parse(id.String()) + assert.NotNil(t, u) assert.Nil(t, err) } func TestWidgetIDFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string expected struct { @@ -37,8 +34,8 @@ func TestWidgetIDFrom(t *testing.T) { result WidgetID err error }{ - WidgetID{}, - ErrInvalidID, + result: WidgetID{}, + err: ErrInvalidID, }, }, { @@ -48,8 +45,8 @@ func TestWidgetIDFrom(t *testing.T) { result WidgetID err error }{ - WidgetID{}, - ErrInvalidID, + result: WidgetID{}, + err: ErrInvalidID, }, }, { @@ -59,27 +56,26 @@ func TestWidgetIDFrom(t *testing.T) { result WidgetID err error }{ - WidgetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, - nil, + result: WidgetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, + err: nil, }, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result, err := WidgetIDFrom(tc.input) - assert.Equal(tt, tc.expected.result, result) - if err != nil { - assert.True(tt, errors.As(tc.expected.err, &err)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result, err := WidgetIDFrom(tt.input) + assert.Equal(t, tt.expected.result, result) + if tt.expected.err != nil { + assert.Equal(t, tt.expected.err, err) } }) } } func TestMustWidgetID(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input string shouldPanic bool @@ -102,23 +98,23 @@ func TestMustWidgetID(t *testing.T) { expected: WidgetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - if tc.shouldPanic { - assert.Panics(tt, func() { MustBeID(tc.input) }) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if tt.shouldPanic { + assert.Panics(t, func() { MustBeID(tt.input) }) return } - result := MustWidgetID(tc.input) - assert.Equal(tt, tc.expected, result) + result := MustWidgetID(tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestWidgetIDFromRef(t *testing.T) { - testCases := []struct { + tests := []struct { name string input string expected *WidgetID @@ -139,159 +135,149 @@ func TestWidgetIDFromRef(t *testing.T) { expected: &WidgetID{ulid.MustParse("01f2r7kg1fvvffp0gmexgy5hxy")}, }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - result := WidgetIDFromRef(&tc.input) - assert.Equal(tt, tc.expected, result) - if tc.expected != nil { - assert.Equal(tt, *tc.expected, *result) - } + + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + result := WidgetIDFromRef(&tt.input) + assert.Equal(t, tt.expected, result) }) } } func TestWidgetIDFromRefID(t *testing.T) { id := New() - - subId := WidgetIDFromRefID(&id) - - assert.NotNil(t, subId) - assert.Equal(t, subId.id, id.id) + id2 := WidgetIDFromRefID(&id) + assert.Equal(t, id.id, id2.id) + assert.Nil(t, WidgetIDFromRefID(nil)) + assert.Nil(t, WidgetIDFromRefID(&ID{})) } func TestWidgetID_ID(t *testing.T) { id := New() - subId := WidgetIDFromRefID(&id) - - idOrg := subId.ID() - - assert.Equal(t, id, idOrg) + id2 := WidgetIDFromRefID(&id) + assert.Equal(t, id, id2.ID()) } func TestWidgetID_String(t *testing.T) { id := New() - subId := WidgetIDFromRefID(&id) - - assert.Equal(t, subId.String(), id.String()) + id2 := WidgetIDFromRefID(&id) + assert.Equal(t, id.String(), id2.String()) + assert.Equal(t, "", WidgetID{}.String()) } -func TestWidgetID_GoString(t *testing.T) { - id := New() - subId := WidgetIDFromRefID(&id) - - assert.Equal(t, subId.GoString(), "id.WidgetID("+id.String()+")") +func TestWidgetID_RefString(t *testing.T) { + id := NewWidgetID() + assert.Equal(t, id.String(), *id.RefString()) + assert.Nil(t, WidgetID{}.RefString()) } -func TestWidgetID_RefString(t *testing.T) { +func TestWidgetID_GoString(t *testing.T) { id := New() - subId := WidgetIDFromRefID(&id) - - refString := subId.StringRef() - - assert.NotNil(t, refString) - assert.Equal(t, *refString, id.String()) + id2 := WidgetIDFromRefID(&id) + assert.Equal(t, "WidgetID("+id.String()+")", id2.GoString()) + assert.Equal(t, "WidgetID()", WidgetID{}.GoString()) } func TestWidgetID_Ref(t *testing.T) { - id := New() - subId := WidgetIDFromRefID(&id) - - subIdRef := subId.Ref() - - assert.Equal(t, *subId, *subIdRef) + id := NewWidgetID() + assert.Equal(t, WidgetID(id), *id.Ref()) + assert.Nil(t, (&WidgetID{}).Ref()) } func TestWidgetID_Contains(t *testing.T) { id := NewWidgetID() id2 := NewWidgetID() assert.True(t, id.Contains([]WidgetID{id, id2})) + assert.False(t, WidgetID{}.Contains([]WidgetID{id, id2, {}})) assert.False(t, id.Contains([]WidgetID{id2})) } func TestWidgetID_CopyRef(t *testing.T) { - id := New() - subId := WidgetIDFromRefID(&id) - - subIdCopyRef := subId.CopyRef() - - assert.Equal(t, *subId, *subIdCopyRef) - assert.NotSame(t, subId, subIdCopyRef) + id := NewWidgetID().Ref() + id2 := id.CopyRef() + assert.Equal(t, id, id2) + assert.NotSame(t, id, id2) + assert.Nil(t, (*WidgetID)(nil).CopyRef()) } func TestWidgetID_IDRef(t *testing.T) { id := New() - subId := WidgetIDFromRefID(&id) - - assert.Equal(t, id, *subId.IDRef()) + id2 := WidgetIDFromRefID(&id) + assert.Equal(t, &id, id2.IDRef()) + assert.Nil(t, (&WidgetID{}).IDRef()) + assert.Nil(t, (*WidgetID)(nil).IDRef()) } func TestWidgetID_StringRef(t *testing.T) { - id := New() - subId := WidgetIDFromRefID(&id) - - assert.Equal(t, *subId.StringRef(), id.String()) + id := NewWidgetID() + assert.Equal(t, id.String(), *id.StringRef()) + assert.Nil(t, (&WidgetID{}).StringRef()) + assert.Nil(t, (*WidgetID)(nil).StringRef()) } func TestWidgetID_MarhsalJSON(t *testing.T) { - id := New() - subId := WidgetIDFromRefID(&id) + id := NewWidgetID() + res, err := id.MarhsalJSON() + assert.Nil(t, err) + exp, _ := json.Marshal(id.String()) + assert.Equal(t, exp, res) - res, err := subId.MarhsalJSON() - exp, _ := json.Marshal(subId.String()) + res, err = (&WidgetID{}).MarhsalJSON() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*WidgetID)(nil).MarhsalJSON() assert.Nil(t, err) - assert.Equal(t, exp, res) + assert.Nil(t, res) } func TestWidgetID_UnmarhsalJSON(t *testing.T) { jsonString := "\"01f3zhkysvcxsnzepyyqtq21fb\"" - - subId := &WidgetID{} - - err := subId.UnmarhsalJSON([]byte(jsonString)) - + id := MustWidgetID("01f3zhkysvcxsnzepyyqtq21fb") + id2 := &WidgetID{} + err := id2.UnmarhsalJSON([]byte(jsonString)) assert.Nil(t, err) - assert.Equal(t, "01f3zhkysvcxsnzepyyqtq21fb", subId.String()) + assert.Equal(t, id, *id2) } func TestWidgetID_MarshalText(t *testing.T) { id := New() - subId := WidgetIDFromRefID(&id) + res, err := WidgetIDFromRefID(&id).MarshalText() + assert.Nil(t, err) + assert.Equal(t, []byte(id.String()), res) - res, err := subId.MarshalText() + res, err = (&WidgetID{}).MarshalText() + assert.Nil(t, err) + assert.Nil(t, res) + res, err = (*WidgetID)(nil).MarshalText() assert.Nil(t, err) - assert.Equal(t, []byte(id.String()), res) + assert.Nil(t, res) } func TestWidgetID_UnmarshalText(t *testing.T) { text := []byte("01f3zhcaq35403zdjnd6dcm0t2") - - subId := &WidgetID{} - - err := subId.UnmarshalText(text) - + id2 := &WidgetID{} + err := id2.UnmarshalText(text) assert.Nil(t, err) - assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", subId.String()) - + assert.Equal(t, "01f3zhcaq35403zdjnd6dcm0t2", id2.String()) } func TestWidgetID_IsNil(t *testing.T) { - subId := WidgetID{} - - assert.True(t, subId.IsNil()) - - id := New() - subId = *WidgetIDFromRefID(&id) + assert.True(t, WidgetID{}.IsNil()) + assert.False(t, NewWidgetID().IsNil()) +} - assert.False(t, subId.IsNil()) +func TestWidgetID_IsNilRef(t *testing.T) { + assert.True(t, WidgetID{}.Ref().IsNilRef()) + assert.True(t, (*WidgetID)(nil).IsNilRef()) + assert.False(t, NewWidgetID().Ref().IsNilRef()) } -func TestWidgetIDToKeys(t *testing.T) { - t.Parallel() - testCases := []struct { +func TestWidgetIDsToStrings(t *testing.T) { + tests := []struct { name string input []WidgetID expected []string @@ -321,19 +307,17 @@ func TestWidgetIDToKeys(t *testing.T) { }, } - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, WidgetIDToKeys(tc.input)) + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.expected, WidgetIDsToStrings(tt.input)) }) } - } func TestWidgetIDsFrom(t *testing.T) { - t.Parallel() - testCases := []struct { + tests := []struct { name string input []string expected struct { @@ -383,10 +367,10 @@ func TestWidgetIDsFrom(t *testing.T) { }, }, { - name: "multiple elements", + name: "error", input: []string{ "01f3zhcaq35403zdjnd6dcm0t1", - "01f3zhcaq35403zdjnd6dcm0t2", + "x", "01f3zhcaq35403zdjnd6dcm0t3", }, expected: struct { @@ -399,27 +383,25 @@ func TestWidgetIDsFrom(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + res, err := WidgetIDsFrom(tc.input) if tc.expected.err != nil { - _, err := WidgetIDsFrom(tc.input) - assert.True(tt, errors.As(ErrInvalidID, &err)) + assert.Equal(t, tc.expected.err, err) + assert.Nil(t, res) } else { - res, err := WidgetIDsFrom(tc.input) - assert.Equal(tt, tc.expected.res, res) - assert.Nil(tt, err) + assert.Nil(t, err) + assert.Equal(t, tc.expected.res, res) } - }) } } func TestWidgetIDsFromID(t *testing.T) { t.Parallel() - testCases := []struct { + tests := []struct { name string input []ID expected []WidgetID @@ -449,25 +431,22 @@ func TestWidgetIDsFromID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := WidgetIDsFromID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestWidgetIDsFromIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - testCases := []struct { + tests := []struct { name string input []*ID expected []WidgetID @@ -493,21 +472,18 @@ func TestWidgetIDsFromIDRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := WidgetIDsFromIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestWidgetIDsToID(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []WidgetID expected []ID @@ -537,28 +513,25 @@ func TestWidgetIDsToID(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := WidgetIDsToID(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestWidgetIDsToIDRef(t *testing.T) { - t.Parallel() - id1 := MustBeID("01f3zhcaq35403zdjnd6dcm0t1") - subId1 := MustWidgetID(id1.String()) + id21 := MustWidgetID(id1.String()) id2 := MustBeID("01f3zhcaq35403zdjnd6dcm0t2") - subId2 := MustWidgetID(id2.String()) + id22 := MustWidgetID(id2.String()) id3 := MustBeID("01f3zhcaq35403zdjnd6dcm0t3") - subId3 := MustWidgetID(id3.String()) + id23 := MustWidgetID(id3.String()) - testCases := []struct { + tests := []struct { name string input []*WidgetID expected []*ID @@ -570,39 +543,35 @@ func TestWidgetIDsToIDRef(t *testing.T) { }, { name: "1 element", - input: []*WidgetID{&subId1}, + input: []*WidgetID{&id21}, expected: []*ID{&id1}, }, { name: "multiple elements", - input: []*WidgetID{&subId1, &subId2, &subId3}, + input: []*WidgetID{&id21, &id22, &id23}, expected: []*ID{&id1, &id2, &id3}, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() res := WidgetIDsToIDRef(tc.input) - assert.Equal(tt, tc.expected, res) + assert.Equal(t, tc.expected, res) }) } } func TestNewWidgetIDSet(t *testing.T) { WidgetIdSet := NewWidgetIDSet() - assert.NotNil(t, WidgetIdSet) assert.Empty(t, WidgetIdSet.m) assert.Empty(t, WidgetIdSet.s) } func TestWidgetIDSet_Add(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input []WidgetID expected *WidgetIDSet @@ -663,24 +632,19 @@ func TestWidgetIDSet_Add(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewWidgetIDSet() set.Add(tc.input...) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestWidgetIDSet_AddRef(t *testing.T) { - t.Parallel() - - WidgetId := MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1") - - testCases := []struct { + tests := []struct { name string input *WidgetID expected *WidgetIDSet @@ -695,7 +659,7 @@ func TestWidgetIDSet_AddRef(t *testing.T) { }, { name: "1 element", - input: &WidgetId, + input: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1").Ref(), expected: &WidgetIDSet{ m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, @@ -703,127 +667,117 @@ func TestWidgetIDSet_AddRef(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - + t.Run(tc.name, func(t *testing.T) { + t.Parallel() set := NewWidgetIDSet() set.AddRef(tc.input) - assert.Equal(tt, tc.expected, set) + assert.Equal(t, tc.expected, set) }) } } func TestWidgetIDSet_Has(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - input struct { - WidgetIDSet - WidgetID - } + tests := []struct { + name string + target *WidgetIDSet + input WidgetID expected bool }{ { - name: "Empty Set", - input: struct { - WidgetIDSet - WidgetID - }{WidgetIDSet: WidgetIDSet{}, WidgetID: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, + name: "Empty Set", + target: &WidgetIDSet{}, + input: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: false, }, { name: "Set Contains the element", - input: struct { - WidgetIDSet - WidgetID - }{WidgetIDSet: WidgetIDSet{ + target: &WidgetIDSet{ m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, WidgetID: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + input: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"), expected: true, }, { name: "Set does not Contains the element", - input: struct { - WidgetIDSet - WidgetID - }{WidgetIDSet: WidgetIDSet{ + target: &WidgetIDSet{ m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, - }, WidgetID: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t2")}, + }, + input: MustWidgetID("01f3zhcaq35403zdjnd6dcm0t2"), expected: false, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - assert.Equal(tt, tc.expected, tc.input.WidgetIDSet.Has(tc.input.WidgetID)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.target.Has(tc.input)) }) } } func TestWidgetIDSet_Clear(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string - input WidgetIDSet - expected WidgetIDSet + input *WidgetIDSet + expected *WidgetIDSet }{ { - name: "Empty Set", - input: WidgetIDSet{}, - expected: WidgetIDSet{ - m: nil, - s: nil, - }, + name: "Empty set", + input: &WidgetIDSet{}, + expected: &WidgetIDSet{}, }, { - name: "Set Contains the element", - input: WidgetIDSet{ + name: "Nil set", + input: nil, + expected: nil, + }, + { + name: "Contains the element", + input: &WidgetIDSet{ m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, }, - expected: WidgetIDSet{ + expected: &WidgetIDSet{ m: nil, s: nil, }, }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - set := tc.input - p := &set - p.Clear() - assert.Equal(tt, tc.expected, *p) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + tc.input.Clear() + assert.Equal(t, tc.expected, tc.input) }) } } func TestWidgetIDSet_All(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *WidgetIDSet expected []WidgetID }{ { - name: "Empty slice", + name: "Empty", input: &WidgetIDSet{ m: map[WidgetID]struct{}{}, s: nil, }, expected: make([]WidgetID, 0), }, + { + name: "Nil", + input: nil, + expected: nil, + }, { name: "1 element", input: &WidgetIDSet{ @@ -854,20 +808,17 @@ func TestWidgetIDSet_All(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.All()) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.All()) }) } } func TestWidgetIDSet_Clone(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input *WidgetIDSet expected *WidgetIDSet @@ -922,21 +873,19 @@ func TestWidgetIDSet_Clone(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() + t.Run(tc.name, func(t *testing.T) { + t.Parallel() clone := tc.input.Clone() - assert.Equal(tt, tc.expected, clone) - assert.False(tt, tc.input == clone) + assert.Equal(t, tc.expected, clone) + assert.NotSame(t, tc.input, clone) }) } } func TestWidgetIDSet_Merge(t *testing.T) { - t.Parallel() - - testCases := []struct { + tests := []struct { name string input struct { a *WidgetIDSet @@ -944,6 +893,23 @@ func TestWidgetIDSet_Merge(t *testing.T) { } expected *WidgetIDSet }{ + { + name: "Nil Set", + input: struct { + a *WidgetIDSet + b *WidgetIDSet + }{ + a: &WidgetIDSet{ + m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + b: nil, + }, + expected: &WidgetIDSet{ + m: map[WidgetID]struct{}{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1"): {}}, + s: []WidgetID{MustWidgetID("01f3zhcaq35403zdjnd6dcm0t1")}, + }, + }, { name: "Empty Set", input: struct { @@ -1000,12 +966,11 @@ func TestWidgetIDSet_Merge(t *testing.T) { }, } - for _, tc := range testCases { + for _, tc := range tests { tc := tc - t.Run(tc.name, func(tt *testing.T) { - tt.Parallel() - - assert.Equal(tt, tc.expected, tc.input.a.Merge(tc.input.b)) + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.expected, tc.input.a.Merge(tc.input.b)) }) } } From 947c5f5b6e96310b1be394f257c4d0c580818d16 Mon Sep 17 00:00:00 2001 From: rot1024 Date: Fri, 14 Jan 2022 23:02:58 +0900 Subject: [PATCH 2/5] remove unnecessary comments, refactor NewID and MustID --- internal/infrastructure/memory/container.go | 1 - internal/infrastructure/memory/scene_lock.go | 7 +++---- internal/usecase/cursor.go | 1 - internal/usecase/operator.go | 9 --------- pkg/asset/asset.go | 13 ++----------- pkg/asset/builder.go | 18 +++--------------- pkg/id/plugin.go | 1 - pkg/id/plugin_extension.go | 6 ------ pkg/scene/builder.go | 3 +-- pkg/scene/builder/encoder_test.go | 8 ++++---- pkg/scene/cluster.go | 2 +- pkg/scene/lock.go | 2 -- pkg/scene/plugin.go | 4 ---- pkg/scene/plugin_system.go | 10 ---------- pkg/scene/widget.go | 2 +- pkg/tag/group_builder.go | 4 ++-- pkg/tag/item_builder.go | 4 ++-- pkg/user/builder.go | 4 ++-- pkg/user/role.go | 4 +--- pkg/user/team_builder.go | 13 ++----------- pkg/visualizer/visualizer.go | 2 -- 21 files changed, 24 insertions(+), 94 deletions(-) diff --git a/internal/infrastructure/memory/container.go b/internal/infrastructure/memory/container.go index 77db2647..888479b8 100644 --- a/internal/infrastructure/memory/container.go +++ b/internal/infrastructure/memory/container.go @@ -4,7 +4,6 @@ import ( "github.com/reearth/reearth-backend/internal/usecase/repo" ) -// InitRepos _ func InitRepos(c *repo.Container) *repo.Container { if c == nil { c = &repo.Container{} diff --git a/internal/infrastructure/memory/scene_lock.go b/internal/infrastructure/memory/scene_lock.go index ab467e0b..2ac0ef28 100644 --- a/internal/infrastructure/memory/scene_lock.go +++ b/internal/infrastructure/memory/scene_lock.go @@ -4,10 +4,9 @@ import ( "context" "sync" + "github.com/reearth/reearth-backend/internal/usecase/repo" "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/scene" - - "github.com/reearth/reearth-backend/internal/usecase/repo" ) type sceneLock struct { @@ -19,7 +18,7 @@ func NewSceneLock() repo.SceneLock { } func (r *sceneLock) GetLock(ctx context.Context, sceneID id.SceneID) (scene.LockMode, error) { - if id.ID(sceneID).IsNil() { + if sceneID.IsNil() { return "", id.ErrInvalidID } if v, ok := r.lock.Load(sceneID); ok { @@ -33,7 +32,7 @@ func (r *sceneLock) GetLock(ctx context.Context, sceneID id.SceneID) (scene.Lock func (r *sceneLock) GetAllLock(ctx context.Context, sceneID []id.SceneID) ([]scene.LockMode, error) { res := make([]scene.LockMode, 0, len(sceneID)) for _, si := range sceneID { - if id.ID(si).IsNil() { + if si.IsNil() { return nil, id.ErrInvalidID } if v, ok := r.lock.Load(si); ok { diff --git a/internal/usecase/cursor.go b/internal/usecase/cursor.go index f18fab83..6e3e5973 100644 --- a/internal/usecase/cursor.go +++ b/internal/usecase/cursor.go @@ -1,4 +1,3 @@ package usecase -// Cursor _ type Cursor string diff --git a/internal/usecase/operator.go b/internal/usecase/operator.go index cc9edd35..e1c606f1 100644 --- a/internal/usecase/operator.go +++ b/internal/usecase/operator.go @@ -5,7 +5,6 @@ import ( "github.com/reearth/reearth-backend/pkg/user" ) -// Operator _ type Operator struct { User id.UserID ReadableTeams []id.TeamID @@ -13,7 +12,6 @@ type Operator struct { OwningTeams []id.TeamID } -// OperatorFrom _ func OperatorFrom(u id.UserID, teams []*user.Team) *Operator { rt := []id.TeamID{} wt := []id.TeamID{} @@ -41,7 +39,6 @@ func OperatorFrom(u id.UserID, teams []*user.Team) *Operator { } } -// Teams _ func (o *Operator) Teams(r user.Role) []id.TeamID { if o == nil { return nil @@ -58,7 +55,6 @@ func (o *Operator) Teams(r user.Role) []id.TeamID { return nil } -// IsReadableTeamIncluded _ func (o *Operator) IsReadableTeamIncluded(team id.TeamID) bool { if o == nil { return false @@ -71,7 +67,6 @@ func (o *Operator) IsReadableTeamIncluded(team id.TeamID) bool { return false } -// IsWritableTeamIncluded _ func (o *Operator) IsWritableTeamIncluded(team id.TeamID) bool { if o == nil { return false @@ -84,7 +79,6 @@ func (o *Operator) IsWritableTeamIncluded(team id.TeamID) bool { return false } -// IsOwningTeamIncluded _ func (o *Operator) IsOwningTeamIncluded(team id.TeamID) bool { if o == nil { return false @@ -97,7 +91,6 @@ func (o *Operator) IsOwningTeamIncluded(team id.TeamID) bool { return false } -// IsReadableTeamsIncluded _ func (o *Operator) IsReadableTeamsIncluded(teams []id.TeamID) bool { if o == nil { return false @@ -112,7 +105,6 @@ func (o *Operator) IsReadableTeamsIncluded(teams []id.TeamID) bool { return false } -// IsWritableTeamsIncluded _ func (o *Operator) IsWritableTeamsIncluded(teams []id.TeamID) bool { if o == nil { return false @@ -127,7 +119,6 @@ func (o *Operator) IsWritableTeamsIncluded(teams []id.TeamID) bool { return false } -// IsOwningTeamsIncluded _ func (o *Operator) IsOwningTeamsIncluded(teams []id.TeamID) bool { if o == nil { return false diff --git a/pkg/asset/asset.go b/pkg/asset/asset.go index c0b60c75..c74119e7 100644 --- a/pkg/asset/asset.go +++ b/pkg/asset/asset.go @@ -8,15 +8,13 @@ import ( ) var ( - // ErrEmptyTeamID _ ErrEmptyTeamID = errors.New("require team id") - // ErrEmptyURL _ + ErrEmptyURL = errors.New("require valid url") - // ErrEmptySize _ + ErrEmptySize = errors.New("file size cannot be zero") ) -// Asset _ type Asset struct { id id.AssetID createdAt time.Time @@ -27,37 +25,30 @@ type Asset struct { contentType string } -// ID _ func (a *Asset) ID() id.AssetID { return a.id } -// Team _ func (a *Asset) Team() id.TeamID { return a.team } -// Name _ func (a *Asset) Name() string { return a.name } -// Size _ func (a *Asset) Size() int64 { return a.size } -// URL _ func (a *Asset) URL() string { return a.url } -// ContentType _ func (a *Asset) ContentType() string { return a.contentType } -// CreatedAt _ func (a *Asset) CreatedAt() time.Time { if a == nil { return time.Time{} diff --git a/pkg/asset/builder.go b/pkg/asset/builder.go index b75ddc6c..485d135d 100644 --- a/pkg/asset/builder.go +++ b/pkg/asset/builder.go @@ -6,22 +6,19 @@ import ( "github.com/reearth/reearth-backend/pkg/id" ) -// Builder _ type Builder struct { a *Asset } -// New _ func New() *Builder { return &Builder{a: &Asset{}} } -// Build _ func (b *Builder) Build() (*Asset, error) { - if id.ID(b.a.id).IsNil() { + if b.a.id.IsNil() { return nil, id.ErrInvalidID } - if id.ID(b.a.team).IsNil() { + if b.a.team.IsNil() { return nil, ErrEmptyTeamID } if b.a.url == "" { @@ -36,7 +33,6 @@ func (b *Builder) Build() (*Asset, error) { return b.a, nil } -// MustBuild _ func (b *Builder) MustBuild() *Asset { r, err := b.Build() if err != nil { @@ -45,49 +41,41 @@ func (b *Builder) MustBuild() *Asset { return r } -// ID _ func (b *Builder) ID(id id.AssetID) *Builder { b.a.id = id return b } -// NewID _ func (b *Builder) NewID() *Builder { - b.a.id = id.AssetID(id.New()) + b.a.id = id.NewAssetID() return b } -// Team _ func (b *Builder) Team(team id.TeamID) *Builder { b.a.team = team return b } -// Name _ func (b *Builder) Name(name string) *Builder { b.a.name = name return b } -// Size _ func (b *Builder) Size(size int64) *Builder { b.a.size = size return b } -// URL _ func (b *Builder) URL(url string) *Builder { b.a.url = url return b } -// ContentType _ func (b *Builder) ContentType(contentType string) *Builder { b.a.contentType = contentType return b } -// CreatedAt - func (b *Builder) CreatedAt(createdAt time.Time) *Builder { b.a.createdAt = createdAt return b diff --git a/pkg/id/plugin.go b/pkg/id/plugin.go index 8de5c59a..4d951529 100644 --- a/pkg/id/plugin.go +++ b/pkg/id/plugin.go @@ -173,7 +173,6 @@ func (d PluginID) Ref() *PluginID { return &d2 } -// CopyRef _ func (d *PluginID) CopyRef() *PluginID { if d == nil { return nil diff --git a/pkg/id/plugin_extension.go b/pkg/id/plugin_extension.go index 4be0d7c2..c401a6c5 100644 --- a/pkg/id/plugin_extension.go +++ b/pkg/id/plugin_extension.go @@ -1,9 +1,7 @@ package id -// PluginExtensionID _ type PluginExtensionID string -// PluginExtensionIDFromRef _ func PluginExtensionIDFromRef(id *string) *PluginExtensionID { if id == nil { return nil @@ -12,12 +10,10 @@ func PluginExtensionIDFromRef(id *string) *PluginExtensionID { return &id2 } -// Ref _ func (id PluginExtensionID) Ref() *PluginExtensionID { return &id } -// CopyRef _ func (id *PluginExtensionID) CopyRef() *PluginExtensionID { if id == nil { return nil @@ -26,12 +22,10 @@ func (id *PluginExtensionID) CopyRef() *PluginExtensionID { return &id2 } -// String _ func (id PluginExtensionID) String() string { return string(id) } -// StringRef _ func (id *PluginExtensionID) StringRef() *string { if id == nil { return nil diff --git a/pkg/scene/builder.go b/pkg/scene/builder.go index 7b15de0e..085ac3aa 100644 --- a/pkg/scene/builder.go +++ b/pkg/scene/builder.go @@ -14,7 +14,6 @@ func New() *Builder { return &Builder{scene: &Scene{}} } -// Build _ func (b *Builder) Build() (*Scene, error) { if b.scene.id.ID().IsNil() { return nil, id.ErrInvalidID @@ -54,7 +53,7 @@ func (b *Builder) ID(id id.SceneID) *Builder { } func (b *Builder) NewID() *Builder { - b.scene.id = id.SceneID(id.New()) + b.scene.id = id.NewSceneID() return b } diff --git a/pkg/scene/builder/encoder_test.go b/pkg/scene/builder/encoder_test.go index 0bb83d02..9c1177b3 100644 --- a/pkg/scene/builder/encoder_test.go +++ b/pkg/scene/builder/encoder_test.go @@ -88,11 +88,11 @@ func TestEncoder_Encode(t *testing.T) { } func TestEncoder_Layers(t *testing.T) { - lid := id.MustLayerID(id.New().String()) - sid := id.MustSceneID(id.New().String()) - pid := id.MustPropertyID(id.New().String()) + lid := id.NewLayerID() + sid := id.NewSceneID() + pid := id.NewPropertyID() ex := id.PluginExtensionID("marker") - iid := id.MustPropertyItemID(id.New().String()) + iid := id.NewPropertyItemID() v1 := property.LatLng{ Lat: 4.4, Lng: 53.4, diff --git a/pkg/scene/cluster.go b/pkg/scene/cluster.go index be5faa90..f32cfb43 100644 --- a/pkg/scene/cluster.go +++ b/pkg/scene/cluster.go @@ -9,7 +9,7 @@ type Cluster struct { } func NewCluster(cid id.ClusterID, name string, pid id.PropertyID) (*Cluster, error) { - if id.ID(cid).IsNil() { + if cid.IsNil() { return nil, id.ErrInvalidID } return &Cluster{ diff --git a/pkg/scene/lock.go b/pkg/scene/lock.go index 03afcd1a..b99d18e3 100644 --- a/pkg/scene/lock.go +++ b/pkg/scene/lock.go @@ -16,7 +16,6 @@ const ( LockModePublishing LockMode = "publishing" ) -// IsLocked _ func (l LockMode) IsLocked() bool { switch l { case LockModeFree: @@ -27,7 +26,6 @@ func (l LockMode) IsLocked() bool { return true } -// Validate _ func (l LockMode) Validate() (LockMode, bool) { switch l { case LockModeFree: diff --git a/pkg/scene/plugin.go b/pkg/scene/plugin.go index 63e863d2..c15ef56e 100644 --- a/pkg/scene/plugin.go +++ b/pkg/scene/plugin.go @@ -4,13 +4,11 @@ import ( "github.com/reearth/reearth-backend/pkg/id" ) -// Plugin _ type Plugin struct { plugin id.PluginID property *id.PropertyID } -// NewPlugin _ func NewPlugin(plugin id.PluginID, property *id.PropertyID) *Plugin { if property != nil { property2 := *property @@ -22,12 +20,10 @@ func NewPlugin(plugin id.PluginID, property *id.PropertyID) *Plugin { } } -// Plugin _ func (s Plugin) Plugin() id.PluginID { return s.plugin } -// Property _ func (s Plugin) Property() *id.PropertyID { property := s.property if property != nil { diff --git a/pkg/scene/plugin_system.go b/pkg/scene/plugin_system.go index e0c756cf..169f77eb 100644 --- a/pkg/scene/plugin_system.go +++ b/pkg/scene/plugin_system.go @@ -4,12 +4,10 @@ import ( "github.com/reearth/reearth-backend/pkg/id" ) -// PluginSystem _ type PluginSystem struct { plugins []*Plugin } -// NewPluginSystem _ func NewPluginSystem(p []*Plugin) *PluginSystem { if p == nil { return &PluginSystem{plugins: []*Plugin{}} @@ -34,12 +32,10 @@ func NewPluginSystem(p []*Plugin) *PluginSystem { return &PluginSystem{plugins: p2} } -// Plugins _ func (p *PluginSystem) Plugins() []*Plugin { return append([]*Plugin{}, p.plugins...) } -// Property _ func (p *PluginSystem) Property(id id.PluginID) *id.PropertyID { for _, p := range p.plugins { if p.plugin.Equal(id) { @@ -49,7 +45,6 @@ func (p *PluginSystem) Property(id id.PluginID) *id.PropertyID { return nil } -// Has _ func (p *PluginSystem) Has(id id.PluginID) bool { for _, p2 := range p.plugins { if p2.plugin.Equal(id) { @@ -59,7 +54,6 @@ func (p *PluginSystem) Has(id id.PluginID) bool { return false } -// HasPlugin _ func (p *PluginSystem) HasPlugin(id id.PluginID) bool { name := id.Name() for _, p2 := range p.plugins { @@ -70,7 +64,6 @@ func (p *PluginSystem) HasPlugin(id id.PluginID) bool { return false } -// Add _ func (p *PluginSystem) Add(sp *Plugin) { if sp == nil || p.Has(sp.plugin) || sp.plugin.Equal(id.OfficialPluginID) { return @@ -79,7 +72,6 @@ func (p *PluginSystem) Add(sp *Plugin) { p.plugins = append(p.plugins, &sp2) } -// Remove _ func (p *PluginSystem) Remove(pid id.PluginID) { if pid.Equal(id.OfficialPluginID) { return @@ -92,7 +84,6 @@ func (p *PluginSystem) Remove(pid id.PluginID) { } } -// Upgrade _ func (p *PluginSystem) Upgrade(pid, newID id.PluginID) { for i, p2 := range p.plugins { if p2.plugin.Equal(id.OfficialPluginID) { @@ -105,7 +96,6 @@ func (p *PluginSystem) Upgrade(pid, newID id.PluginID) { } } -// Properties _ func (p *PluginSystem) Properties() []id.PropertyID { if p == nil { return nil diff --git a/pkg/scene/widget.go b/pkg/scene/widget.go index 5e7943ad..e420d1aa 100644 --- a/pkg/scene/widget.go +++ b/pkg/scene/widget.go @@ -14,7 +14,7 @@ type Widget struct { } func NewWidget(wid id.WidgetID, plugin id.PluginID, extension id.PluginExtensionID, property id.PropertyID, enabled, extended bool) (*Widget, error) { - if !plugin.Validate() || string(extension) == "" || id.ID(property).IsNil() { + if !plugin.Validate() || string(extension) == "" || property.IsNil() { return nil, id.ErrInvalidID } diff --git a/pkg/tag/group_builder.go b/pkg/tag/group_builder.go index 76bce120..7b948021 100644 --- a/pkg/tag/group_builder.go +++ b/pkg/tag/group_builder.go @@ -21,10 +21,10 @@ func GroupFrom(t Tag) *Group { } func (b *GroupBuilder) Build() (*Group, error) { - if id.ID(b.g.id).IsNil() { + if b.g.id.IsNil() { return nil, id.ErrInvalidID } - if id.ID(b.g.sceneId).IsNil() { + if b.g.sceneId.IsNil() { return nil, ErrInvalidSceneID } if b.g.label == "" { diff --git a/pkg/tag/item_builder.go b/pkg/tag/item_builder.go index 4d2cb79a..a44cbb7d 100644 --- a/pkg/tag/item_builder.go +++ b/pkg/tag/item_builder.go @@ -19,10 +19,10 @@ func ItemFrom(t Tag) *Item { } func (b *ItemBuilder) Build() (*Item, error) { - if id.ID(b.i.id).IsNil() { + if b.i.id.IsNil() { return nil, id.ErrInvalidID } - if id.ID(b.i.sceneId).IsNil() { + if b.i.sceneId.IsNil() { return nil, ErrInvalidSceneID } if b.i.label == "" { diff --git a/pkg/user/builder.go b/pkg/user/builder.go index 495983d5..afdaed61 100644 --- a/pkg/user/builder.go +++ b/pkg/user/builder.go @@ -14,7 +14,7 @@ func New() *Builder { } func (b *Builder) Build() (*User, error) { - if id.ID(b.u.id).IsNil() { + if b.u.id.IsNil() { return nil, id.ErrInvalidID } return b.u, nil @@ -34,7 +34,7 @@ func (b *Builder) ID(id id.UserID) *Builder { } func (b *Builder) NewID() *Builder { - b.u.id = id.UserID(id.New()) + b.u.id = id.NewUserID() return b } diff --git a/pkg/user/role.go b/pkg/user/role.go index b6359d34..53efa91c 100644 --- a/pkg/user/role.go +++ b/pkg/user/role.go @@ -12,11 +12,10 @@ var ( RoleWriter = Role("writer") // RoleOwner is a role who can have full controll of project RoleOwner = Role("owner") - // ErrInvalidRole _ + ErrInvalidRole = errors.New("invalid role") ) -// Role _ type Role string func checkRole(role Role) bool { @@ -31,7 +30,6 @@ func checkRole(role Role) bool { return false } -// RoleFromString _ func RoleFromString(r string) (Role, error) { role := Role(strings.ToLower(r)) diff --git a/pkg/user/team_builder.go b/pkg/user/team_builder.go index ec62b689..8f53bdcc 100644 --- a/pkg/user/team_builder.go +++ b/pkg/user/team_builder.go @@ -4,21 +4,18 @@ import ( "github.com/reearth/reearth-backend/pkg/id" ) -// TeamBuilder _ type TeamBuilder struct { t *Team members map[id.UserID]Role personal bool } -// NewTeam _ func NewTeam() *TeamBuilder { return &TeamBuilder{t: &Team{}} } -// Build _ func (b *TeamBuilder) Build() (*Team, error) { - if id.ID(b.t.id).IsNil() { + if b.t.id.IsNil() { return nil, id.ErrInvalidID } if b.members == nil { @@ -30,7 +27,6 @@ func (b *TeamBuilder) Build() (*Team, error) { return b.t, nil } -// MustBuild _ func (b *TeamBuilder) MustBuild() *Team { r, err := b.Build() if err != nil { @@ -39,31 +35,26 @@ func (b *TeamBuilder) MustBuild() *Team { return r } -// ID _ func (b *TeamBuilder) ID(id id.TeamID) *TeamBuilder { b.t.id = id return b } -// NewID _ func (b *TeamBuilder) NewID() *TeamBuilder { - b.t.id = id.TeamID(id.New()) + b.t.id = id.NewTeamID() return b } -// Name _ func (b *TeamBuilder) Name(name string) *TeamBuilder { b.t.name = name return b } -// Members _ func (b *TeamBuilder) Members(members map[id.UserID]Role) *TeamBuilder { b.members = members return b } -// Personal _ func (b *TeamBuilder) Personal(p bool) *TeamBuilder { b.personal = p return b diff --git a/pkg/visualizer/visualizer.go b/pkg/visualizer/visualizer.go index 3e7b2235..a9a49cf6 100644 --- a/pkg/visualizer/visualizer.go +++ b/pkg/visualizer/visualizer.go @@ -1,9 +1,7 @@ package visualizer -// Visualizer _ type Visualizer string const ( - // VisualizerCesium _ VisualizerCesium Visualizer = "cesium" ) From d130808da6c786169262d9d91acbbb034055536f Mon Sep 17 00:00:00 2001 From: rot1024 Date: Sat, 15 Jan 2022 00:39:35 +0900 Subject: [PATCH 3/5] use id aliases --- pkg/asset/asset.go | 18 +- pkg/asset/asset_test.go | 15 +- pkg/asset/builder.go | 10 +- pkg/asset/builder_test.go | 51 ++-- pkg/asset/id.go | 31 +++ pkg/builtin/main.go | 9 +- pkg/builtin/main_test.go | 13 +- pkg/dataset/builder.go | 24 +- pkg/dataset/csvparser.go | 15 +- pkg/dataset/csvparser_test.go | 3 +- pkg/dataset/dataset.go | 22 +- pkg/dataset/dataset_test.go | 17 +- pkg/dataset/diff.go | 5 +- pkg/dataset/field.go | 10 +- pkg/dataset/graph_iterator.go | 20 +- pkg/dataset/graph_iterator_test.go | 33 ++- pkg/dataset/graph_loader.go | 8 +- pkg/dataset/id.go | 45 ++++ pkg/dataset/list.go | 24 +- pkg/dataset/list_test.go | 21 +- pkg/dataset/loader.go | 10 +- pkg/dataset/schema.go | 26 +- pkg/dataset/schema_builder.go | 24 +- pkg/dataset/schema_field.go | 12 +- pkg/dataset/schema_field_builder.go | 12 +- pkg/dataset/schema_field_diff.go | 6 +- pkg/dataset/schema_graph_iterator.go | 21 +- pkg/dataset/schema_graph_iterator_test.go | 31 ++- pkg/dataset/schema_list.go | 11 +- pkg/dataset/schema_list_test.go | 15 +- pkg/layer/builder.go | 16 +- pkg/layer/decoding/common.go | 32 +-- pkg/layer/decoding/czml.go | 9 +- pkg/layer/decoding/czml_test.go | 4 +- pkg/layer/decoding/decoder.go | 3 +- pkg/layer/decoding/geojson.go | 9 +- pkg/layer/decoding/geojson_test.go | 4 +- pkg/layer/decoding/kml.go | 9 +- pkg/layer/decoding/kml_test.go | 24 +- pkg/layer/decoding/reearth.go | 55 +++-- pkg/layer/decoding/reearth_test.go | 37 ++- pkg/layer/decoding/shp.go | 9 +- pkg/layer/encoding/czml.go | 4 +- pkg/layer/encoding/czml_test.go | 58 +++-- pkg/layer/encoding/exporter.go | 3 +- pkg/layer/encoding/geojson.go | 4 +- pkg/layer/encoding/geojson_test.go | 65 +++-- pkg/layer/encoding/kml.go | 4 +- pkg/layer/encoding/kml_test.go | 67 +++--- pkg/layer/encoding/shp.go | 4 +- pkg/layer/encoding/shp_test.go | 33 ++- pkg/layer/group.go | 23 +- pkg/layer/group_builder.go | 22 +- pkg/layer/group_test.go | 31 ++- pkg/layer/id.go | 75 ++++++ pkg/layer/id_list.go | 63 ++--- pkg/layer/id_list_test.go | 12 +- pkg/layer/infobox.go | 25 +- pkg/layer/infobox_field.go | 21 +- pkg/layer/infobox_field_builder.go | 21 +- pkg/layer/infobox_test.go | 29 ++- pkg/layer/initializer.go | 45 ++-- pkg/layer/initializer_test.go | 83 ++++--- pkg/layer/item.go | 21 +- pkg/layer/item_builder.go | 22 +- pkg/layer/layer.go | 45 ++-- pkg/layer/layerops/initializer.go | 9 +- pkg/layer/layerops/initializer_test.go | 20 +- pkg/layer/layerops/processor.go | 9 +- pkg/layer/layerops/processor_test.go | 29 ++- pkg/layer/list.go | 32 +-- pkg/layer/list_test.go | 3 +- pkg/layer/loader.go | 18 +- pkg/layer/loader_test.go | 25 +- pkg/layer/merged.go | 25 +- pkg/layer/merged_test.go | 39 ++- pkg/layer/merging/merged.go | 15 +- pkg/layer/merging/merger.go | 3 +- pkg/layer/merging/merger_test.go | 29 ++- pkg/layer/tag.go | 6 - pkg/plugin/builder.go | 9 +- pkg/plugin/builder_test.go | 51 ++-- pkg/plugin/extension.go | 9 +- pkg/plugin/extension_builder.go | 7 +- pkg/plugin/extension_builder_test.go | 29 ++- pkg/plugin/extension_test.go | 9 +- pkg/plugin/id.go | 31 +++ pkg/plugin/loader.go | 4 +- pkg/plugin/manifest/convert.go | 35 ++- pkg/plugin/manifest/convert_test.go | 67 +++--- pkg/plugin/manifest/parser.go | 8 +- pkg/plugin/manifest/parser_test.go | 23 +- pkg/plugin/manifest/parser_translation.go | 8 +- .../manifest/parser_translation_test.go | 4 +- pkg/plugin/plugin.go | 29 +-- pkg/plugin/plugin_test.go | 19 +- pkg/plugin/pluginpack/package.go | 4 +- pkg/plugin/pluginpack/package_test.go | 3 +- pkg/project/builder.go | 11 +- pkg/project/builder_test.go | 33 ++- pkg/project/id.go | 31 +++ pkg/project/project.go | 14 +- pkg/project/project_test.go | 3 +- pkg/project/publishment_status.go | 6 +- pkg/property/builder.go | 28 +-- pkg/property/builder_test.go | 63 +++-- pkg/property/condition.go | 6 +- pkg/property/field.go | 23 +- pkg/property/field_builder.go | 8 +- pkg/property/field_builder_test.go | 19 +- pkg/property/field_test.go | 25 +- pkg/property/group.go | 38 ++- pkg/property/group_builder.go | 14 +- pkg/property/group_builder_test.go | 49 ++-- pkg/property/group_list.go | 58 ++--- pkg/property/group_list_builder.go | 14 +- pkg/property/group_list_builder_test.go | 55 +++-- pkg/property/group_list_test.go | 223 +++++++++--------- pkg/property/group_test.go | 85 ++++--- pkg/property/id.go | 71 ++++++ pkg/property/id_test.go | 9 + pkg/property/initializer.go | 52 ++-- pkg/property/initializer_test.go | 113 +++++---- pkg/property/item.go | 25 +- pkg/property/item_builder.go | 8 +- pkg/property/item_test.go | 29 ++- pkg/property/link.go | 77 ++---- pkg/property/link_test.go | 133 ++++++----- pkg/property/list.go | 22 +- pkg/property/list_test.go | 7 +- pkg/property/loader.go | 12 +- pkg/property/loader_test.go | 21 +- pkg/property/merged.go | 64 +++-- pkg/property/merged_test.go | 142 ++++++----- pkg/property/pointer.go | 42 ++-- pkg/property/pointer_test.go | 7 +- pkg/property/property.go | 35 ++- pkg/property/property_test.go | 75 +++--- pkg/property/schema.go | 21 +- pkg/property/schema_builder.go | 8 +- pkg/property/schema_builder_test.go | 45 ++-- pkg/property/schema_field.go | 5 +- pkg/property/schema_field_builder.go | 5 +- pkg/property/schema_field_builder_test.go | 9 +- pkg/property/schema_field_ui.go | 1 - pkg/property/schema_group.go | 25 +- pkg/property/schema_group_builder.go | 11 +- pkg/property/schema_group_builder_test.go | 15 +- pkg/property/schema_group_test.go | 33 ++- pkg/property/schema_list.go | 4 +- pkg/property/schema_test.go | 25 +- pkg/property/sealed.go | 31 ++- pkg/property/sealed_test.go | 71 +++--- pkg/scene/builder.go | 22 +- pkg/scene/builder/builder_test.go | 63 +++-- pkg/scene/builder/encoder_test.go | 20 +- pkg/scene/builder/scene.go | 5 +- pkg/scene/builder/scene_test.go | 25 +- pkg/scene/builder_test.go | 142 ++++++----- pkg/scene/cluster.go | 20 +- pkg/scene/cluster_list.go | 12 +- pkg/scene/cluster_list_test.go | 37 ++- pkg/scene/cluster_test.go | 35 ++- pkg/scene/id.go | 68 ++++++ pkg/scene/plugin.go | 14 +- pkg/scene/plugin_system.go | 26 +- pkg/scene/plugin_system_test.go | 83 ++++--- pkg/scene/plugin_test.go | 5 +- pkg/scene/scene.go | 40 ++-- pkg/scene/scene_test.go | 33 ++- pkg/scene/sceneops/dataset_migrator.go | 43 ++-- pkg/scene/sceneops/dataset_migrator_test.go | 14 +- pkg/scene/sceneops/plugin_installer.go | 4 +- pkg/scene/sceneops/plugin_migrator.go | 25 +- pkg/scene/widget.go | 26 +- pkg/scene/widget_align_system.go | 10 +- pkg/scene/widget_align_system_test.go | 73 +++--- pkg/scene/widget_area.go | 26 +- pkg/scene/widget_area_test.go | 93 ++++---- pkg/scene/widget_section.go | 6 +- pkg/scene/widget_section_test.go | 49 ++-- pkg/scene/widget_system.go | 18 +- pkg/scene/widget_system_test.go | 115 +++++---- pkg/scene/widget_test.go | 37 ++- pkg/scene/widget_zone.go | 6 +- pkg/scene/widget_zone_test.go | 49 ++-- pkg/tag/group_builder.go | 12 +- pkg/tag/group_test.go | 27 +-- pkg/tag/id.go | 41 ++++ pkg/tag/item.go | 20 +- pkg/tag/item_builder.go | 18 +- pkg/tag/item_test.go | 33 ++- pkg/tag/list.go | 18 +- pkg/tag/list_test.go | 23 +- pkg/tag/tag.go | 14 +- pkg/user/builder.go | 9 +- pkg/user/builder_test.go | 25 +- pkg/user/id.go | 23 ++ pkg/user/initializer.go | 11 +- pkg/user/initializer_test.go | 15 +- pkg/user/members.go | 34 ++- pkg/user/members_test.go | 81 ++++--- pkg/user/team.go | 6 +- pkg/user/team_builder.go | 14 +- pkg/user/team_builder_test.go | 25 +- pkg/user/team_test.go | 7 +- pkg/user/user.go | 11 +- pkg/user/user_test.go | 15 +- 208 files changed, 2986 insertions(+), 2963 deletions(-) create mode 100644 pkg/asset/id.go create mode 100644 pkg/dataset/id.go create mode 100644 pkg/layer/id.go create mode 100644 pkg/plugin/id.go create mode 100644 pkg/project/id.go create mode 100644 pkg/property/id.go create mode 100644 pkg/property/id_test.go create mode 100644 pkg/scene/id.go create mode 100644 pkg/tag/id.go create mode 100644 pkg/user/id.go diff --git a/pkg/asset/asset.go b/pkg/asset/asset.go index c74119e7..ad417d0d 100644 --- a/pkg/asset/asset.go +++ b/pkg/asset/asset.go @@ -3,33 +3,29 @@ package asset import ( "errors" "time" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( ErrEmptyTeamID = errors.New("require team id") - - ErrEmptyURL = errors.New("require valid url") - - ErrEmptySize = errors.New("file size cannot be zero") + ErrEmptyURL = errors.New("require valid url") + ErrEmptySize = errors.New("file size cannot be zero") ) type Asset struct { - id id.AssetID + id ID createdAt time.Time - team id.TeamID + team TeamID name string // file name size int64 // file size url string contentType string } -func (a *Asset) ID() id.AssetID { +func (a *Asset) ID() ID { return a.id } -func (a *Asset) Team() id.TeamID { +func (a *Asset) Team() TeamID { return a.team } @@ -53,5 +49,5 @@ func (a *Asset) CreatedAt() time.Time { if a == nil { return time.Time{} } - return id.ID(a.id).Timestamp() + return createdAt(a.id) } diff --git a/pkg/asset/asset_test.go b/pkg/asset/asset_test.go index b0b65643..d685bd52 100644 --- a/pkg/asset/asset_test.go +++ b/pkg/asset/asset_test.go @@ -4,20 +4,19 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestAsset(t *testing.T) { - aid := id.NewAssetID() - tid := id.NewTeamID() - d := id.ID(aid).Timestamp() + aid := NewID() + tid := NewTeamID() + d := createdAt(aid) testCases := []struct { Name string Expected struct { - ID id.AssetID + ID ID CreatedAt time.Time - Team id.TeamID + Team TeamID Name string Size int64 Url string @@ -27,9 +26,9 @@ func TestAsset(t *testing.T) { }{ { Expected: struct { - ID id.AssetID + ID ID CreatedAt time.Time - Team id.TeamID + Team TeamID Name string Size int64 Url string diff --git a/pkg/asset/builder.go b/pkg/asset/builder.go index 485d135d..48f88e4e 100644 --- a/pkg/asset/builder.go +++ b/pkg/asset/builder.go @@ -2,8 +2,6 @@ package asset import ( "time" - - "github.com/reearth/reearth-backend/pkg/id" ) type Builder struct { @@ -16,7 +14,7 @@ func New() *Builder { func (b *Builder) Build() (*Asset, error) { if b.a.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.a.team.IsNil() { return nil, ErrEmptyTeamID @@ -41,17 +39,17 @@ func (b *Builder) MustBuild() *Asset { return r } -func (b *Builder) ID(id id.AssetID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.a.id = id return b } func (b *Builder) NewID() *Builder { - b.a.id = id.NewAssetID() + b.a.id = NewID() return b } -func (b *Builder) Team(team id.TeamID) *Builder { +func (b *Builder) Team(team TeamID) *Builder { b.a.team = team return b } diff --git a/pkg/asset/builder_test.go b/pkg/asset/builder_test.go index 0142afb7..ada47282 100644 --- a/pkg/asset/builder_test.go +++ b/pkg/asset/builder_test.go @@ -5,19 +5,18 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestBuilder_Build(t *testing.T) { - aid := id.NewAssetID() - tid := id.NewTeamID() + aid := NewID() + tid := NewTeamID() d := time.Date(1900, 1, 1, 00, 00, 0, 1, time.UTC) testCases := []struct { Name, AssetName string - Id id.AssetID + Id ID CreatedAt time.Time - Team id.TeamID + Team TeamID Size int64 Url string ContentType string @@ -46,9 +45,9 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "failed empty size", - Id: id.NewAssetID(), + Id: NewID(), CreatedAt: d, - Team: id.NewTeamID(), + Team: NewTeamID(), Size: 0, Url: "tt://xxx.zz", ContentType: "bbb", @@ -57,9 +56,9 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "failed empty url", - Id: id.NewAssetID(), + Id: NewID(), CreatedAt: d, - Team: id.NewTeamID(), + Team: NewTeamID(), Size: 10, Url: "", ContentType: "bbb", @@ -68,9 +67,9 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "failed empty team", - Id: id.NewAssetID(), + Id: NewID(), CreatedAt: d, - Team: id.TeamID{}, + Team: TeamID{}, Size: 10, Url: "tt://xxx.zz", ContentType: "bbb", @@ -79,9 +78,9 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "failed invalid Id", - Id: id.AssetID{}, + Id: ID{}, CreatedAt: d, - Team: id.NewTeamID(), + Team: NewTeamID(), Size: 10, Url: "tt://xxx.zz", ContentType: "bbb", @@ -112,14 +111,14 @@ func TestBuilder_Build(t *testing.T) { } func TestBuilder_MustBuild(t *testing.T) { - aid := id.NewAssetID() - tid := id.NewTeamID() + aid := NewID() + tid := NewTeamID() d := time.Date(1900, 1, 1, 00, 00, 0, 1, time.UTC) testCases := []struct { name, assetName string createdAt time.Time - id id.AssetID - team id.TeamID + id ID + team TeamID size int64 url string contentType string @@ -149,8 +148,8 @@ func TestBuilder_MustBuild(t *testing.T) { { name: "failed empty size", createdAt: d, - id: id.NewAssetID(), - team: id.NewTeamID(), + id: NewID(), + team: NewTeamID(), size: 0, url: "tt://xxx.zz", contentType: "bbb", @@ -160,8 +159,8 @@ func TestBuilder_MustBuild(t *testing.T) { { name: "failed empty url", createdAt: d, - id: id.NewAssetID(), - team: id.NewTeamID(), + id: NewID(), + team: NewTeamID(), size: 10, url: "", contentType: "bbb", @@ -171,8 +170,8 @@ func TestBuilder_MustBuild(t *testing.T) { { name: "failed empty team", createdAt: d, - id: id.NewAssetID(), - team: id.TeamID{}, + id: NewID(), + team: TeamID{}, size: 10, url: "tt://xxx.zz", contentType: "bbb", @@ -182,8 +181,8 @@ func TestBuilder_MustBuild(t *testing.T) { { name: "failed invalid Id", createdAt: d, - id: id.AssetID{}, - team: id.NewTeamID(), + id: ID{}, + team: NewTeamID(), size: 10, url: "tt://xxx.zz", contentType: "bbb", @@ -231,6 +230,6 @@ func TestBuilder_MustBuild(t *testing.T) { } func TestNewID(t *testing.T) { - a := New().NewID().URL("tt://xxx.bb").Team(id.NewTeamID()).Size(10).MustBuild() + a := New().NewID().URL("tt://xxx.bb").Team(NewTeamID()).Size(10).MustBuild() assert.False(t, a.id.IsNil()) } diff --git a/pkg/asset/id.go b/pkg/asset/id.go new file mode 100644 index 00000000..7a259992 --- /dev/null +++ b/pkg/asset/id.go @@ -0,0 +1,31 @@ +package asset + +import ( + "time" + + "github.com/reearth/reearth-backend/pkg/id" +) + +type ID = id.AssetID +type TeamID = id.TeamID + +var NewID = id.NewAssetID +var NewTeamID = id.NewTeamID + +var MustID = id.MustAssetID +var MustTeamID = id.MustTeamID + +var IDFrom = id.AssetIDFrom +var TeamIDFrom = id.TeamIDFrom + +var IDFromRef = id.AssetIDFromRef +var TeamIDFromRef = id.TeamIDFromRef + +var IDFromRefID = id.AssetIDFromRefID +var TeamIDFromRefID = id.TeamIDFromRefID + +var ErrInvalidID = id.ErrInvalidID + +func createdAt(i ID) time.Time { + return id.ID(i).Timestamp() +} diff --git a/pkg/builtin/main.go b/pkg/builtin/main.go index 513a2352..e64c659c 100644 --- a/pkg/builtin/main.go +++ b/pkg/builtin/main.go @@ -3,7 +3,6 @@ package builtin import ( _ "embed" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/plugin/manifest" "github.com/reearth/reearth-backend/pkg/property" @@ -20,10 +19,10 @@ var pluginTranslationList = map[string]*manifest.TranslationRoot{"ja": manifest. var pluginManifest = manifest.MergeManifestTranslation(manifest.MustParseSystemFromBytes(pluginManifestJSON, nil), pluginTranslationList) // MUST NOT CHANGE -var PropertySchemaIDVisualizerCesium = id.MustPropertySchemaID("reearth/cesium") +var PropertySchemaIDVisualizerCesium = property.MustSchemaID("reearth/cesium") // MUST NOT CHANGE -var PropertySchemaIDInfobox = id.MustPropertySchemaID("reearth/infobox") +var PropertySchemaIDInfobox = property.MustSchemaID("reearth/infobox") func GetPropertySchemaByVisualizer(v visualizer.Visualizer) *property.Schema { for _, p := range pluginManifest.ExtensionSchema { @@ -42,7 +41,7 @@ func MustPropertySchemaByVisualizer(v visualizer.Visualizer) *property.Schema { return ps } -func GetPropertySchema(id id.PropertySchemaID) *property.Schema { +func GetPropertySchema(id property.SchemaID) *property.Schema { for _, p := range pluginManifest.ExtensionSchema { if id == p.ID() { return p @@ -55,7 +54,7 @@ func Plugin() *plugin.Plugin { return pluginManifest.Plugin } -func GetPlugin(id id.PluginID) *plugin.Plugin { +func GetPlugin(id plugin.ID) *plugin.Plugin { if id.Equal(pluginManifest.Plugin.ID()) { return pluginManifest.Plugin } diff --git a/pkg/builtin/main_test.go b/pkg/builtin/main_test.go index 0f8e06c9..fa444d16 100644 --- a/pkg/builtin/main_test.go +++ b/pkg/builtin/main_test.go @@ -3,7 +3,8 @@ package builtin import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/plugin" + "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/visualizer" "github.com/stretchr/testify/assert" ) @@ -45,17 +46,17 @@ func TestPlugin(t *testing.T) { func TestGetPlugin(t *testing.T) { testCases := []struct { name string - pluginID id.PluginID + pluginID plugin.ID expectedNil bool }{ { name: "Official Plugin", - pluginID: id.OfficialPluginID, + pluginID: plugin.OfficialPluginID, expectedNil: false, }, { name: "foo plugin", - pluginID: id.MustPluginID("foo~1.1.1"), + pluginID: plugin.MustID("foo~1.1.1"), expectedNil: true, }, } @@ -76,7 +77,7 @@ func TestGetPlugin(t *testing.T) { func TestGetPropertySchema(t *testing.T) { testCases := []struct { name string - psId id.PropertySchemaID + psId property.SchemaID expectedNil bool }{ { @@ -86,7 +87,7 @@ func TestGetPropertySchema(t *testing.T) { }, { name: "unknown propertySchemaId", - psId: id.MustPropertySchemaID("xxx~1.1.1/aa"), + psId: property.MustSchemaID("xxx~1.1.1/aa"), expectedNil: true, }, } diff --git a/pkg/dataset/builder.go b/pkg/dataset/builder.go index 33919ae2..7fb866b1 100644 --- a/pkg/dataset/builder.go +++ b/pkg/dataset/builder.go @@ -1,9 +1,5 @@ package dataset -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type Builder struct { d *Dataset } @@ -13,12 +9,12 @@ func New() *Builder { } func (b *Builder) Build() (*Dataset, error) { - if id.ID(b.d.id).IsNil() { - return nil, id.ErrInvalidID + if b.d.id.IsNil() { + return nil, ErrInvalidID } if b.d.fields == nil || b.d.order == nil { - b.d.fields = map[id.DatasetSchemaFieldID]*Field{} - b.d.order = []id.DatasetSchemaFieldID{} + b.d.fields = map[FieldID]*Field{} + b.d.order = []FieldID{} } return b.d, nil } @@ -31,17 +27,17 @@ func (b *Builder) MustBuild() *Dataset { return r } -func (b *Builder) ID(id id.DatasetID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.d.id = id return b } func (b *Builder) NewID() *Builder { - b.d.id = id.DatasetID(id.New()) + b.d.id = NewID() return b } -func (b *Builder) Scene(scene id.SceneID) *Builder { +func (b *Builder) Scene(scene SceneID) *Builder { b.d.scene = scene return b } @@ -51,14 +47,14 @@ func (b *Builder) Source(source string) *Builder { return b } -func (b *Builder) Schema(schema id.DatasetSchemaID) *Builder { +func (b *Builder) Schema(schema SchemaID) *Builder { b.d.schema = schema return b } func (b *Builder) Fields(fields []*Field) *Builder { - b.d.fields = map[id.DatasetSchemaFieldID]*Field{} - b.d.order = make([]id.DatasetSchemaFieldID, 0, len(fields)) + b.d.fields = map[FieldID]*Field{} + b.d.order = make([]FieldID, 0, len(fields)) sources := map[string]struct{}{} for _, f := range b.d.fields { diff --git a/pkg/dataset/csvparser.go b/pkg/dataset/csvparser.go index 16f77f6a..3d9bbcb7 100644 --- a/pkg/dataset/csvparser.go +++ b/pkg/dataset/csvparser.go @@ -6,17 +6,12 @@ import ( "io" "strconv" "strings" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( - // ErrFailedToParseCSVorTSVFile _ ErrFailedToParseCSVorTSVFile error = errors.New("failed to parse file content") - // ErrIncompatibleSchema _ - ErrIncompatibleSchema error = errors.New("schema is not compatible with csv") - // ErrDuplicatiedNameFields _ - ErrDuplicatiedNameFields error = errors.New("failed to parse, name-duplicated fields") + ErrIncompatibleSchema error = errors.New("schema is not compatible with csv") + ErrDuplicatiedNameFields error = errors.New("failed to parse, name-duplicated fields") ) type DatasetCSVParser struct { @@ -53,7 +48,7 @@ func (p *DatasetCSVParser) validateLine(line []string) bool { return len(p.headers) == len(line) } -func (p *DatasetCSVParser) GuessSchema(sid id.SceneID) error { +func (p *DatasetCSVParser) GuessSchema(sid SceneID) error { if !p.validateLine(p.firstline) { return ErrFailedToParseCSVorTSVFile } @@ -95,7 +90,7 @@ func (p *DatasetCSVParser) ReadAll() (*Schema, []*Dataset, error) { return nil, nil, errors.New("schema is not generated yet") } var fields []*Field - schemafieldmap := make(map[string]id.DatasetSchemaFieldID) + schemafieldmap := make(map[string]FieldID) for _, f := range p.schema.Fields() { if _, ok := schemafieldmap[f.Name()]; !ok { schemafieldmap[f.Name()] = f.ID() @@ -141,7 +136,7 @@ func (p *DatasetCSVParser) ReadAll() (*Schema, []*Dataset, error) { return p.schema, datasets, nil } -func (p *DatasetCSVParser) getFields(line []string, sfm map[string]id.DatasetSchemaFieldID) ([]*Field, error) { +func (p *DatasetCSVParser) getFields(line []string, sfm map[string]FieldID) ([]*Field, error) { fields := []*Field{} var lat, lng *float64 for i, record := range line { diff --git a/pkg/dataset/csvparser_test.go b/pkg/dataset/csvparser_test.go index 534dc32e..ea3f8e01 100644 --- a/pkg/dataset/csvparser_test.go +++ b/pkg/dataset/csvparser_test.go @@ -4,7 +4,6 @@ import ( "strings" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -18,7 +17,7 @@ func TestCSVParser(t *testing.T) { p := NewCSVParser(r, "hoge.csv", ',') err := p.Init() assert.NoError(t, err) - sceneID := id.NewSceneID() + sceneID := NewSceneID() err = p.GuessSchema(sceneID) assert.NoError(t, err) diff --git a/pkg/dataset/dataset.go b/pkg/dataset/dataset.go index f06678ed..271ade5a 100644 --- a/pkg/dataset/dataset.go +++ b/pkg/dataset/dataset.go @@ -1,24 +1,22 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - type Dataset struct { - id id.DatasetID + id ID source string - schema id.DatasetSchemaID - fields map[id.DatasetSchemaFieldID]*Field - order []id.DatasetSchemaFieldID - scene id.SceneID + schema SchemaID + fields map[FieldID]*Field + order []FieldID + scene SceneID } -func (d *Dataset) ID() (i id.DatasetID) { +func (d *Dataset) ID() (i ID) { if d == nil { return } return d.id } -func (d *Dataset) Scene() (i id.SceneID) { +func (d *Dataset) Scene() (i SceneID) { if d == nil { return } @@ -32,7 +30,7 @@ func (d *Dataset) Source() string { return d.source } -func (d *Dataset) Schema() (i id.DatasetSchemaID) { +func (d *Dataset) Schema() (i SchemaID) { if d == nil { return } @@ -50,14 +48,14 @@ func (d *Dataset) Fields() []*Field { return fields } -func (d *Dataset) Field(id id.DatasetSchemaFieldID) *Field { +func (d *Dataset) Field(id FieldID) *Field { if d == nil || d.fields == nil { return nil } return d.fields[id] } -func (d *Dataset) FieldRef(id *id.DatasetSchemaFieldID) *Field { +func (d *Dataset) FieldRef(id *FieldID) *Field { if d == nil || id == nil { return nil } diff --git a/pkg/dataset/dataset_test.go b/pkg/dataset/dataset_test.go index 9520080a..df3110ca 100644 --- a/pkg/dataset/dataset_test.go +++ b/pkg/dataset/dataset_test.go @@ -3,14 +3,13 @@ package dataset import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestDataset_Interface(t *testing.T) { - f1 := id.NewDatasetSchemaFieldID() - f2 := id.NewDatasetSchemaFieldID() - sid := id.NewDatasetSchemaID() + f1 := NewFieldID() + f2 := NewFieldID() + sid := NewSchemaID() tests := []struct { name string @@ -20,11 +19,11 @@ func TestDataset_Interface(t *testing.T) { }{ { name: "ok", - schema: NewSchema().ID(sid).Scene(id.NewSceneID()).Fields([]*SchemaField{ + schema: NewSchema().ID(sid).Scene(NewSceneID()).Fields([]*SchemaField{ NewSchemaField().ID(f1).Name("foo").Type(ValueTypeNumber).MustBuild(), NewSchemaField().ID(f2).Name("bar").Type(ValueTypeLatLng).MustBuild(), }).MustBuild(), - dataset: New().NewID().Scene(id.NewSceneID()).Schema(sid).Fields([]*Field{ + dataset: New().NewID().Scene(NewSceneID()).Schema(sid).Fields([]*Field{ NewField(f1, ValueTypeNumber.ValueFrom(1), ""), NewField(f2, ValueTypeLatLng.ValueFrom(LatLng{Lat: 1, Lng: 2}), ""), }).MustBuild(), @@ -51,8 +50,8 @@ func TestDataset_Interface(t *testing.T) { } func TestDataset_InterfaceWithFieldIDs(t *testing.T) { - f1 := id.NewDatasetSchemaFieldID() - f2 := id.NewDatasetSchemaFieldID() + f1 := NewFieldID() + f2 := NewFieldID() tests := []struct { name string @@ -61,7 +60,7 @@ func TestDataset_InterfaceWithFieldIDs(t *testing.T) { }{ { name: "ok", - dataset: New().NewID().Scene(id.NewSceneID()).Schema(id.NewDatasetSchemaID()).Fields([]*Field{ + dataset: New().NewID().Scene(NewSceneID()).Schema(NewSchemaID()).Fields([]*Field{ NewField(f1, ValueTypeNumber.ValueFrom(1), ""), NewField(f2, ValueTypeLatLng.ValueFrom(LatLng{Lat: 1, Lng: 2}), ""), }).MustBuild(), diff --git a/pkg/dataset/diff.go b/pkg/dataset/diff.go index bbd41a72..c7b5722d 100644 --- a/pkg/dataset/diff.go +++ b/pkg/dataset/diff.go @@ -1,10 +1,7 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - -// Diff _ type Diff struct { Added List Removed List - Others map[id.DatasetID]*Dataset + Others map[ID]*Dataset } diff --git a/pkg/dataset/field.go b/pkg/dataset/field.go index e99dffd3..bf6355c6 100644 --- a/pkg/dataset/field.go +++ b/pkg/dataset/field.go @@ -1,14 +1,12 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - type Field struct { - field id.DatasetSchemaFieldID + field FieldID value *Value source string } -func NewField(field id.DatasetSchemaFieldID, value *Value, source string) *Field { +func NewField(field FieldID, value *Value, source string) *Field { if value == nil { return nil } @@ -18,14 +16,14 @@ func NewField(field id.DatasetSchemaFieldID, value *Value, source string) *Field } } -func (d *Field) Field() (i id.DatasetSchemaFieldID) { +func (d *Field) Field() (i FieldID) { if d == nil { return } return d.field } -func (d *Field) FieldRef() *id.DatasetSchemaFieldID { +func (d *Field) FieldRef() *FieldID { if d == nil { return nil } diff --git a/pkg/dataset/graph_iterator.go b/pkg/dataset/graph_iterator.go index db4432f7..17e357e1 100644 --- a/pkg/dataset/graph_iterator.go +++ b/pkg/dataset/graph_iterator.go @@ -1,29 +1,27 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - // GraphIterator is a iterator for graphically exploring a dataset. type GraphIterator struct { m Map - ids [][]id.DatasetID + ids [][]ID currentIndex int currentDepthIndex int maxDepth int } -func GraphIteratorFrom(root id.DatasetID, depth int) *GraphIterator { +func GraphIteratorFrom(root ID, depth int) *GraphIterator { return &GraphIterator{ - ids: [][]id.DatasetID{{root}}, + ids: [][]ID{{root}}, maxDepth: depth, } } -func (di *GraphIterator) Next(d *Dataset) (id.DatasetID, bool) { +func (di *GraphIterator) Next(d *Dataset) (ID, bool) { if di == nil || di.maxDepth == 0 || len(di.ids) == 0 || d == nil { - return id.DatasetID{}, false + return ID{}, false } if di.currentDepthIndex >= len(di.ids) { - return id.DatasetID{}, true + return ID{}, true } if di.m == nil { @@ -33,13 +31,13 @@ func (di *GraphIterator) Next(d *Dataset) (id.DatasetID, bool) { // add fields if len(di.ids) <= di.currentDepthIndex+1 { - di.ids = append(di.ids, []id.DatasetID{}) + di.ids = append(di.ids, []ID{}) } nextDepthIDs := di.ids[di.currentDepthIndex+1] currentIDs := di.ids[di.currentDepthIndex] for _, f := range d.Fields() { if r := f.Value().ValueRef(); r != nil { - if rid, err := id.DatasetIDFrom(*r); err == nil { + if rid, err := IDFrom(*r); err == nil { nextDepthIDs = append(nextDepthIDs, rid) } } @@ -53,7 +51,7 @@ func (di *GraphIterator) Next(d *Dataset) (id.DatasetID, bool) { if di.maxDepth <= di.currentDepthIndex || len(nextDepthIDs) == 0 { // done di.currentDepthIndex++ - return id.DatasetID{}, true + return ID{}, true } di.currentDepthIndex++ } else { diff --git a/pkg/dataset/graph_iterator_test.go b/pkg/dataset/graph_iterator_test.go index 254b1a8e..04837c03 100644 --- a/pkg/dataset/graph_iterator_test.go +++ b/pkg/dataset/graph_iterator_test.go @@ -3,40 +3,39 @@ package dataset import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestDatasetGraphIterator(t *testing.T) { - sid := id.NewSceneID() - dsid := id.NewDatasetSchemaID() + sid := NewSceneID() + dsid := NewSchemaID() - d0id := id.NewDatasetID() - d11id := id.NewDatasetID() - d12id := id.NewDatasetID() - d21id := id.NewDatasetID() - d31id := id.NewDatasetID() - d32id := id.NewDatasetID() + d0id := NewID() + d11id := NewID() + d12id := NewID() + d21id := NewID() + d31id := NewID() + d32id := NewID() d0, _ := New().ID(d0id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeRef.ValueFrom(d11id.ID()), ""), - NewField(id.NewDatasetSchemaFieldID(), ValueTypeRef.ValueFrom(d12id.ID()), ""), + NewField(NewFieldID(), ValueTypeRef.ValueFrom(d11id.ID()), ""), + NewField(NewFieldID(), ValueTypeRef.ValueFrom(d12id.ID()), ""), }).Build() d11, _ := New().ID(d11id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeRef.ValueFrom(d21id.ID()), ""), + NewField(NewFieldID(), ValueTypeRef.ValueFrom(d21id.ID()), ""), }).Build() d12, _ := New().ID(d12id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeString.ValueFrom("hoge"), ""), + NewField(NewFieldID(), ValueTypeString.ValueFrom("hoge"), ""), }).Build() d21, _ := New().ID(d21id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeRef.ValueFrom(d31id.ID()), ""), - NewField(id.NewDatasetSchemaFieldID(), ValueTypeRef.ValueFrom(d32id.ID()), ""), + NewField(NewFieldID(), ValueTypeRef.ValueFrom(d31id.ID()), ""), + NewField(NewFieldID(), ValueTypeRef.ValueFrom(d32id.ID()), ""), }).Build() d31, _ := New().ID(d31id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeString.ValueFrom("foo"), ""), + NewField(NewFieldID(), ValueTypeString.ValueFrom("foo"), ""), }).Build() d32, _ := New().ID(d32id).Schema(dsid).Scene(sid).Fields([]*Field{ - NewField(id.NewDatasetSchemaFieldID(), ValueTypeString.ValueFrom("bar"), ""), + NewField(NewFieldID(), ValueTypeString.ValueFrom("bar"), ""), }).Build() it := GraphIteratorFrom(d0id, 3) diff --git a/pkg/dataset/graph_loader.go b/pkg/dataset/graph_loader.go index a613abf4..623280e9 100644 --- a/pkg/dataset/graph_loader.go +++ b/pkg/dataset/graph_loader.go @@ -2,21 +2,19 @@ package dataset import ( "context" - - "github.com/reearth/reearth-backend/pkg/id" ) -type GraphLoader func(context.Context, id.DatasetID, ...id.DatasetSchemaFieldID) (List, *Field, error) +type GraphLoader func(context.Context, ID, ...FieldID) (List, *Field, error) func GraphLoaderFromMap(m Map) GraphLoader { - return func(ctx context.Context, root id.DatasetID, fields ...id.DatasetSchemaFieldID) (List, *Field, error) { + return func(ctx context.Context, root ID, fields ...FieldID) (List, *Field, error) { list, field := m.GraphSearchByFields(root, fields...) return list, field, nil } } func GraphLoaderFromMapAndGraph(m Map, g GraphLoader) GraphLoader { - return func(ctx context.Context, root id.DatasetID, fields ...id.DatasetSchemaFieldID) (List, *Field, error) { + return func(ctx context.Context, root ID, fields ...FieldID) (List, *Field, error) { if m != nil { if len(fields) == 0 { return List{m[root]}, nil, nil diff --git a/pkg/dataset/id.go b/pkg/dataset/id.go new file mode 100644 index 00000000..701ffb11 --- /dev/null +++ b/pkg/dataset/id.go @@ -0,0 +1,45 @@ +package dataset + +import "github.com/reearth/reearth-backend/pkg/id" + +type ID = id.DatasetID +type FieldID = id.DatasetSchemaFieldID +type SchemaID = id.DatasetSchemaID +type SceneID = id.SceneID + +var NewID = id.NewDatasetID +var NewSchemaID = id.NewDatasetSchemaID +var NewFieldID = id.NewDatasetSchemaFieldID +var NewSceneID = id.NewSceneID + +var MustID = id.MustDatasetID +var MustSchemaID = id.MustDatasetSchemaID +var MustFieldID = id.MustDatasetSchemaFieldID +var MustSceneID = id.MustSceneID + +var IDFrom = id.DatasetIDFrom +var SchemaIDFrom = id.DatasetSchemaIDFrom +var FieldIDFrom = id.DatasetSchemaFieldIDFrom +var SceneIDFrom = id.SceneIDFrom + +var IDFromRef = id.DatasetIDFromRef +var SchemaIDFromRef = id.DatasetSchemaIDFromRef +var FieldIDFromRef = id.DatasetSchemaFieldIDFromRef +var SceneIDFromRef = id.SceneIDFromRef + +var IDFromRefID = id.DatasetIDFromRefID +var SchemaIDFromRefID = id.DatasetSchemaIDFromRefID +var FieldIDFromRefID = id.DatasetSchemaFieldIDFromRefID +var SceneIDFromRefID = id.SceneIDFromRefID + +type IDSet = id.DatasetIDSet +type SchemaIDSet = id.DatasetSchemaIDSet +type FieldIDSet = id.DatasetSchemaFieldIDSet +type SceneIDSet = id.SceneIDSet + +var NewIDSet = id.NewDatasetIDSet +var NewSchemaIDset = id.NewDatasetSchemaIDSet +var NewFieldIDset = id.NewDatasetSchemaFieldIDSet +var NewSceneIDset = id.NewSceneIDSet + +var ErrInvalidID = id.ErrInvalidID diff --git a/pkg/dataset/list.go b/pkg/dataset/list.go index e22e8957..7675c6a3 100644 --- a/pkg/dataset/list.go +++ b/pkg/dataset/list.go @@ -1,9 +1,5 @@ package dataset -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type List []*Dataset func (l List) First() *Dataset { @@ -20,7 +16,7 @@ func (l List) Last() *Dataset { return l[len(l)-1] } -func (l List) FindDataset(id id.DatasetID) *Dataset { +func (l List) FindDataset(id ID) *Dataset { for _, t := range l { if t.ID() == id { return t @@ -29,12 +25,12 @@ func (l List) FindDataset(id id.DatasetID) *Dataset { return nil } -func (l List) ToDatasetIds() []id.DatasetID { +func (l List) ToDatasetIds() []ID { if l == nil { return nil } - ids := []id.DatasetID{} + ids := []ID{} for _, t := range l { ids = append(ids, t.ID()) } @@ -50,7 +46,7 @@ func (l List) FindDatasetBySource(s string) *Dataset { return nil } -func (l List) FilterByDatasetSchema(s id.DatasetSchemaID) List { +func (l List) FilterByDatasetSchema(s SchemaID) List { n := List{} for _, t := range l { if t.Schema() == s { @@ -65,7 +61,7 @@ func (l List) DiffBySource(l2 List) Diff { added := []*Dataset{} removed := []*Dataset{} // others := map[string]DatasetDiffTouple{} - others2 := map[id.DatasetID]*Dataset{} + others2 := map[ID]*Dataset{} s1 := map[string]*Dataset{} for _, d1 := range l { @@ -119,14 +115,14 @@ func (l List) GraphLoader() GraphLoader { return GraphLoaderFromMap(l.Map()) } -type Map map[id.DatasetID]*Dataset +type Map map[ID]*Dataset func (dm Map) Add(dss ...*Dataset) { if dss == nil { return } if dm == nil { - dm = map[id.DatasetID]*Dataset{} + dm = map[ID]*Dataset{} } for _, ds := range dss { if ds == nil { @@ -147,7 +143,7 @@ func (dm Map) Slice() List { return res } -func (dm Map) GraphSearchByFields(root id.DatasetID, fields ...id.DatasetSchemaFieldID) (List, *Field) { +func (dm Map) GraphSearchByFields(root ID, fields ...FieldID) (List, *Field) { res := make(List, 0, len(fields)) currentD := dm[root] if currentD == nil { @@ -165,8 +161,8 @@ func (dm Map) GraphSearchByFields(root id.DatasetID, fields ...id.DatasetSchemaF if len(fields)-1 == i { return res, field } else if fids := field.Value().ValueRef(); fids != nil { - if fid, err := id.DatasetIDFrom(*fids); err == nil { - currentD = dm[id.DatasetID(fid)] + if fid, err := IDFrom(*fids); err == nil { + currentD = dm[ID(fid)] } else { return res, nil } diff --git a/pkg/dataset/list_test.go b/pkg/dataset/list_test.go index 4dfcccbf..f98cd3c2 100644 --- a/pkg/dataset/list_test.go +++ b/pkg/dataset/list_test.go @@ -3,12 +3,11 @@ package dataset import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestDatasetListDiff(t *testing.T) { - sid := id.SceneID(id.New()) + sid := NewSceneID() source1 := "hogehoge/1" source2 := "hogehoge/2" source3 := "hogehoge/3" @@ -24,7 +23,7 @@ func TestDatasetListDiff(t *testing.T) { expected := Diff{ Added: []*Dataset{d4}, Removed: []*Dataset{d1}, - Others: map[id.DatasetID]*Dataset{ + Others: map[ID]*Dataset{ d2.ID(): d3, }, } @@ -36,7 +35,7 @@ func TestDatasetListDiff(t *testing.T) { expected = Diff{ Added: []*Dataset{d4}, Removed: []*Dataset{d1, d2}, - Others: map[id.DatasetID]*Dataset{ + Others: map[ID]*Dataset{ d5.ID(): d3, }, } @@ -44,13 +43,13 @@ func TestDatasetListDiff(t *testing.T) { } func TestDatasetMapGraphSearchByFields(t *testing.T) { - did1 := id.NewDatasetID() - did2 := id.NewDatasetID() - did3 := id.NewDatasetID() - fid1 := id.NewDatasetSchemaFieldID() - fid2 := id.NewDatasetSchemaFieldID() - fid3 := id.NewDatasetSchemaFieldID() - sid := id.NewSceneID() + did1 := NewID() + did2 := NewID() + did3 := NewID() + fid1 := NewFieldID() + fid2 := NewFieldID() + fid3 := NewFieldID() + sid := NewSceneID() v1 := ValueTypeRef.ValueFrom(did2.ID()) v2 := ValueTypeRef.ValueFrom(did3.ID()) v3 := ValueTypeString.ValueFrom("value") diff --git a/pkg/dataset/loader.go b/pkg/dataset/loader.go index 5092aa34..4e20a045 100644 --- a/pkg/dataset/loader.go +++ b/pkg/dataset/loader.go @@ -2,14 +2,12 @@ package dataset import ( "context" - - "github.com/reearth/reearth-backend/pkg/id" ) -type Loader func(context.Context, ...id.DatasetID) (List, error) +type Loader func(context.Context, ...ID) (List, error) func LoaderFrom(data []*Dataset) Loader { - return func(ctx context.Context, ids ...id.DatasetID) (List, error) { + return func(ctx context.Context, ids ...ID) (List, error) { res := make(List, 0, len(ids)) for _, i := range ids { found := false @@ -28,8 +26,8 @@ func LoaderFrom(data []*Dataset) Loader { } } -func LoaderFromMap(data map[id.DatasetID]*Dataset) Loader { - return func(ctx context.Context, ids ...id.DatasetID) (List, error) { +func LoaderFromMap(data map[ID]*Dataset) Loader { + return func(ctx context.Context, ids ...ID) (List, error) { res := make(List, 0, len(ids)) for _, i := range ids { if d, ok := data[i]; ok { diff --git a/pkg/dataset/schema.go b/pkg/dataset/schema.go index ae3bf22a..b6d01b1f 100644 --- a/pkg/dataset/schema.go +++ b/pkg/dataset/schema.go @@ -1,33 +1,31 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - type Schema struct { - id id.DatasetSchemaID + id SchemaID source string name string - fields map[id.DatasetSchemaFieldID]*SchemaField - order []id.DatasetSchemaFieldID - representativeField *id.DatasetSchemaFieldID - scene id.SceneID + fields map[FieldID]*SchemaField + order []FieldID + representativeField *FieldID + scene SceneID dynamic bool } -func (d *Schema) ID() (i id.DatasetSchemaID) { +func (d *Schema) ID() (i SchemaID) { if d == nil { return } return d.id } -func (d *Schema) IDRef() *id.DatasetSchemaID { +func (d *Schema) IDRef() *SchemaID { if d == nil { return nil } return d.id.Ref() } -func (d *Schema) Scene() (i id.SceneID) { +func (d *Schema) Scene() (i SceneID) { if d == nil { return } @@ -48,7 +46,7 @@ func (d *Schema) Name() string { return d.name } -func (d *Schema) RepresentativeFieldID() *id.DatasetSchemaFieldID { +func (d *Schema) RepresentativeFieldID() *FieldID { if d == nil { return nil } @@ -73,14 +71,14 @@ func (d *Schema) Fields() []*SchemaField { return fields } -func (d *Schema) Field(id id.DatasetSchemaFieldID) *SchemaField { +func (d *Schema) Field(id FieldID) *SchemaField { if d == nil { return nil } return d.fields[id] } -func (d *Schema) FieldRef(id *id.DatasetSchemaFieldID) *SchemaField { +func (d *Schema) FieldRef(id *FieldID) *SchemaField { if d == nil || id == nil { return nil } @@ -111,12 +109,10 @@ func (d *Schema) FieldByType(t ValueType) *SchemaField { return nil } -// Dynamic _ func (d *Schema) Dynamic() bool { return d.dynamic } -// Rename _ func (u *Schema) Rename(name string) { u.name = name } diff --git a/pkg/dataset/schema_builder.go b/pkg/dataset/schema_builder.go index 675b2c80..2b4d138c 100644 --- a/pkg/dataset/schema_builder.go +++ b/pkg/dataset/schema_builder.go @@ -1,9 +1,5 @@ package dataset -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type SchemaBuilder struct { d *Schema } @@ -13,12 +9,12 @@ func NewSchema() *SchemaBuilder { } func (b *SchemaBuilder) Build() (*Schema, error) { - if id.ID(b.d.id).IsNil() { - return nil, id.ErrInvalidID + if b.d.id.IsNil() { + return nil, ErrInvalidID } if b.d.fields == nil || b.d.order == nil { - b.d.fields = map[id.DatasetSchemaFieldID]*SchemaField{} - b.d.order = []id.DatasetSchemaFieldID{} + b.d.fields = map[FieldID]*SchemaField{} + b.d.order = []FieldID{} } return b.d, nil } @@ -31,17 +27,17 @@ func (b *SchemaBuilder) MustBuild() *Schema { return r } -func (b *SchemaBuilder) ID(id id.DatasetSchemaID) *SchemaBuilder { +func (b *SchemaBuilder) ID(id SchemaID) *SchemaBuilder { b.d.id = id return b } func (b *SchemaBuilder) NewID() *SchemaBuilder { - b.d.id = id.DatasetSchemaID(id.New()) + b.d.id = NewSchemaID() return b } -func (b *SchemaBuilder) Scene(scene id.SceneID) *SchemaBuilder { +func (b *SchemaBuilder) Scene(scene SceneID) *SchemaBuilder { b.d.scene = scene return b } @@ -61,15 +57,15 @@ func (b *SchemaBuilder) Source(source string) *SchemaBuilder { return b } -func (b *SchemaBuilder) RepresentativeField(representativeField id.DatasetSchemaFieldID) *SchemaBuilder { +func (b *SchemaBuilder) RepresentativeField(representativeField FieldID) *SchemaBuilder { rf := representativeField b.d.representativeField = &rf return b } func (b *SchemaBuilder) Fields(fields []*SchemaField) *SchemaBuilder { - b.d.fields = map[id.DatasetSchemaFieldID]*SchemaField{} - b.d.order = make([]id.DatasetSchemaFieldID, 0, len(fields)) + b.d.fields = map[FieldID]*SchemaField{} + b.d.order = make([]FieldID, 0, len(fields)) sources := map[string]struct{}{} for _, f := range fields { diff --git a/pkg/dataset/schema_field.go b/pkg/dataset/schema_field.go index 538dce7f..6c0856af 100644 --- a/pkg/dataset/schema_field.go +++ b/pkg/dataset/schema_field.go @@ -1,23 +1,21 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - type SchemaField struct { - id id.DatasetSchemaFieldID + id FieldID name string dataType ValueType source string - ref *id.DatasetSchemaID + ref *SchemaID } -func (d *SchemaField) ID() (i id.DatasetSchemaFieldID) { +func (d *SchemaField) ID() (i FieldID) { if d == nil { return } return d.id } -func (d *SchemaField) IDRef() *id.DatasetSchemaFieldID { +func (d *SchemaField) IDRef() *FieldID { if d == nil { return nil } @@ -31,7 +29,7 @@ func (d *SchemaField) Name() (n string) { return d.name } -func (d *SchemaField) Ref() *id.DatasetSchemaID { +func (d *SchemaField) Ref() *SchemaID { if d == nil { return nil } diff --git a/pkg/dataset/schema_field_builder.go b/pkg/dataset/schema_field_builder.go index b6db538b..b51abd76 100644 --- a/pkg/dataset/schema_field_builder.go +++ b/pkg/dataset/schema_field_builder.go @@ -2,8 +2,6 @@ package dataset import ( "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) type SchemaFieldBuilder struct { @@ -15,8 +13,8 @@ func NewSchemaField() *SchemaFieldBuilder { } func (b *SchemaFieldBuilder) Build() (*SchemaField, error) { - if id.ID(b.d.id).IsNil() { - return nil, id.ErrInvalidID + if b.d.id.IsNil() { + return nil, ErrInvalidID } if !b.d.dataType.Default() { return nil, errors.New("invalid value type") @@ -32,13 +30,13 @@ func (b *SchemaFieldBuilder) MustBuild() *SchemaField { return r } -func (b *SchemaFieldBuilder) ID(id id.DatasetSchemaFieldID) *SchemaFieldBuilder { +func (b *SchemaFieldBuilder) ID(id FieldID) *SchemaFieldBuilder { b.d.id = id return b } func (b *SchemaFieldBuilder) NewID() *SchemaFieldBuilder { - b.d.id = id.DatasetSchemaFieldID(id.New()) + b.d.id = NewFieldID() return b } @@ -57,7 +55,7 @@ func (b *SchemaFieldBuilder) Source(source string) *SchemaFieldBuilder { return b } -func (b *SchemaFieldBuilder) Ref(ref *id.DatasetSchemaID) *SchemaFieldBuilder { +func (b *SchemaFieldBuilder) Ref(ref *SchemaID) *SchemaFieldBuilder { if ref == nil { b.d.ref = nil } else { diff --git a/pkg/dataset/schema_field_diff.go b/pkg/dataset/schema_field_diff.go index a58b206a..1bcace8a 100644 --- a/pkg/dataset/schema_field_diff.go +++ b/pkg/dataset/schema_field_diff.go @@ -1,18 +1,16 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - type SchemaFieldDiff struct { Added []*SchemaField Removed []*SchemaField - Replaced map[id.DatasetSchemaFieldID]*SchemaField + Replaced map[FieldID]*SchemaField } func (d *Schema) FieldDiffBySource(d2 *Schema) SchemaFieldDiff { added := []*SchemaField{} removed := []*SchemaField{} // others := map[string]DatasetDiffTouple{} - others2 := map[id.DatasetSchemaFieldID]*SchemaField{} + others2 := map[FieldID]*SchemaField{} s1 := map[string]*SchemaField{} for _, d1 := range d.fields { diff --git a/pkg/dataset/schema_graph_iterator.go b/pkg/dataset/schema_graph_iterator.go index 8c5e7e15..59b4a765 100644 --- a/pkg/dataset/schema_graph_iterator.go +++ b/pkg/dataset/schema_graph_iterator.go @@ -1,31 +1,27 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - // SchemaGraphIterator は、データセットをグラフ探索するためのイテレータです。 type SchemaGraphIterator struct { m SchemaMap - ids [][]id.DatasetSchemaID + ids [][]SchemaID currentIndex int currentDepthIndex int maxDepth int } -// SchemaGraphIteratorFrom _ -func SchemaGraphIteratorFrom(root id.DatasetSchemaID, depth int) *SchemaGraphIterator { +func SchemaGraphIteratorFrom(root SchemaID, depth int) *SchemaGraphIterator { return &SchemaGraphIterator{ - ids: [][]id.DatasetSchemaID{{root}}, + ids: [][]SchemaID{{root}}, maxDepth: depth, } } -// Next _ -func (di *SchemaGraphIterator) Next(d *Schema) (id.DatasetSchemaID, bool) { +func (di *SchemaGraphIterator) Next(d *Schema) (SchemaID, bool) { if di == nil || di.maxDepth == 0 || di.ids == nil || len(di.ids) == 0 || d == nil { - return id.DatasetSchemaID{}, false + return SchemaID{}, false } if di.currentDepthIndex >= len(di.ids) { - return id.DatasetSchemaID{}, true + return SchemaID{}, true } if di.m == nil { @@ -35,7 +31,7 @@ func (di *SchemaGraphIterator) Next(d *Schema) (id.DatasetSchemaID, bool) { // add fields if len(di.ids) <= di.currentDepthIndex+1 { - di.ids = append(di.ids, []id.DatasetSchemaID{}) + di.ids = append(di.ids, []SchemaID{}) } nextDepthIDs := di.ids[di.currentDepthIndex+1] currentIDs := di.ids[di.currentDepthIndex] @@ -53,7 +49,7 @@ func (di *SchemaGraphIterator) Next(d *Schema) (id.DatasetSchemaID, bool) { if di.maxDepth <= di.currentDepthIndex || len(nextDepthIDs) == 0 { // done di.currentDepthIndex++ - return id.DatasetSchemaID{}, true + return SchemaID{}, true } di.currentDepthIndex++ } else { @@ -63,7 +59,6 @@ func (di *SchemaGraphIterator) Next(d *Schema) (id.DatasetSchemaID, bool) { return di.ids[di.currentDepthIndex][di.currentIndex], false } -// Result _ func (di *SchemaGraphIterator) Result() SchemaMap { if di == nil { return nil diff --git a/pkg/dataset/schema_graph_iterator_test.go b/pkg/dataset/schema_graph_iterator_test.go index fef53de1..c7f556bc 100644 --- a/pkg/dataset/schema_graph_iterator_test.go +++ b/pkg/dataset/schema_graph_iterator_test.go @@ -3,27 +3,26 @@ package dataset import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestDatasetSchemaGraphIterator(t *testing.T) { - sid := id.NewSceneID() - d0id := id.NewDatasetSchemaID() - d11id := id.NewDatasetSchemaID() - d12id := id.NewDatasetSchemaID() - d21id := id.NewDatasetSchemaID() - d31id := id.NewDatasetSchemaID() - d32id := id.NewDatasetSchemaID() + sid := NewSceneID() + d0id := NewSchemaID() + d11id := NewSchemaID() + d12id := NewSchemaID() + d21id := NewSchemaID() + d31id := NewSchemaID() + d32id := NewSchemaID() - d0f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeRef).Ref(&d11id).Build() - d0f1, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeRef).Ref(&d12id).Build() - d11f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeString).Build() - d12f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeRef).Ref(&d21id).Build() - d21f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeRef).Ref(&d31id).Build() - d21f1, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeRef).Ref(&d32id).Build() - d31f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeString).Build() - d32f0, _ := NewSchemaField().ID(id.NewDatasetSchemaFieldID()).Type(ValueTypeString).Build() + d0f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeRef).Ref(&d11id).Build() + d0f1, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeRef).Ref(&d12id).Build() + d11f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeString).Build() + d12f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeRef).Ref(&d21id).Build() + d21f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeRef).Ref(&d31id).Build() + d21f1, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeRef).Ref(&d32id).Build() + d31f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeString).Build() + d32f0, _ := NewSchemaField().ID(NewFieldID()).Type(ValueTypeString).Build() d0, _ := NewSchema().ID(d0id).Scene(sid).Fields([]*SchemaField{ d0f0, d0f1, diff --git a/pkg/dataset/schema_list.go b/pkg/dataset/schema_list.go index 6e55b026..f9041298 100644 --- a/pkg/dataset/schema_list.go +++ b/pkg/dataset/schema_list.go @@ -1,11 +1,7 @@ package dataset -import "github.com/reearth/reearth-backend/pkg/id" - -// SchemaList _ type SchemaList []*Schema -// Map _ func (dsl SchemaList) Map() SchemaMap { if dsl == nil { return nil @@ -19,10 +15,8 @@ func (dsl SchemaList) Map() SchemaMap { return m } -// SchemaMap _ -type SchemaMap map[id.DatasetSchemaID]*Schema +type SchemaMap map[SchemaID]*Schema -// Slice _ func (dsm SchemaMap) Slice() SchemaList { if dsm == nil { return nil @@ -36,8 +30,7 @@ func (dsm SchemaMap) Slice() SchemaList { return res } -// GraphSearchByFields _ -func (dsm SchemaMap) GraphSearchByFields(root id.DatasetSchemaID, fields ...id.DatasetSchemaFieldID) (SchemaList, *SchemaField) { +func (dsm SchemaMap) GraphSearchByFields(root SchemaID, fields ...FieldID) (SchemaList, *SchemaField) { res := make(SchemaList, 0, len(fields)) currentDs := dsm[root] if currentDs == nil { diff --git a/pkg/dataset/schema_list_test.go b/pkg/dataset/schema_list_test.go index c9f17451..267c4b32 100644 --- a/pkg/dataset/schema_list_test.go +++ b/pkg/dataset/schema_list_test.go @@ -3,18 +3,17 @@ package dataset import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestDatasetSchemaMapGraphSearchByFields(t *testing.T) { - did1 := id.NewDatasetSchemaID() - did2 := id.NewDatasetSchemaID() - did3 := id.NewDatasetSchemaID() - fid1 := id.NewDatasetSchemaFieldID() - fid2 := id.NewDatasetSchemaFieldID() - fid3 := id.NewDatasetSchemaFieldID() - sid := id.NewSceneID() + did1 := NewSchemaID() + did2 := NewSchemaID() + did3 := NewSchemaID() + fid1 := NewFieldID() + fid2 := NewFieldID() + fid3 := NewFieldID() + sid := NewSceneID() f1, _ := NewSchemaField().ID(fid1).Type(ValueTypeString).Ref(&did2).Build() f2, _ := NewSchemaField().ID(fid2).Type(ValueTypeString).Ref(&did3).Build() f3, _ := NewSchemaField().ID(fid3).Type(ValueTypeString).Build() diff --git a/pkg/layer/builder.go b/pkg/layer/builder.go index 0eadb525..651d378b 100644 --- a/pkg/layer/builder.go +++ b/pkg/layer/builder.go @@ -1,9 +1,5 @@ package layer -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type Builder struct { base layerBase } @@ -20,17 +16,17 @@ func (b *Builder) Item() *ItemBuilder { return NewItem().base(b.base) } -func (b *Builder) ID(id id.LayerID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.base.id = id return b } func (b *Builder) NewID() *Builder { - b.base.id = id.NewLayerID() + b.base.id = NewID() return b } -func (b *Builder) Scene(s id.SceneID) *Builder { +func (b *Builder) Scene(s SceneID) *Builder { b.base.scene = s return b } @@ -52,17 +48,17 @@ func (b *Builder) IsVisibleRef(visible *bool) *Builder { return b } -func (b *Builder) Plugin(plugin *id.PluginID) *Builder { +func (b *Builder) Plugin(plugin *PluginID) *Builder { b.base.plugin = plugin.CopyRef() return b } -func (b *Builder) Extension(extension *id.PluginExtensionID) *Builder { +func (b *Builder) Extension(extension *PluginExtensionID) *Builder { b.base.extension = extension.CopyRef() return b } -func (b *Builder) Property(p *id.PropertyID) *Builder { +func (b *Builder) Property(p *PropertyID) *Builder { b.base.property = p.CopyRef() return b } diff --git a/pkg/layer/decoding/common.go b/pkg/layer/decoding/common.go index acae2d58..10d27579 100644 --- a/pkg/layer/decoding/common.go +++ b/pkg/layer/decoding/common.go @@ -7,8 +7,8 @@ import ( "github.com/reearth/reearth-backend/pkg/builtin" "github.com/reearth/reearth-backend/pkg/czml" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/kml" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) @@ -18,21 +18,21 @@ var ( ) var ( - extensions = map[string]id.PluginExtensionID{ - "Point": id.PluginExtensionID("marker"), - "Polygon": id.PluginExtensionID("polygon"), - "Polyline": id.PluginExtensionID("polyline"), + extensions = map[string]layer.PluginExtensionID{ + "Point": layer.PluginExtensionID("marker"), + "Polygon": layer.PluginExtensionID("polygon"), + "Polyline": layer.PluginExtensionID("polyline"), } - propertySchemas = map[string]id.PropertySchemaID{ - "Point": id.MustPropertySchemaID("reearth/marker"), - "Polygon": id.MustPropertySchemaID("reearth/polygon"), - "Polyline": id.MustPropertySchemaID("reearth/polyline"), + propertySchemas = map[string]property.SchemaID{ + "Point": property.MustSchemaID("reearth/marker"), + "Polygon": property.MustSchemaID("reearth/polygon"), + "Polyline": property.MustSchemaID("reearth/polyline"), } - propertyItems = id.PropertySchemaGroupID("default") - propertyFields = map[string]id.PropertySchemaFieldID{ - "Point": id.PropertySchemaFieldID("location"), - "Polygon": id.PropertySchemaFieldID("polygon"), - "Polyline": id.PropertySchemaFieldID("coordinates"), + propertyItems = property.SchemaGroupID("default") + propertyFields = map[string]property.FieldID{ + "Point": property.FieldID("location"), + "Polygon": property.FieldID("polygon"), + "Polyline": property.FieldID("coordinates"), } ) @@ -74,7 +74,7 @@ func rgbafToHex(rgbaf []float64) (string, error) { return rgbaToHex(rgba) } -func MustCreateProperty(t string, v interface{}, sceneID id.SceneID, styleItem interface{}, extension string) *property.Property { +func MustCreateProperty(t string, v interface{}, sceneID layer.SceneID, styleItem interface{}, extension string) *property.Property { p, err := createProperty(t, v, sceneID, styleItem, extension) if err != nil { panic(err) @@ -82,7 +82,7 @@ func MustCreateProperty(t string, v interface{}, sceneID id.SceneID, styleItem i return p } -func createProperty(t string, v interface{}, sceneID id.SceneID, styleItem interface{}, extension string) (*property.Property, error) { +func createProperty(t string, v interface{}, sceneID layer.SceneID, styleItem interface{}, extension string) (*property.Property, error) { propertySchema := propertySchemas[t] item := propertyItems field := propertyFields[t] diff --git a/pkg/layer/decoding/czml.go b/pkg/layer/decoding/czml.go index b17f266b..ed6a43c3 100644 --- a/pkg/layer/decoding/czml.go +++ b/pkg/layer/decoding/czml.go @@ -5,18 +5,17 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/czml" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) type CZMLDecoder struct { decoder *json.Decoder - sceneId id.SceneID + sceneId layer.SceneID groupName string } -func NewCZMLDecoder(d *json.Decoder, s id.SceneID) *CZMLDecoder { +func NewCZMLDecoder(d *json.Decoder, s layer.SceneID) *CZMLDecoder { return &CZMLDecoder{ decoder: d, sceneId: s, @@ -76,7 +75,7 @@ func (d *CZMLDecoder) Decode() (Result, error) { func (d *CZMLDecoder) decodeLayer(t string, coords []float64, style interface{}, layerName string) (*layer.Item, *property.Property, error) { var p *property.Property var l *layer.Item - var ex id.PluginExtensionID + var ex layer.PluginExtensionID var err error switch t { case "Point": @@ -164,7 +163,7 @@ func (d *CZMLDecoder) decodeLayer(t string, coords []float64, style interface{}, Scene(d.sceneId). Property(p.IDRef()). Extension(&ex). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). Build() if err != nil { return nil, nil, err diff --git a/pkg/layer/decoding/czml_test.go b/pkg/layer/decoding/czml_test.go index ed4a4972..e23b8665 100644 --- a/pkg/layer/decoding/czml_test.go +++ b/pkg/layer/decoding/czml_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" ) @@ -86,7 +86,7 @@ const ( func TestCZMLDecoder_Decode(t *testing.T) { r := strings.NewReader(czmlmock) d := json.NewDecoder(r) - s := id.NewSceneID() + s := layer.NewSceneID() p := NewCZMLDecoder(d, s) result, err := p.Decode() assert.NoError(t, err) diff --git a/pkg/layer/decoding/decoder.go b/pkg/layer/decoding/decoder.go index 641e3baa..3467be35 100644 --- a/pkg/layer/decoding/decoder.go +++ b/pkg/layer/decoding/decoder.go @@ -3,7 +3,6 @@ package decoding import ( "fmt" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) @@ -51,7 +50,7 @@ func (r Result) Validate() error { func resultFrom(lg *layer.Group, layers layer.Map, properties property.Map) (r Result, err error) { r = Result{ - Root: layer.NewIDList([]id.LayerID{lg.ID()}), + Root: layer.NewIDList([]layer.ID{lg.ID()}), Layers: layers.Add(lg.LayerRef()), Properties: properties, } diff --git a/pkg/layer/decoding/geojson.go b/pkg/layer/decoding/geojson.go index b21ef8ba..ab4516b7 100644 --- a/pkg/layer/decoding/geojson.go +++ b/pkg/layer/decoding/geojson.go @@ -6,7 +6,6 @@ import ( "io" geojson "github.com/paulmach/go.geojson" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) @@ -19,11 +18,11 @@ type GeoStyle struct { type GeoJSONDecoder struct { reader io.Reader features []*geojson.Feature - sceneId id.SceneID + sceneId layer.SceneID groupName string } -func NewGeoJSONDecoder(r io.Reader, s id.SceneID) *GeoJSONDecoder { +func NewGeoJSONDecoder(r io.Reader, s layer.SceneID) *GeoJSONDecoder { return &GeoJSONDecoder{ reader: r, sceneId: s, @@ -109,7 +108,7 @@ func (d *GeoJSONDecoder) decodeLayer() (*layer.Item, *property.Property, error) var feat *geojson.Feature var p *property.Property var l *layer.Item - var ex id.PluginExtensionID + var ex layer.PluginExtensionID var err error var stroke, fillColor string var strokeWidth float64 @@ -242,7 +241,7 @@ func (d *GeoJSONDecoder) decodeLayer() (*layer.Item, *property.Property, error) Scene(d.sceneId). Property(p.IDRef()). Extension(&ex). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). Build() if err != nil { return nil, nil, err diff --git a/pkg/layer/decoding/geojson_test.go b/pkg/layer/decoding/geojson_test.go index d1fd13c6..4f63e6de 100644 --- a/pkg/layer/decoding/geojson_test.go +++ b/pkg/layer/decoding/geojson_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" ) @@ -159,7 +159,7 @@ const geojsonmock = `{ func TestGeoJSONDecoder_Decode(t *testing.T) { r := strings.NewReader(geojsonmock) - s := id.NewSceneID() + s := layer.NewSceneID() p := NewGeoJSONDecoder(r, s) result, err := p.Decode() assert.NoError(t, err) diff --git a/pkg/layer/decoding/kml.go b/pkg/layer/decoding/kml.go index 07f701d8..b09a1960 100644 --- a/pkg/layer/decoding/kml.go +++ b/pkg/layer/decoding/kml.go @@ -8,7 +8,6 @@ import ( "strconv" "strings" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/kml" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" @@ -16,11 +15,11 @@ import ( type KMLDecoder struct { decoder *xml.Decoder - sceneId id.SceneID + sceneId layer.SceneID styles map[string]kml.Style } -func NewKMLDecoder(d *xml.Decoder, s id.SceneID) *KMLDecoder { +func NewKMLDecoder(d *xml.Decoder, s layer.SceneID) *KMLDecoder { return &KMLDecoder{ decoder: d, sceneId: s, @@ -177,7 +176,7 @@ func (d *KMLDecoder) decodeCollection(c kml.Collection, depth int) (*layer.Group func (d *KMLDecoder) decodePlacemark(p kml.Placemark) (*layer.Item, *property.Property, error) { var layerItem *layer.Item var prop *property.Property - var ex id.PluginExtensionID + var ex layer.PluginExtensionID var styleId string var layerName string @@ -243,7 +242,7 @@ func (d *KMLDecoder) decodePlacemark(p kml.Placemark) (*layer.Item, *property.Pr Scene(d.sceneId). Property(prop.IDRef()). Extension(&ex). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). Build() if err != nil { return nil, nil, err diff --git a/pkg/layer/decoding/kml_test.go b/pkg/layer/decoding/kml_test.go index 62be12af..781dd0d4 100644 --- a/pkg/layer/decoding/kml_test.go +++ b/pkg/layer/decoding/kml_test.go @@ -11,8 +11,6 @@ import ( "github.com/reearth/reearth-backend/pkg/builtin" "github.com/reearth/reearth-backend/pkg/kml" "github.com/reearth/reearth-backend/pkg/layer" - - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" ) @@ -83,14 +81,14 @@ const kmlmock = ` ` func TestNewKMLDecoder(t *testing.T) { - d := NewKMLDecoder(xml.NewDecoder(strings.NewReader(``)), id.NewSceneID()) + d := NewKMLDecoder(xml.NewDecoder(strings.NewReader(``)), layer.NewSceneID()) assert.NotNil(t, d) } func TestKMLDecoder_Decode(t *testing.T) { r := strings.NewReader(kmlmock) d := xml.NewDecoder(r) - s := id.NewSceneID() + s := layer.NewSceneID() k := NewKMLDecoder(d, s) result, err := k.Decode() @@ -120,7 +118,7 @@ func TestKMLDecoder_Decode(t *testing.T) { fImage, _, _ := prop.Field(property.PointFieldBySchemaGroup(propertyItems, "image")) actUrl, _ := url.Parse("http://maps.google.com/mapfiles/kml/pal3/icon19.png") assert.Equal(t, actUrl, fImage.Value().Value()) - fh, _, _ := prop.Field(property.PointFieldBySchemaGroup(propertyItems, id.PropertySchemaFieldID("height"))) + fh, _, _ := prop.Field(property.PointFieldBySchemaGroup(propertyItems, property.FieldID("height"))) assert.Equal(t, 43.0, fh.Value().Value()) // Polygon test @@ -397,7 +395,7 @@ func TestKMLDecoder_Decode(t *testing.T) { //} // func TestKMLparseKML(t *testing.T) { - s := id.NewSceneID() + s := layer.NewSceneID() testCases := []struct { name, KMLstr string @@ -489,7 +487,7 @@ func TestKMLparseKML(t *testing.T) { } } func TestKMLdecodePlacemark(t *testing.T) { - s := id.NewSceneID() + s := layer.NewSceneID() point := MustCreateProperty("Point", property.LatLngHeight{ Lat: 23, Lng: 40, @@ -554,7 +552,7 @@ func TestKMLdecodePlacemark(t *testing.T) { Scene(s). Property(point.IDRef()). Extension(&pointExt). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). MustBuild(), expectedProperty: point, err: nil, @@ -578,7 +576,7 @@ func TestKMLdecodePlacemark(t *testing.T) { Scene(s). Property(polyline.IDRef()). Extension(&polylineExt). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). MustBuild(), expectedProperty: polyline, err: nil, @@ -609,7 +607,7 @@ func TestKMLdecodePlacemark(t *testing.T) { Scene(s). Property(polygon.IDRef()). Extension(&polygonExt). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). MustBuild(), expectedProperty: polygon, err: nil, @@ -630,7 +628,7 @@ func TestKMLdecodePlacemark(t *testing.T) { Name("Point"). Scene(s). Extension(&pointExt). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). MustBuild(), expectedProperty: nil, err: nil, @@ -660,7 +658,7 @@ func TestKMLdecodePlacemark(t *testing.T) { // @todo not finished yet //func TestKMLdecodeCollection(t *testing.T) { // // @todo err and style cases -// s := id.NewSceneID() +// s := layer.NewSceneID() // pointExt := extensions["Point"] // point := MustCreateProperty("Point", property.LatLngHeight{ // Lat: 39, @@ -674,7 +672,7 @@ func TestKMLdecodePlacemark(t *testing.T) { // Scene(s). // Property(point.IDRef()). // Extension(&pointExt). -// Plugin(&id.OfficialPluginID). +// Plugin(&layer.OfficialPluginID). // MustBuild() // var ll layer.Layer = li // testCases := []struct { diff --git a/pkg/layer/decoding/reearth.go b/pkg/layer/decoding/reearth.go index 361b0bcd..a365b4c2 100644 --- a/pkg/layer/decoding/reearth.go +++ b/pkg/layer/decoding/reearth.go @@ -5,17 +5,16 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/builtin" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) type ReearthDecoder struct { d *json.Decoder - scene id.SceneID + scene layer.SceneID } -func NewReearthDecoder(d *json.Decoder, scene id.SceneID) *ReearthDecoder { +func NewReearthDecoder(d *json.Decoder, scene layer.SceneID) *ReearthDecoder { return &ReearthDecoder{d: d, scene: scene} } @@ -43,7 +42,7 @@ type ReearthRoot struct { Layers []*ReearthLayer `json:"layers"` } -func (r *ReearthRoot) Result(scene id.SceneID) (result Result, err error) { +func (r *ReearthRoot) Result(scene layer.SceneID) (result Result, err error) { if r == nil { return } @@ -66,15 +65,15 @@ func (r *ReearthRoot) Result(scene id.SceneID) (result Result, err error) { } type ReearthLayer struct { - Plugin *id.PluginID `json:"plugin"` - Extension *id.PluginExtensionID `json:"extension"` - Name string `json:"name"` - Infobox *ReearthInfobox `json:"infobox"` - Property *ReearthProperty `json:"property"` - Layers []ReearthLayer `json:"layers"` - IsVisible *bool `json:"isVisible"` - LinkedDatasetSchema *id.DatasetSchemaID `json:"linkedDatasetSchema"` - LinkedDataset *id.DatasetID `json:"linkedDataset"` + Plugin *layer.PluginID `json:"plugin"` + Extension *layer.PluginExtensionID `json:"extension"` + Name string `json:"name"` + Infobox *ReearthInfobox `json:"infobox"` + Property *ReearthProperty `json:"property"` + Layers []ReearthLayer `json:"layers"` + IsVisible *bool `json:"isVisible"` + LinkedDatasetSchema *layer.DatasetSchemaID `json:"linkedDatasetSchema"` + LinkedDataset *layer.DatasetID `json:"linkedDataset"` } func (l *ReearthLayer) layer() *layer.Initializer { @@ -92,9 +91,9 @@ func (l *ReearthLayer) layer() *layer.Initializer { } } - var psid *id.PropertySchemaID + var psid *property.SchemaID if l.Plugin != nil || l.Extension != nil { - psid2, err := id.PropertySchemaIDFromExtension(*l.Plugin, *l.Extension) + psid2, err := layer.PropertySchemaIDFromExtension(*l.Plugin, *l.Extension) if err == nil { // if there is an error, property schema id will be nil. psid = psid2.Ref() @@ -151,9 +150,9 @@ func (i *ReearthInfobox) infobox() *layer.InitializerInfobox { } type ReearthInfoboxField struct { - Plugin id.PluginID `json:"plugin"` - Extension id.PluginExtensionID `json:"extension"` - Property *ReearthProperty `json:"property"` + Plugin layer.PluginID `json:"plugin"` + Extension layer.PluginExtensionID `json:"extension"` + Property *ReearthProperty `json:"property"` } func (f *ReearthInfoboxField) infoboxField() *layer.InitializerInfoboxField { @@ -161,9 +160,9 @@ func (f *ReearthInfoboxField) infoboxField() *layer.InitializerInfoboxField { return nil } - var psid *id.PropertySchemaID + var psid *property.SchemaID { - psid2, err := id.PropertySchemaIDFromExtension(f.Plugin, f.Extension) + psid2, err := layer.PropertySchemaIDFromExtension(f.Plugin, f.Extension) if err == nil { // if there is an error, property schema id will be nil. psid = psid2.Ref() @@ -182,9 +181,9 @@ func (f *ReearthInfoboxField) infoboxField() *layer.InitializerInfoboxField { } } -type ReearthProperty map[id.PropertySchemaGroupID]ReearthPropertyItem +type ReearthProperty map[property.SchemaGroupID]ReearthPropertyItem -func (p ReearthProperty) property(schema *id.PropertySchemaID) *property.Initializer { +func (p ReearthProperty) property(schema *property.SchemaID) *property.Initializer { if schema == nil || p == nil { return nil } @@ -206,7 +205,7 @@ type ReearthPropertyItem struct { Fields ReearthPropertyGroup `json:"fields"` } -func (p *ReearthPropertyItem) propertyItem(key id.PropertySchemaGroupID) *property.InitializerItem { +func (p *ReearthPropertyItem) propertyItem(key property.SchemaGroupID) *property.InitializerItem { if p == nil { return nil } @@ -244,7 +243,7 @@ func (p *ReearthPropertyItem) propertyItem(key id.PropertySchemaGroupID) *proper } } -type ReearthPropertyGroup map[id.PropertySchemaFieldID]*ReearthPropertyField +type ReearthPropertyGroup map[property.FieldID]*ReearthPropertyField func (p ReearthPropertyGroup) propertyGroup() *property.InitializerGroup { if p == nil || len(p) == 0 { @@ -270,7 +269,7 @@ type ReearthPropertyField struct { Value interface{} `json:"value"` } -func (f *ReearthPropertyField) propertyField(key id.PropertySchemaFieldID) *property.InitializerField { +func (f *ReearthPropertyField) propertyField(key property.FieldID) *property.InitializerField { if f == nil || f.Type == "" { return nil } @@ -301,7 +300,7 @@ func (f *ReearthPropertyField) propertyField(key id.PropertySchemaFieldID) *prop } type ReearthPropertyLink struct { - Dataset *id.DatasetID `json:"dataset"` - Schema id.DatasetSchemaID `json:"schema"` - Field id.DatasetSchemaFieldID `json:"field"` + Dataset *property.DatasetID `json:"dataset"` + Schema property.DatasetSchemaID `json:"schema"` + Field property.DatasetFieldID `json:"field"` } diff --git a/pkg/layer/decoding/reearth_test.go b/pkg/layer/decoding/reearth_test.go index 29b78151..9179c5c3 100644 --- a/pkg/layer/decoding/reearth_test.go +++ b/pkg/layer/decoding/reearth_test.go @@ -5,7 +5,6 @@ import ( "strings" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" @@ -14,9 +13,9 @@ import ( var _ Decoder = &ReearthDecoder{} func TestReearthDecoder_Decode(t *testing.T) { - sid := id.NewSceneID() - dsid := id.NewDatasetSchemaID() - did := id.NewDatasetID() + sid := layer.NewSceneID() + dsid := layer.NewDatasetSchemaID() + did := layer.NewDatasetID() reearthjson := `{ "reearth": 1, "layers": [ @@ -92,8 +91,8 @@ func TestReearthDecoder_Decode(t *testing.T) { rootLayer := result.Layers.Group(result.Root.LayerAt(0)) assert.Equal(t, (&layer.Initializer{ ID: rootLayer.IDRef(), - Plugin: id.MustPluginID("reearth").Ref(), - Extension: id.PluginExtensionID("marker").Ref(), + Plugin: layer.OfficialPluginID.Ref(), + Extension: layer.PluginExtensionID("marker").Ref(), PropertyID: rootLayer.Property().Ref(), Name: "ABC", Infobox: &layer.InitializerInfobox{ @@ -101,8 +100,8 @@ func TestReearthDecoder_Decode(t *testing.T) { Fields: []*layer.InitializerInfoboxField{ { ID: rootLayer.Infobox().FieldAt(0).ID().Ref(), - Plugin: id.MustPluginID("reearth"), - Extension: id.PluginExtensionID("textblock"), + Plugin: layer.OfficialPluginID, + Extension: layer.PluginExtensionID("textblock"), PropertyID: rootLayer.Infobox().FieldAt(0).Property().Ref(), }, }, @@ -116,8 +115,8 @@ func TestReearthDecoder_Decode(t *testing.T) { secondLayer := result.Layers.Item(rootLayer.Layers().LayerAt(0)) assert.Equal(t, (&layer.Initializer{ ID: secondLayer.IDRef(), - Plugin: id.MustPluginID("reearth").Ref(), - Extension: id.PluginExtensionID("marker").Ref(), + Plugin: layer.OfficialPluginID.Ref(), + Extension: layer.PluginExtensionID("marker").Ref(), PropertyID: secondLayer.Property().Ref(), Name: "abc", IsVisible: &tr, @@ -130,14 +129,14 @@ func TestReearthDecoder_Decode(t *testing.T) { t, (&property.Initializer{ ID: prop.ID().Ref(), - Schema: id.MustPropertySchemaID("reearth/marker"), + Schema: property.MustSchemaID("reearth/marker"), Items: []*property.InitializerItem{ { ID: prop.Items()[0].ID().Ref(), - SchemaItem: id.PropertySchemaGroupID("default"), + SchemaItem: property.SchemaGroupID("default"), Fields: []*property.InitializerField{ { - Field: id.PropertySchemaFieldID("latlng"), + Field: property.FieldID("latlng"), Type: property.ValueTypeLatLng, Value: property.ValueTypeLatLng.ValueFrom(property.LatLng{Lat: 1, Lng: 2}), }, @@ -154,7 +153,7 @@ func TestReearthDecoder_Decode(t *testing.T) { t, (&property.Initializer{ ID: rootLayer.Infobox().PropertyRef(), - Schema: id.MustPropertySchemaID("reearth/infobox"), + Schema: property.MustSchemaID("reearth/infobox"), }).MustBeProperty(sid), prop, ) @@ -165,7 +164,7 @@ func TestReearthDecoder_Decode(t *testing.T) { t, (&property.Initializer{ ID: rootLayer.Infobox().FieldAt(0).PropertyRef(), - Schema: id.MustPropertySchemaID("reearth/textblock"), + Schema: property.MustSchemaID("reearth/textblock"), }).MustBeProperty(sid), prop, ) @@ -176,17 +175,17 @@ func TestReearthDecoder_Decode(t *testing.T) { t, (&property.Initializer{ ID: prop.ID().Ref(), - Schema: id.MustPropertySchemaID("reearth/marker"), + Schema: property.MustSchemaID("reearth/marker"), Items: []*property.InitializerItem{ { ID: prop.Items()[0].ID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + SchemaItem: property.SchemaGroupID("hoge"), Groups: []*property.InitializerGroup{ { ID: property.ToGroupList(prop.Items()[0]).GroupAt(0).IDRef(), Fields: []*property.InitializerField{ { - Field: id.PropertySchemaFieldID("foobar"), + Field: property.FieldID("foobar"), Type: property.ValueTypeString, Value: property.ValueTypeString.ValueFrom("bar"), }, @@ -196,7 +195,7 @@ func TestReearthDecoder_Decode(t *testing.T) { ID: property.ToGroupList(prop.Items()[0]).GroupAt(1).IDRef(), Fields: []*property.InitializerField{ { - Field: id.PropertySchemaFieldID("foobar"), + Field: property.FieldID("foobar"), Type: property.ValueTypeString, Value: property.ValueTypeString.ValueFrom("foo"), }, diff --git a/pkg/layer/decoding/shp.go b/pkg/layer/decoding/shp.go index e808ce82..652fd2e5 100644 --- a/pkg/layer/decoding/shp.go +++ b/pkg/layer/decoding/shp.go @@ -1,7 +1,6 @@ package decoding import ( - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/shp" @@ -14,10 +13,10 @@ type ShapeReader interface { } type ShapeDecoder struct { reader ShapeReader - sceneId id.SceneID + sceneId layer.SceneID } -func NewShapeDecoder(r ShapeReader, s id.SceneID) *ShapeDecoder { +func NewShapeDecoder(r ShapeReader, s layer.SceneID) *ShapeDecoder { return &ShapeDecoder{ reader: r, sceneId: s, @@ -27,7 +26,7 @@ func NewShapeDecoder(r ShapeReader, s id.SceneID) *ShapeDecoder { func (shd *ShapeDecoder) getLayer(t string, coords interface{}) (*layer.Item, *property.Property, error) { var p *property.Property var l *layer.Item - var ex id.PluginExtensionID + var ex layer.PluginExtensionID var err error p, err = createProperty(t, coords, shd.sceneId, nil, "") if err != nil { @@ -40,7 +39,7 @@ func (shd *ShapeDecoder) getLayer(t string, coords interface{}) (*layer.Item, *p Scene(shd.sceneId). Property(p.IDRef()). Extension(&ex). - Plugin(&id.OfficialPluginID). + Plugin(&layer.OfficialPluginID). Build() if err != nil { return nil, nil, err diff --git a/pkg/layer/encoding/czml.go b/pkg/layer/encoding/czml.go index 5f616c97..e7117233 100644 --- a/pkg/layer/encoding/czml.go +++ b/pkg/layer/encoding/czml.go @@ -6,7 +6,7 @@ import ( "io" "github.com/reearth/reearth-backend/pkg/czml" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" ) @@ -29,7 +29,7 @@ func (e *CZMLEncoder) stringToCZMLColor(s string) *czml.Color { } func (e *CZMLEncoder) encodeSingleLayer(li *merging.SealedLayerItem) (*czml.Feature, error) { - if li.PluginID == nil || !id.OfficialPluginID.Equal(*li.PluginID) { + if li.PluginID == nil || !layer.OfficialPluginID.Equal(*li.PluginID) { return nil, nil } diff --git a/pkg/layer/encoding/czml_test.go b/pkg/layer/encoding/czml_test.go index 805d7ab7..17edc3a7 100644 --- a/pkg/layer/encoding/czml_test.go +++ b/pkg/layer/encoding/czml_test.go @@ -6,8 +6,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/czml" - - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" @@ -17,9 +15,9 @@ import ( var _ Encoder = (*CZMLEncoder)(nil) func TestCZMLEncoder_Encode(t *testing.T) { - lid := id.NewLayerID() - sid := id.NewSceneID() - iid := id.NewPropertyItemID() + lid := layer.NewID() + sid := layer.NewSceneID() + iid := property.NewItemID() tests := []struct { name string @@ -34,18 +32,18 @@ func TestCZMLEncoder_Encode(t *testing.T) { Original: lid, Name: "test", Scene: sid, - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("marker").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("marker").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { Original: &iid, - SchemaGroup: id.PropertySchemaGroupID("default"), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("location"), + ID: property.FieldID("location"), Val: property.NewValueAndDatasetValue( property.ValueTypeLatLng, nil, @@ -53,7 +51,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("height"), + ID: property.FieldID("height"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -61,7 +59,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("pointColor"), + ID: property.FieldID("pointColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -69,7 +67,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("pointSize"), + ID: property.FieldID("pointSize"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -102,18 +100,18 @@ func TestCZMLEncoder_Encode(t *testing.T) { Original: lid, Name: "test", Scene: sid, - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polygon").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polygon").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { Original: &iid, - SchemaGroup: id.PropertySchemaGroupID("default"), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("polygon"), + ID: property.FieldID("polygon"), Val: property.NewValueAndDatasetValue( property.ValueTypePolygon, nil, @@ -127,7 +125,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("fill"), + ID: property.FieldID("fill"), Val: property.NewValueAndDatasetValue( property.ValueTypeBool, nil, @@ -135,7 +133,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("fillColor"), + ID: property.FieldID("fillColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -143,7 +141,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("stroke"), + ID: property.FieldID("stroke"), Val: property.NewValueAndDatasetValue( property.ValueTypeBool, nil, @@ -151,7 +149,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -159,7 +157,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -197,18 +195,18 @@ func TestCZMLEncoder_Encode(t *testing.T) { Original: lid, Name: "test", Scene: sid, - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polyline").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polyline").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { Original: &iid, - SchemaGroup: id.PropertySchemaGroupID("default"), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("coordinates"), + ID: property.FieldID("coordinates"), Val: property.NewValueAndDatasetValue( property.ValueTypeCoordinates, nil, @@ -220,7 +218,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -228,7 +226,7 @@ func TestCZMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, diff --git a/pkg/layer/encoding/exporter.go b/pkg/layer/encoding/exporter.go index b01dceaf..01773256 100644 --- a/pkg/layer/encoding/exporter.go +++ b/pkg/layer/encoding/exporter.go @@ -3,7 +3,6 @@ package encoding import ( "context" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" ) @@ -14,7 +13,7 @@ type Exporter struct { Encoder Encoder } -func (e *Exporter) ExportLayerByID(ctx context.Context, l id.LayerID) error { +func (e *Exporter) ExportLayerByID(ctx context.Context, l layer.ID) error { if e == nil { return nil } diff --git a/pkg/layer/encoding/geojson.go b/pkg/layer/encoding/geojson.go index b65d4e70..6fb4c4e0 100644 --- a/pkg/layer/encoding/geojson.go +++ b/pkg/layer/encoding/geojson.go @@ -5,7 +5,7 @@ import ( "io" geojson "github.com/paulmach/go.geojson" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" ) @@ -40,7 +40,7 @@ func (e *GeoJSONEncoder) coordsToFloat(c property.Coordinates) [][]float64 { } func (e *GeoJSONEncoder) encodeSingleLayer(li *merging.SealedLayerItem) (*geojson.Feature, error) { - if li == nil || li.PluginID == nil || !id.OfficialPluginID.Equal(*li.PluginID) { + if li == nil || li.PluginID == nil || !layer.OfficialPluginID.Equal(*li.PluginID) { return nil, nil } diff --git a/pkg/layer/encoding/geojson_test.go b/pkg/layer/encoding/geojson_test.go index 04095a28..c7baffff 100644 --- a/pkg/layer/encoding/geojson_test.go +++ b/pkg/layer/encoding/geojson_test.go @@ -5,7 +5,6 @@ import ( "testing" geojson "github.com/paulmach/go.geojson" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" @@ -25,21 +24,21 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { target: &merging.SealedLayerItem{ SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ - Original: id.NewLayerID(), - Scene: id.NewSceneID(), + Original: layer.NewID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("marker").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("marker").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("location"), + ID: property.FieldID("location"), Val: property.NewValueAndDatasetValue( property.ValueTypeLatLng, nil, @@ -47,7 +46,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("pointColor"), + ID: property.FieldID("pointColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -55,7 +54,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("height"), + ID: property.FieldID("height"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -80,21 +79,21 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { target: &merging.SealedLayerItem{ SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ - Original: id.NewLayerID(), - Scene: id.NewSceneID(), + Original: layer.NewID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polygon").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polygon").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("polygon"), + ID: property.FieldID("polygon"), Val: property.NewValueAndDatasetValue( property.ValueTypePolygon, nil, @@ -106,7 +105,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("fillColor"), + ID: property.FieldID("fillColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -114,7 +113,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -122,7 +121,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -130,7 +129,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -157,21 +156,21 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { target: &merging.SealedLayerItem{ SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ - Original: id.NewLayerID(), - Scene: id.NewSceneID(), + Original: layer.NewID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polyline").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polyline").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("coordinates"), + ID: property.FieldID("coordinates"), Val: property.NewValueAndDatasetValue( property.ValueTypeCoordinates, nil, @@ -183,7 +182,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -191,7 +190,7 @@ func TestGeoJSONEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, diff --git a/pkg/layer/encoding/kml.go b/pkg/layer/encoding/kml.go index 750c5cb2..9c00f111 100644 --- a/pkg/layer/encoding/kml.go +++ b/pkg/layer/encoding/kml.go @@ -4,7 +4,7 @@ import ( "errors" "io" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" kml "github.com/twpayne/go-kml" ) @@ -154,7 +154,7 @@ func (e *KMLEncoder) encodeStyle(li *merging.SealedLayerItem) (*kml.SharedElemen // encodes non style layer features func (e *KMLEncoder) encodeLayerTag(li *merging.SealedLayerItem) (*kml.CompoundElement, error) { - if li.PluginID == nil || !id.OfficialPluginID.Equal(*li.PluginID) { + if li.PluginID == nil || !layer.OfficialPluginID.Equal(*li.PluginID) { return nil, nil } diff --git a/pkg/layer/encoding/kml_test.go b/pkg/layer/encoding/kml_test.go index 686b366f..61cbc87e 100644 --- a/pkg/layer/encoding/kml_test.go +++ b/pkg/layer/encoding/kml_test.go @@ -4,7 +4,6 @@ import ( "bytes" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" @@ -15,7 +14,7 @@ import ( var _ Encoder = (*KMLEncoder)(nil) func TestKMLEncoder_Encode(t *testing.T) { - lid := id.MustLayerID("01fmph48ykj1nd82r8e4znh6a6") + lid := layer.MustID("01fmph48ykj1nd82r8e4znh6a6") tests := []struct { name string @@ -28,20 +27,20 @@ func TestKMLEncoder_Encode(t *testing.T) { SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ Original: lid, - Scene: id.NewSceneID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("marker").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("marker").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("location"), + ID: property.FieldID("location"), Val: property.NewValueAndDatasetValue( property.ValueTypeLatLng, nil, @@ -49,7 +48,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("height"), + ID: property.FieldID("height"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -57,7 +56,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("imageSize"), + ID: property.FieldID("imageSize"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -65,7 +64,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("image"), + ID: property.FieldID("image"), Val: property.NewValueAndDatasetValue( property.ValueTypeURL, nil, @@ -73,7 +72,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("pointColor"), + ID: property.FieldID("pointColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -113,20 +112,20 @@ func TestKMLEncoder_Encode(t *testing.T) { SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ Original: lid, - Scene: id.NewSceneID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polygon").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polygon").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("polygon"), + ID: property.FieldID("polygon"), Val: property.NewValueAndDatasetValue( property.ValueTypePolygon, nil, @@ -138,7 +137,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("fill"), + ID: property.FieldID("fill"), Val: property.NewValueAndDatasetValue( property.ValueTypeBool, nil, @@ -146,7 +145,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("fillColor"), + ID: property.FieldID("fillColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -154,7 +153,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("stroke"), + ID: property.FieldID("stroke"), Val: property.NewValueAndDatasetValue( property.ValueTypeBool, nil, @@ -162,7 +161,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -170,7 +169,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, @@ -217,20 +216,20 @@ func TestKMLEncoder_Encode(t *testing.T) { SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ Original: lid, - Scene: id.NewSceneID(), + Scene: layer.NewSceneID(), Name: "test", - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polyline").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polyline").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("coordinates"), + ID: property.FieldID("coordinates"), Val: property.NewValueAndDatasetValue( property.ValueTypeCoordinates, nil, @@ -242,7 +241,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeColor"), + ID: property.FieldID("strokeColor"), Val: property.NewValueAndDatasetValue( property.ValueTypeString, nil, @@ -250,7 +249,7 @@ func TestKMLEncoder_Encode(t *testing.T) { ), }, { - ID: id.PropertySchemaFieldID("strokeWidth"), + ID: property.FieldID("strokeWidth"), Val: property.NewValueAndDatasetValue( property.ValueTypeNumber, nil, diff --git a/pkg/layer/encoding/shp.go b/pkg/layer/encoding/shp.go index 833c0731..842e0f5b 100644 --- a/pkg/layer/encoding/shp.go +++ b/pkg/layer/encoding/shp.go @@ -4,7 +4,7 @@ import ( "errors" "io" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" shp "github.com/reearth/reearth-backend/pkg/shp" @@ -100,7 +100,7 @@ func polygonToSHP(poly property.Polygon) *shp.Polygon { } func (e *SHPEncoder) encodeLayer(li *merging.SealedLayerItem) (sh shp.Shape, st shp.ShapeType, err error) { - if li.PluginID == nil || !id.OfficialPluginID.Equal(*li.PluginID) { + if li.PluginID == nil || !layer.OfficialPluginID.Equal(*li.PluginID) { return nil, 0, nil } switch li.ExtensionID.String() { diff --git a/pkg/layer/encoding/shp_test.go b/pkg/layer/encoding/shp_test.go index b7256f5b..68d4d265 100644 --- a/pkg/layer/encoding/shp_test.go +++ b/pkg/layer/encoding/shp_test.go @@ -6,7 +6,6 @@ import ( "github.com/jonas-p/go-shp" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" @@ -25,23 +24,23 @@ func TestEncodeSHP(t *testing.T) { layer: &merging.SealedLayerItem{ SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ - Original: id.NewLayerID(), + Original: layer.NewID(), Parent: nil, - Scene: id.NewSceneID(), + Scene: layer.NewSceneID(), Property: nil, Infobox: nil, - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polygon").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polygon").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("polygon"), + ID: property.FieldID("polygon"), Val: property.NewValueAndDatasetValue( property.ValueTypePolygon, nil, @@ -80,24 +79,24 @@ func TestEncodeSHP(t *testing.T) { layer: &merging.SealedLayerItem{ SealedLayerCommon: merging.SealedLayerCommon{ Merged: layer.Merged{ - Original: id.NewLayerID(), + Original: layer.NewID(), Parent: nil, Name: "test", - Scene: id.NewSceneID(), + Scene: layer.NewSceneID(), Property: nil, Infobox: nil, - PluginID: &id.OfficialPluginID, - ExtensionID: id.PluginExtensionID("polyline").Ref(), + PluginID: &layer.OfficialPluginID, + ExtensionID: layer.PluginExtensionID("polyline").Ref(), }, Property: &property.Sealed{ - Original: id.NewPropertyID().Ref(), + Original: property.NewID().Ref(), Items: []*property.SealedItem{ { - Original: id.NewPropertyItemID().Ref(), - SchemaGroup: id.PropertySchemaGroupID("default"), + Original: property.NewItemID().Ref(), + SchemaGroup: property.SchemaGroupID("default"), Fields: []*property.SealedField{ { - ID: id.PropertySchemaFieldID("coordinates"), + ID: property.FieldID("coordinates"), Val: property.NewValueAndDatasetValue( property.ValueTypeCoordinates, nil, diff --git a/pkg/layer/group.go b/pkg/layer/group.go index ca1a6c33..d6827e59 100644 --- a/pkg/layer/group.go +++ b/pkg/layer/group.go @@ -1,22 +1,21 @@ package layer import ( - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) type Group struct { layerBase layers *IDList - linkedDatasetSchema *id.DatasetSchemaID + linkedDatasetSchema *DatasetSchemaID root bool } -func (l *Group) ID() id.LayerID { +func (l *Group) ID() ID { return l.layerBase.ID() } -func (l *Group) IDRef() *id.LayerID { +func (l *Group) IDRef() *ID { if l == nil { return nil } @@ -27,14 +26,14 @@ func (l *Group) Name() string { return l.layerBase.Name() } -func (l *Group) Plugin() *id.PluginID { +func (l *Group) Plugin() *PluginID { if l == nil { return nil } return l.layerBase.Plugin() } -func (l *Group) Extension() *id.PluginExtensionID { +func (l *Group) Extension() *PluginExtensionID { if l == nil { return nil } @@ -45,7 +44,7 @@ func (l *Group) UsesPlugin() bool { return l.layerBase.UsesPlugin() } -func (l *Group) Property() *id.PropertyID { +func (l *Group) Property() *PropertyID { if l == nil { return nil } @@ -87,7 +86,7 @@ func (l *Group) SetVisible(visible bool) { l.layerBase.SetVisible(visible) } -func (l *Group) SetPlugin(plugin *id.PluginID) { +func (l *Group) SetPlugin(plugin *PluginID) { if l == nil { return } @@ -101,7 +100,7 @@ func (l *Group) IsLinked() bool { return l.linkedDatasetSchema != nil } -func (l *Group) LinkedDatasetSchema() *id.DatasetSchemaID { +func (l *Group) LinkedDatasetSchema() *DatasetSchemaID { if l == nil || l.linkedDatasetSchema == nil { return nil } @@ -109,7 +108,7 @@ func (l *Group) LinkedDatasetSchema() *id.DatasetSchemaID { return &id } -func (l *Group) Link(ds id.DatasetSchemaID) { +func (l *Group) Link(ds DatasetSchemaID) { if l == nil { return } @@ -134,7 +133,7 @@ func (l *Group) Layers() *IDList { return l.layers } -func (l *Group) MoveLayerFrom(id id.LayerID, index int, fromLayerGroup *Group) { +func (l *Group) MoveLayerFrom(id ID, index int, fromLayerGroup *Group) { if l == nil { return } @@ -167,7 +166,7 @@ func (l *Group) IsRoot() bool { return l.root } -func (l *Group) Properties() []id.PropertyID { +func (l *Group) Properties() []PropertyID { if l == nil { return nil } diff --git a/pkg/layer/group_builder.go b/pkg/layer/group_builder.go index a271589c..4a189817 100644 --- a/pkg/layer/group_builder.go +++ b/pkg/layer/group_builder.go @@ -1,9 +1,5 @@ package layer -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - func GroupFromLayer(l Layer) *Group { li, ok := l.(*Group) if !ok { @@ -32,8 +28,8 @@ func NewGroup() *GroupBuilder { } func (b *GroupBuilder) Build() (*Group, error) { - if id.ID(b.l.id).IsNil() { - return nil, id.ErrInvalidID + if b.l.id.IsNil() { + return nil, ErrInvalidID } return b.l, nil } @@ -51,17 +47,17 @@ func (b *GroupBuilder) base(layer layerBase) *GroupBuilder { return b } -func (b *GroupBuilder) ID(id id.LayerID) *GroupBuilder { +func (b *GroupBuilder) ID(id ID) *GroupBuilder { b.l.id = id return b } func (b *GroupBuilder) NewID() *GroupBuilder { - b.l.id = id.NewLayerID() + b.l.id = NewID() return b } -func (b *GroupBuilder) Scene(s id.SceneID) *GroupBuilder { +func (b *GroupBuilder) Scene(s SceneID) *GroupBuilder { b.l.scene = s return b } @@ -81,17 +77,17 @@ func (b *GroupBuilder) IsVisible(visible bool) *GroupBuilder { return b } -func (b *GroupBuilder) Plugin(plugin *id.PluginID) *GroupBuilder { +func (b *GroupBuilder) Plugin(plugin *PluginID) *GroupBuilder { b.l.plugin = plugin.CopyRef() return b } -func (b *GroupBuilder) Extension(extension *id.PluginExtensionID) *GroupBuilder { +func (b *GroupBuilder) Extension(extension *PluginExtensionID) *GroupBuilder { b.l.extension = extension.CopyRef() return b } -func (b *GroupBuilder) Property(property *id.PropertyID) *GroupBuilder { +func (b *GroupBuilder) Property(property *PropertyID) *GroupBuilder { b.l.property = property.CopyRef() return b } @@ -106,7 +102,7 @@ func (b *GroupBuilder) Infobox(infobox *Infobox) *GroupBuilder { return b } -func (b *GroupBuilder) LinkedDatasetSchema(linkedDatasetSchema *id.DatasetSchemaID) *GroupBuilder { +func (b *GroupBuilder) LinkedDatasetSchema(linkedDatasetSchema *DatasetSchemaID) *GroupBuilder { b.l.linkedDatasetSchema = linkedDatasetSchema.CopyRef() return b } diff --git a/pkg/layer/group_test.go b/pkg/layer/group_test.go index 555d1f20..bad67b07 100644 --- a/pkg/layer/group_test.go +++ b/pkg/layer/group_test.go @@ -3,29 +3,28 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) var _ Layer = &Group{} -var l1 = id.MustLayerID(id.New().String()) -var l2 = id.MustLayerID(id.New().String()) +var l1 = NewID() +var l2 = NewID() var group = Group{ layerBase: layerBase{ - id: id.MustLayerID(id.New().String()), + id: NewID(), name: "xxx", visible: false, - plugin: id.MustPluginID("aaa~1.1.1").Ref(), - extension: id.PluginExtensionID("foo").Ref(), + plugin: MustPluginID("aaa~1.1.1").Ref(), + extension: PluginExtensionID("foo").Ref(), property: nil, infobox: nil, tags: nil, - scene: id.SceneID{}, + scene: SceneID{}, }, layers: &IDList{ - layers: append(make([]id.LayerID, 0), l1, l2), - layerIDs: map[id.LayerID]struct{}{l1: {}, l2: {}}, + layers: append(make([]ID, 0), l1, l2), + layerIDs: map[ID]struct{}{l1: {}, l2: {}}, }, linkedDatasetSchema: nil, root: true, @@ -33,7 +32,7 @@ var group = Group{ func TestGroup_ID(t *testing.T) { assert.NotNil(t, group.ID()) - assert.IsType(t, id.MustLayerID(id.New().String()), group.ID()) + assert.IsType(t, NewID(), group.ID()) } func TestGroup_Name(t *testing.T) { @@ -42,12 +41,12 @@ func TestGroup_Name(t *testing.T) { func TestGroup_Plugin(t *testing.T) { assert.NotNil(t, group.Plugin()) - assert.True(t, id.MustPluginID("aaa~1.1.1").Equal(*group.Plugin())) + assert.True(t, MustPluginID("aaa~1.1.1").Equal(*group.Plugin())) } func TestGroup_IDRef(t *testing.T) { assert.NotNil(t, group.IDRef()) - assert.IsType(t, id.MustLayerID(id.New().String()), group.ID()) + assert.IsType(t, NewID(), group.ID()) } func TestGroup_Extension(t *testing.T) { @@ -82,7 +81,7 @@ func TestGroup_Rename(t *testing.T) { func TestGroup_SetInfobox(t *testing.T) { inf := Infobox{ - property: id.MustPropertyID(id.New().String()), + property: NewPropertyID(), fields: nil, ids: nil, } @@ -91,9 +90,9 @@ func TestGroup_SetInfobox(t *testing.T) { } func TestGroup_SetPlugin(t *testing.T) { - group.SetPlugin(id.MustPluginID("ccc~1.1.1").Ref()) + group.SetPlugin(MustPluginID("ccc~1.1.1").Ref()) assert.NotNil(t, group.Plugin()) - assert.True(t, id.MustPluginID("ccc~1.1.1").Equal(*group.Plugin())) + assert.True(t, MustPluginID("ccc~1.1.1").Equal(*group.Plugin())) } func TestGroup_SetVisible(t *testing.T) { @@ -123,7 +122,7 @@ func TestGroup_LinkedDatasetSchema(t *testing.T) { } func TestGroup_Link(t *testing.T) { - group.Link(id.MustDatasetSchemaID(id.New().String())) + group.Link(NewDatasetSchemaID()) assert.NotNil(t, group.LinkedDatasetSchema()) } diff --git a/pkg/layer/id.go b/pkg/layer/id.go new file mode 100644 index 00000000..b34b0271 --- /dev/null +++ b/pkg/layer/id.go @@ -0,0 +1,75 @@ +package layer + +import ( + "sort" + + "github.com/reearth/reearth-backend/pkg/id" +) + +type ID = id.LayerID +type InfoboxFieldID = id.InfoboxFieldID +type TagID = id.TagID +type SceneID = id.SceneID +type PluginID = id.PluginID +type PluginExtensionID = id.PluginExtensionID +type PropertyID = id.PropertyID +type DatasetID = id.DatasetID +type DatasetSchemaID = id.DatasetSchemaID + +var NewID = id.NewLayerID +var NewInfoboxFieldID = id.NewInfoboxFieldID +var NewTagID = id.NewTagID +var NewSceneID = id.NewSceneID +var NewPropertyID = id.NewPropertyID +var NewDatasetID = id.NewDatasetID +var NewDatasetSchemaID = id.NewDatasetSchemaID + +var MustID = id.MustLayerID +var MustInfoboxFieldID = id.MustInfoboxFieldID +var MustTagID = id.MustTagID +var MustSceneID = id.MustSceneID +var MustPluginID = id.MustPluginID +var MustPropertyID = id.MustPropertyID +var PropertySchemaIDFromExtension = id.PropertySchemaIDFromExtension +var MustPropertySchemaIDFromExtension = id.MustPropertySchemaIDFromExtension + +var IDFrom = id.LayerIDFrom +var InfoboxFieldIDFrom = id.InfoboxFieldIDFrom +var TagIDFrom = id.TagIDFrom +var SceneIDFrom = id.SceneIDFrom +var PropertyIDFrom = id.PropertyIDFrom +var DatasetIDFrom = id.DatasetIDFrom +var DatasetSchemaIDFrom = id.DatasetSchemaIDFrom + +var IDFromRef = id.LayerIDFromRef +var InfoboxFieldIDFromRef = id.InfoboxFieldIDFromRef +var TagIDFromRef = id.TagIDFromRef +var SceneIDFromRef = id.SceneIDFromRef +var PropertyIDFromRef = id.PropertyIDFromRef +var DatasetIDFromRef = id.DatasetIDFromRef +var DatasetSchemaIDFromRef = id.DatasetSchemaIDFromRef + +var IDFromRefID = id.LayerIDFromRefID +var InfoboxFieldIDFromRefID = id.InfoboxFieldIDFromRefID +var TagIDFromRefID = id.TagIDFromRefID +var SceneIDFromRefID = id.SceneIDFromRefID +var PropertyIDFromRefID = id.PropertyIDFromRefID +var DatasetIDFromRefID = id.DatasetIDFromRefID +var DatasetSchemaIDFromRefID = id.DatasetSchemaIDFromRefID + +type IDSet = id.LayerIDSet +type InfoboxFIeldIDSet = id.InfoboxFieldIDSet +type DatasetIDSet = id.DatasetIDSet + +var NewIDSet = id.NewLayerIDSet +var NewInfoboxFIeldIDSet = id.NewInfoboxFieldIDSet +var NewDatasetIDSet = id.NewDatasetIDSet + +var OfficialPluginID = id.OfficialPluginID +var ErrInvalidID = id.ErrInvalidID + +func sortIDs(a []ID) { + sort.SliceStable(a, func(i, j int) bool { + return id.ID(a[i]).Compare(id.ID(a[j])) < 0 + }) +} diff --git a/pkg/layer/id_list.go b/pkg/layer/id_list.go index ec7273cb..f2e9a385 100644 --- a/pkg/layer/id_list.go +++ b/pkg/layer/id_list.go @@ -1,40 +1,34 @@ package layer -import "github.com/reearth/reearth-backend/pkg/id" - -// IDList _ type IDList struct { - layers []id.LayerID + layers []ID // for checking duplication - layerIDs map[id.LayerID]struct{} + layerIDs map[ID]struct{} } -// NewIDList _ -func NewIDList(layers []id.LayerID) *IDList { +func NewIDList(layers []ID) *IDList { ll := IDList{} if len(layers) == 0 { return &ll } - ll.layers = append([]id.LayerID{}, layers...) - ll.layerIDs = make(map[id.LayerID]struct{}, len(layers)) + ll.layers = append([]ID{}, layers...) + ll.layerIDs = make(map[ID]struct{}, len(layers)) for _, l := range layers { ll.layerIDs[l] = struct{}{} } return &ll } -// Layers _ -func (l *IDList) Layers() []id.LayerID { +func (l *IDList) Layers() []ID { if l == nil { return nil } - result := append([]id.LayerID{}, l.layers...) + result := append([]ID{}, l.layers...) return result } -// HasLayer _ -func (l *IDList) HasLayer(id id.LayerID) bool { +func (l *IDList) HasLayer(id ID) bool { if l == nil || len(l.layerIDs) == 0 { return false } @@ -42,23 +36,21 @@ func (l *IDList) HasLayer(id id.LayerID) bool { return ok } -// LayerAt _ -func (l *IDList) LayerAt(index int) id.LayerID { +func (l *IDList) LayerAt(index int) ID { if l == nil || index < 0 || len(l.layers) <= index { - return id.LayerID{} + return ID{} } return l.layers[index] } -func (l *IDList) AtRef(index int) *id.LayerID { +func (l *IDList) AtRef(index int) *ID { if l == nil || index < 0 || len(l.layers) <= index { return nil } return &l.layers[index] } -// FindLayerIndex _ -func (l *IDList) FindLayerIndex(id id.LayerID) int { +func (l *IDList) FindLayerIndex(id ID) int { if l == nil { return -1 } @@ -70,7 +62,6 @@ func (l *IDList) FindLayerIndex(id id.LayerID) int { return -1 } -// LayerCount _ func (l *IDList) LayerCount() int { if l == nil { return 0 @@ -78,13 +69,12 @@ func (l *IDList) LayerCount() int { return len(l.layers) } -// AddLayer _ -func (l *IDList) AddLayer(lid id.LayerID, index int) { +func (l *IDList) AddLayer(lid ID, index int) { if l == nil || l.HasLayer(lid) { return } if l.layerIDs == nil { - l.layerIDs = make(map[id.LayerID]struct{}) + l.layerIDs = make(map[ID]struct{}) } l.layerIDs[lid] = struct{}{} @@ -93,12 +83,11 @@ func (l *IDList) AddLayer(lid id.LayerID, index int) { if index < 0 || le <= index { l.layers = append(l.layers, lid) } else { - l.layers = append(l.layers[:index], append([]id.LayerID{lid}, l.layers[index:]...)...) + l.layers = append(l.layers[:index], append([]ID{lid}, l.layers[index:]...)...) } } -// AppendLayers _ -func (l *IDList) AppendLayers(lid ...id.LayerID) *IDList { +func (l *IDList) AppendLayers(lid ...ID) *IDList { if l == nil { return NewIDList(lid) } @@ -119,8 +108,7 @@ func (l *IDList) Clone() (l2 *IDList) { return NewIDList(l.layers) } -// AddOrMoveLayer _ -func (l *IDList) AddOrMoveLayer(lid id.LayerID, index int) { +func (l *IDList) AddOrMoveLayer(lid ID, index int) { if l == nil { return } @@ -134,12 +122,11 @@ func (l *IDList) AddOrMoveLayer(lid id.LayerID, index int) { l.MoveLayer(lid, index) return } - l.layers = append(l.layers[:index], append([]id.LayerID{lid}, l.layers[index:]...)...) + l.layers = append(l.layers[:index], append([]ID{lid}, l.layers[index:]...)...) l.layerIDs[lid] = struct{}{} } -// MoveLayer _ -func (l *IDList) MoveLayer(id id.LayerID, toIndex int) { +func (l *IDList) MoveLayer(id ID, toIndex int) { if l == nil { return } @@ -152,7 +139,6 @@ func (l *IDList) MoveLayer(id id.LayerID, toIndex int) { } } -// MoveLayerAt _ func (l *IDList) MoveLayerAt(fromIndex int, toIndex int) { if l == nil || len(l.layers) == 0 { return @@ -171,14 +157,13 @@ func (l *IDList) MoveLayerAt(fromIndex int, toIndex int) { f := l.layers[fromIndex] l.layers = append(l.layers[:fromIndex], l.layers[fromIndex+1:]...) - newSlice := make([]id.LayerID, toIndex+1) + newSlice := make([]ID, toIndex+1) copy(newSlice, l.layers[:toIndex]) newSlice[toIndex] = f l.layers = append(newSlice, l.layers[toIndex:]...) } -// RemoveLayer _ -func (l *IDList) RemoveLayer(id id.LayerID) { +func (l *IDList) RemoveLayer(id ID) { if l == nil { return } @@ -191,7 +176,6 @@ func (l *IDList) RemoveLayer(id id.LayerID) { } } -// RemoveLayerAt _ func (l *IDList) RemoveLayerAt(index int) { if l == nil || len(l.layers) == 0 { return @@ -203,9 +187,9 @@ func (l *IDList) RemoveLayerAt(index int) { } layer := l.layers[index] - var layers []id.LayerID + var layers []ID if index == le { - layers = []id.LayerID{} + layers = []ID{} } else { layers = l.layers[index+1:] } @@ -213,7 +197,6 @@ func (l *IDList) RemoveLayerAt(index int) { delete(l.layerIDs, layer) } -// Empty _ func (l *IDList) Empty() { if l == nil { return diff --git a/pkg/layer/id_list_test.go b/pkg/layer/id_list_test.go index 5edcf2bf..c9345551 100644 --- a/pkg/layer/id_list_test.go +++ b/pkg/layer/id_list_test.go @@ -3,17 +3,15 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" - "github.com/stretchr/testify/assert" ) func TestLayerIDList(t *testing.T) { - l1 := id.LayerID(id.New()) - l2 := id.LayerID(id.New()) - l3 := id.LayerID(id.New()) - l4 := id.LayerID(id.New()) - rawLayers := []id.LayerID{l1, l3} + l1 := NewID() + l2 := NewID() + l3 := NewID() + l4 := NewID() + rawLayers := []ID{l1, l3} layers := NewIDList(rawLayers) assert.NotNil(t, layers) diff --git a/pkg/layer/infobox.go b/pkg/layer/infobox.go index 001c9e84..f446e2a5 100644 --- a/pkg/layer/infobox.go +++ b/pkg/layer/infobox.go @@ -5,22 +5,21 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/builtin" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) type Infobox struct { - property id.PropertyID + property PropertyID fields []*InfoboxField // for checking duplication - ids map[id.InfoboxFieldID]struct{} + ids map[InfoboxFieldID]struct{} } -func NewInfobox(fields []*InfoboxField, p id.PropertyID) *Infobox { +func NewInfobox(fields []*InfoboxField, p PropertyID) *Infobox { infobox := Infobox{ property: p, fields: make([]*InfoboxField, len(fields)), - ids: make(map[id.InfoboxFieldID]struct{}, len(fields)), + ids: make(map[InfoboxFieldID]struct{}, len(fields)), } for i, f := range fields { if f == nil { @@ -32,11 +31,11 @@ func NewInfobox(fields []*InfoboxField, p id.PropertyID) *Infobox { return &infobox } -func (i *Infobox) Property() id.PropertyID { +func (i *Infobox) Property() PropertyID { return i.property } -func (i *Infobox) PropertyRef() *id.PropertyID { +func (i *Infobox) PropertyRef() *PropertyID { if i == nil { return nil } @@ -51,7 +50,7 @@ func (i *Infobox) Fields() []*InfoboxField { return append([]*InfoboxField{}, i.fields...) } -func (i *Infobox) Field(field id.InfoboxFieldID) *InfoboxField { +func (i *Infobox) Field(field InfoboxFieldID) *InfoboxField { for _, f := range i.fields { if f.ID() == field { return f @@ -67,7 +66,7 @@ func (i *Infobox) FieldAt(index int) *InfoboxField { return i.fields[index] } -func (i *Infobox) Has(id id.InfoboxFieldID) bool { +func (i *Infobox) Has(id InfoboxFieldID) bool { _, ok := i.ids[id] return ok } @@ -90,7 +89,7 @@ func (i *Infobox) Add(field *InfoboxField, index int) { i.ids[id] = struct{}{} } -func (i *Infobox) Move(field id.InfoboxFieldID, toIndex int) { +func (i *Infobox) Move(field InfoboxFieldID, toIndex int) { for fromIndex, f := range i.fields { if f.ID() == field { i.MoveAt(fromIndex, toIndex) @@ -116,7 +115,7 @@ func (i *Infobox) MoveAt(fromIndex int, toIndex int) { i.fields = append(newSlice, i.fields[toIndex:]...) } -func (i *Infobox) Remove(field id.InfoboxFieldID) { +func (i *Infobox) Remove(field InfoboxFieldID) { for index, f := range i.fields { if f.ID() == field { i.RemoveAt(index) @@ -125,12 +124,12 @@ func (i *Infobox) Remove(field id.InfoboxFieldID) { } } -func (i *Infobox) RemoveAllByPlugin(pid id.PluginID) []id.PropertyID { +func (i *Infobox) RemoveAllByPlugin(pid PluginID) []PropertyID { if i == nil { return nil } - var properties []id.PropertyID + var properties []PropertyID for j := 0; j < len(i.fields); j++ { if i.fields[j].plugin.Equal(pid) { properties = append(properties, i.fields[j].Property()) diff --git a/pkg/layer/infobox_field.go b/pkg/layer/infobox_field.go index 70c036fc..b7e5379d 100644 --- a/pkg/layer/infobox_field.go +++ b/pkg/layer/infobox_field.go @@ -5,34 +5,33 @@ package layer import ( "errors" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) type InfoboxField struct { - id id.InfoboxFieldID - plugin id.PluginID - extension id.PluginExtensionID - property id.PropertyID + id InfoboxFieldID + plugin PluginID + extension PluginExtensionID + property PropertyID } -func (i *InfoboxField) ID() id.InfoboxFieldID { +func (i *InfoboxField) ID() InfoboxFieldID { return i.id } -func (i *InfoboxField) Plugin() id.PluginID { +func (i *InfoboxField) Plugin() PluginID { return i.plugin } -func (i *InfoboxField) Extension() id.PluginExtensionID { +func (i *InfoboxField) Extension() PluginExtensionID { return i.extension } -func (i *InfoboxField) Property() id.PropertyID { +func (i *InfoboxField) Property() PropertyID { return i.property } -func (i *InfoboxField) PropertyRef() *id.PropertyID { +func (i *InfoboxField) PropertyRef() *PropertyID { if i == nil { return nil } @@ -48,7 +47,7 @@ func (i *InfoboxField) ValidateProperty(pm property.Map) error { if lp == nil { return errors.New("property does not exist") } - if !lp.Schema().Equal(id.MustPropertySchemaIDFromExtension(i.plugin, i.extension)) { + if !lp.Schema().Equal(MustPropertySchemaIDFromExtension(i.plugin, i.extension)) { return errors.New("property has a invalid schema") } diff --git a/pkg/layer/infobox_field_builder.go b/pkg/layer/infobox_field_builder.go index 4a8af2c1..47ce14ff 100644 --- a/pkg/layer/infobox_field_builder.go +++ b/pkg/layer/infobox_field_builder.go @@ -1,10 +1,5 @@ package layer -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - -// InfoboxFieldBuilder _ type InfoboxFieldBuilder struct { i *InfoboxField } @@ -14,10 +9,10 @@ func NewInfoboxField() *InfoboxFieldBuilder { } func (b *InfoboxFieldBuilder) Build() (*InfoboxField, error) { - if id.ID(b.i.id).IsNil() || + if b.i.id.IsNil() || string(b.i.extension) == "" || - id.ID(b.i.property).IsNil() { - return nil, id.ErrInvalidID + b.i.property.IsNil() { + return nil, ErrInvalidID } return b.i, nil } @@ -30,27 +25,27 @@ func (b *InfoboxFieldBuilder) MustBuild() *InfoboxField { return i } -func (b *InfoboxFieldBuilder) ID(id id.InfoboxFieldID) *InfoboxFieldBuilder { +func (b *InfoboxFieldBuilder) ID(id InfoboxFieldID) *InfoboxFieldBuilder { b.i.id = id return b } func (b *InfoboxFieldBuilder) NewID() *InfoboxFieldBuilder { - b.i.id = id.InfoboxFieldID(id.New()) + b.i.id = NewInfoboxFieldID() return b } -func (b *InfoboxFieldBuilder) Plugin(plugin id.PluginID) *InfoboxFieldBuilder { +func (b *InfoboxFieldBuilder) Plugin(plugin PluginID) *InfoboxFieldBuilder { b.i.plugin = plugin return b } -func (b *InfoboxFieldBuilder) Extension(extension id.PluginExtensionID) *InfoboxFieldBuilder { +func (b *InfoboxFieldBuilder) Extension(extension PluginExtensionID) *InfoboxFieldBuilder { b.i.extension = extension return b } -func (b *InfoboxFieldBuilder) Property(p id.PropertyID) *InfoboxFieldBuilder { +func (b *InfoboxFieldBuilder) Property(p PropertyID) *InfoboxFieldBuilder { b.i.property = p return b } diff --git a/pkg/layer/infobox_test.go b/pkg/layer/infobox_test.go index d8a016aa..1b6d77c7 100644 --- a/pkg/layer/infobox_test.go +++ b/pkg/layer/infobox_test.go @@ -3,17 +3,16 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestInfobox(t *testing.T) { - f1 := &InfoboxField{id: id.NewInfoboxFieldID()} - f2 := &InfoboxField{id: id.NewInfoboxFieldID()} - f3 := &InfoboxField{id: id.NewInfoboxFieldID()} - f4 := &InfoboxField{id: id.NewInfoboxFieldID()} + f1 := &InfoboxField{id: NewInfoboxFieldID()} + f2 := &InfoboxField{id: NewInfoboxFieldID()} + f3 := &InfoboxField{id: NewInfoboxFieldID()} + f4 := &InfoboxField{id: NewInfoboxFieldID()} fields := []*InfoboxField{f1, f2, f3} - infobox := NewInfobox(fields, id.NewPropertyID()) + infobox := NewInfobox(fields, NewPropertyID()) assert.NotNil(t, infobox) assert.Equal(t, fields, infobox.Fields()) @@ -52,17 +51,17 @@ func TestInfobox(t *testing.T) { } func TestInfobox_RemoveAllByPlugin(t *testing.T) { - pid1 := id.MustPluginID("xxx~1.1.1") - pid2 := id.MustPluginID("xxy~1.1.1") - f1 := &InfoboxField{id: id.NewInfoboxFieldID(), plugin: pid1, extension: "a", property: id.NewPropertyID()} - f2 := &InfoboxField{id: id.NewInfoboxFieldID(), plugin: pid2, extension: "b", property: id.NewPropertyID()} - f3 := &InfoboxField{id: id.NewInfoboxFieldID(), plugin: pid1, extension: "c", property: id.NewPropertyID()} - infobox := NewInfobox([]*InfoboxField{f1, f2, f3}, id.NewPropertyID()) + pid1 := MustPluginID("xxx~1.1.1") + pid2 := MustPluginID("xxy~1.1.1") + f1 := &InfoboxField{id: NewInfoboxFieldID(), plugin: pid1, extension: "a", property: NewPropertyID()} + f2 := &InfoboxField{id: NewInfoboxFieldID(), plugin: pid2, extension: "b", property: NewPropertyID()} + f3 := &InfoboxField{id: NewInfoboxFieldID(), plugin: pid1, extension: "c", property: NewPropertyID()} + infobox := NewInfobox([]*InfoboxField{f1, f2, f3}, NewPropertyID()) - assert.Equal(t, []id.PropertyID(nil), (*Infobox)(nil).RemoveAllByPlugin(pid1)) + assert.Equal(t, []PropertyID(nil), (*Infobox)(nil).RemoveAllByPlugin(pid1)) assert.Equal(t, []*InfoboxField{f1, f2, f3}, infobox.fields) - assert.Equal(t, []id.PropertyID{f1.Property(), f3.Property()}, infobox.RemoveAllByPlugin(pid1)) + assert.Equal(t, []PropertyID{f1.Property(), f3.Property()}, infobox.RemoveAllByPlugin(pid1)) assert.Equal(t, []*InfoboxField{f2}, infobox.fields) - assert.Equal(t, []id.PropertyID(nil), infobox.RemoveAllByPlugin(pid1)) + assert.Equal(t, []PropertyID(nil), infobox.RemoveAllByPlugin(pid1)) assert.Equal(t, []*InfoboxField{f2}, infobox.fields) } diff --git a/pkg/layer/initializer.go b/pkg/layer/initializer.go index 98aa1b71..8d0624b4 100644 --- a/pkg/layer/initializer.go +++ b/pkg/layer/initializer.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/builtin" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/rerror" ) @@ -18,7 +17,7 @@ var ( ) type InitializerResult struct { - Root id.LayerID + Root ID Layers Map Properties property.Map } @@ -40,18 +39,18 @@ func (r InitializerResult) RootLayerItem() *Item { } type Initializer struct { - ID *id.LayerID `json:"id"` - Plugin *id.PluginID `json:"plugin"` - Extension *id.PluginExtensionID `json:"extension"` + ID *ID `json:"id"` + Plugin *PluginID `json:"plugin"` + Extension *PluginExtensionID `json:"extension"` Name string `json:"name"` Infobox *InitializerInfobox `json:"infobox"` - PropertyID *id.PropertyID `json:"propertyId"` + PropertyID *PropertyID `json:"propertyId"` Property *property.Initializer `json:"property"` Layers []*Initializer `json:"layers"` - LayerIDs []id.LayerID `json:"layerIds"` + LayerIDs []ID `json:"layerIds"` IsVisible *bool `json:"isVisible"` - LinkedDatasetSchema *id.DatasetSchemaID `json:"linkedDatasetSchema"` - LinkedDataset *id.DatasetID `json:"linkedDataset"` + LinkedDatasetSchema *DatasetSchemaID `json:"linkedDatasetSchema"` + LinkedDataset *DatasetID `json:"linkedDataset"` } func (i *Initializer) Clone() *Initializer { @@ -73,9 +72,9 @@ func (i *Initializer) Clone() *Initializer { } } - var layerIDs []id.LayerID + var layerIDs []ID if len(i.LayerIDs) > 0 { - layerIDs = append([]id.LayerID{}, i.LayerIDs...) + layerIDs = append([]ID{}, i.LayerIDs...) } return &Initializer{ @@ -94,7 +93,7 @@ func (i *Initializer) Clone() *Initializer { } } -func (i *Initializer) Layer(sid id.SceneID) (r InitializerResult, err error) { +func (i *Initializer) Layer(sid SceneID) (r InitializerResult, err error) { if i == nil { return } @@ -108,7 +107,7 @@ func (i *Initializer) Layer(sid id.SceneID) (r InitializerResult, err error) { lid := i.ID if i.ID == nil { - lid = id.NewLayerID().Ref() + lid = NewID().Ref() } pid := i.PropertyID @@ -166,7 +165,7 @@ func (i *Initializer) Layer(sid id.SceneID) (r InitializerResult, err error) { return } -func (i *Initializer) MustBeLayer(sid id.SceneID) InitializerResult { +func (i *Initializer) MustBeLayer(sid SceneID) InitializerResult { r, err := i.Layer(sid) if err != nil { panic(err) @@ -175,7 +174,7 @@ func (i *Initializer) MustBeLayer(sid id.SceneID) InitializerResult { } type InitializerInfobox struct { - PropertyID *id.PropertyID `json:"propertyId"` + PropertyID *PropertyID `json:"propertyId"` Property *property.Initializer `json:"property"` Fields []*InitializerInfoboxField `json:"fields"` } @@ -200,7 +199,7 @@ func (i *InitializerInfobox) Clone() *InitializerInfobox { } } -func (i *InitializerInfobox) Infobox(scene id.SceneID) (*Infobox, property.Map, error) { +func (i *InitializerInfobox) Infobox(scene SceneID) (*Infobox, property.Map, error) { if i == nil { return nil, nil, nil } @@ -240,10 +239,10 @@ func (i *InitializerInfobox) Infobox(scene id.SceneID) (*Infobox, property.Map, } type InitializerInfoboxField struct { - ID *id.InfoboxFieldID `json:"id"` - Plugin id.PluginID `json:"plugin"` - Extension id.PluginExtensionID `json:"extension"` - PropertyID *id.PropertyID `json:"propertyId"` + ID *InfoboxFieldID `json:"id"` + Plugin PluginID `json:"plugin"` + Extension PluginExtensionID `json:"extension"` + PropertyID *PropertyID `json:"propertyId"` Property *property.Initializer `json:"property"` } @@ -261,19 +260,19 @@ func (i *InitializerInfoboxField) Clone() *InitializerInfoboxField { } } -func (i *InitializerInfoboxField) InfoboxField(scene id.SceneID) (*InfoboxField, *property.Property, error) { +func (i *InitializerInfoboxField) InfoboxField(scene SceneID) (*InfoboxField, *property.Property, error) { if i == nil { return nil, nil, nil } - psid, err := id.PropertySchemaIDFromExtension(i.Plugin, i.Extension) + psid, err := PropertySchemaIDFromExtension(i.Plugin, i.Extension) if err != nil { return nil, nil, err } fid := i.ID if i.ID == nil { - fid = id.NewInfoboxFieldID().Ref() + fid = NewInfoboxFieldID().Ref() } pid := i.PropertyID diff --git a/pkg/layer/initializer_test.go b/pkg/layer/initializer_test.go index 960bf26c..725ad4f2 100644 --- a/pkg/layer/initializer_test.go +++ b/pkg/layer/initializer_test.go @@ -3,7 +3,6 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" ) @@ -11,19 +10,19 @@ import ( func TestInitializer_Clone(t *testing.T) { isVisible := false i := &Initializer{ - ID: id.NewLayerID().Ref(), - Plugin: id.MustPluginID("reearth").Ref(), - Extension: id.PluginExtensionID("marker").Ref(), + ID: NewID().Ref(), + Plugin: MustPluginID("reearth").Ref(), + Extension: PluginExtensionID("marker").Ref(), Name: "hoge", Infobox: &InitializerInfobox{}, - PropertyID: id.NewPropertyID().Ref(), + PropertyID: NewPropertyID().Ref(), Property: &property.Initializer{ - ID: id.NewPropertyID().Ref(), + ID: NewPropertyID().Ref(), }, Layers: []*Initializer{{}}, IsVisible: &isVisible, - LinkedDatasetSchema: id.NewDatasetSchemaID().Ref(), - LinkedDataset: id.NewDatasetID().Ref(), + LinkedDatasetSchema: NewDatasetSchemaID().Ref(), + LinkedDataset: NewDatasetID().Ref(), } actual := i.Clone() @@ -44,24 +43,24 @@ func TestInitializer_Clone(t *testing.T) { } func TestInitializer_Layer(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() isVisible := false i := &Initializer{ - ID: id.NewLayerID().Ref(), - Plugin: id.MustPluginID("reearth").Ref(), - Extension: id.PluginExtensionID("marker").Ref(), + ID: NewID().Ref(), + Plugin: MustPluginID("reearth").Ref(), + Extension: PluginExtensionID("marker").Ref(), Name: "hoge", Infobox: &InitializerInfobox{ - PropertyID: id.NewPropertyID().Ref(), + PropertyID: NewPropertyID().Ref(), }, - PropertyID: id.NewPropertyID().Ref(), + PropertyID: NewPropertyID().Ref(), IsVisible: &isVisible, - LinkedDatasetSchema: id.NewDatasetSchemaID().Ref(), - LinkedDataset: id.NewDatasetID().Ref(), + LinkedDatasetSchema: NewDatasetSchemaID().Ref(), + LinkedDataset: NewDatasetID().Ref(), Layers: []*Initializer{{ - ID: id.NewLayerID().Ref(), + ID: NewID().Ref(), Layers: []*Initializer{{ - ID: id.NewLayerID().Ref(), + ID: NewID().Ref(), }}, }}, } @@ -76,10 +75,10 @@ func TestInitializer_Layer(t *testing.T) { Infobox(NewInfobox(nil, *i.Infobox.PropertyID)). Property(i.PropertyID). Group(). - Layers(NewIDList([]id.LayerID{*i.Layers[0].ID})). + Layers(NewIDList([]ID{*i.Layers[0].ID})). LinkedDatasetSchema(i.LinkedDatasetSchema). MustBuild() - expected2 := New().ID(*i.Layers[0].ID).Scene(sid).Group().Layers(NewIDList([]id.LayerID{*i.Layers[0].Layers[0].ID})).MustBuild() + expected2 := New().ID(*i.Layers[0].ID).Scene(sid).Group().Layers(NewIDList([]ID{*i.Layers[0].Layers[0].ID})).MustBuild() expected3 := New().ID(*i.Layers[0].Layers[0].ID).Scene(sid).Item().MustBuild() actual, err := i.Layer(sid) @@ -99,15 +98,15 @@ func TestInitializer_Layer(t *testing.T) { func TestInitializerInfobox_Clone(t *testing.T) { i := &InitializerInfobox{ - PropertyID: id.NewPropertyID().Ref(), + PropertyID: NewPropertyID().Ref(), Property: &property.Initializer{ - ID: id.NewPropertyID().Ref(), + ID: NewPropertyID().Ref(), }, Fields: []*InitializerInfoboxField{{ - ID: id.NewInfoboxFieldID().Ref(), - Plugin: id.MustPluginID("reearth"), - Extension: id.PluginExtensionID("marker"), - PropertyID: id.NewPropertyID().Ref(), + ID: NewInfoboxFieldID().Ref(), + Plugin: MustPluginID("reearth"), + Extension: PluginExtensionID("marker"), + PropertyID: NewPropertyID().Ref(), }}, } @@ -121,14 +120,14 @@ func TestInitializerInfobox_Clone(t *testing.T) { } func TestInitializerInfobox_Infobox(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() i := &InitializerInfobox{ - PropertyID: id.NewPropertyID().Ref(), + PropertyID: NewPropertyID().Ref(), Fields: []*InitializerInfoboxField{{ - ID: id.NewInfoboxFieldID().Ref(), - Plugin: id.MustPluginID("reearth"), - Extension: id.PluginExtensionID("marker"), - PropertyID: id.NewPropertyID().Ref(), + ID: NewInfoboxFieldID().Ref(), + Plugin: MustPluginID("reearth"), + Extension: PluginExtensionID("marker"), + PropertyID: NewPropertyID().Ref(), }}, } @@ -148,12 +147,12 @@ func TestInitializerInfobox_Infobox(t *testing.T) { func TestInitializerInfoboxField_Clone(t *testing.T) { i := &InitializerInfoboxField{ - ID: id.NewInfoboxFieldID().Ref(), - Plugin: id.MustPluginID("reearth"), - Extension: id.PluginExtensionID("marker"), - PropertyID: id.NewPropertyID().Ref(), + ID: NewInfoboxFieldID().Ref(), + Plugin: MustPluginID("reearth"), + Extension: PluginExtensionID("marker"), + PropertyID: NewPropertyID().Ref(), Property: &property.Initializer{ - ID: id.NewPropertyID().Ref(), + ID: NewPropertyID().Ref(), }, } @@ -166,12 +165,12 @@ func TestInitializerInfoboxField_Clone(t *testing.T) { } func TestInitializerInfoboxField_InfoboxField(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() i := &InitializerInfoboxField{ - ID: id.NewInfoboxFieldID().Ref(), - Plugin: id.MustPluginID("reearth"), - Extension: id.PluginExtensionID("marker"), - PropertyID: id.NewPropertyID().Ref(), + ID: NewInfoboxFieldID().Ref(), + Plugin: MustPluginID("reearth"), + Extension: PluginExtensionID("marker"), + PropertyID: NewPropertyID().Ref(), } expected := NewInfoboxField().ID(*i.ID).Plugin(i.Plugin).Extension(i.Extension).Property(*i.PropertyID).MustBuild() diff --git a/pkg/layer/item.go b/pkg/layer/item.go index abf81999..e134863a 100644 --- a/pkg/layer/item.go +++ b/pkg/layer/item.go @@ -1,20 +1,19 @@ package layer import ( - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) type Item struct { layerBase - linkedDataset *id.DatasetID + linkedDataset *DatasetID } -func (l *Item) ID() id.LayerID { +func (l *Item) ID() ID { return l.layerBase.ID() } -func (l *Item) IDRef() *id.LayerID { +func (l *Item) IDRef() *ID { if l == nil { return nil } @@ -35,14 +34,14 @@ func (l *Item) IsVisible() bool { return l.layerBase.IsVisible() } -func (l *Item) Plugin() *id.PluginID { +func (l *Item) Plugin() *PluginID { if l == nil { return nil } return l.layerBase.Plugin() } -func (l *Item) Extension() *id.PluginExtensionID { +func (l *Item) Extension() *PluginExtensionID { if l == nil { return nil } @@ -56,7 +55,7 @@ func (l *Item) UsesPlugin() bool { return l.layerBase.UsesPlugin() } -func (l *Item) Property() *id.PropertyID { +func (l *Item) Property() *PropertyID { if l == nil { return nil } @@ -91,7 +90,7 @@ func (l *Item) SetInfobox(infobox *Infobox) { l.layerBase.SetInfobox(infobox) } -func (l *Item) SetPlugin(plugin *id.PluginID) { +func (l *Item) SetPlugin(plugin *PluginID) { if l == nil { return } @@ -105,7 +104,7 @@ func (l *Item) IsLinked() bool { return l.linkedDataset != nil } -func (l *Item) LinkedDataset() *id.DatasetID { +func (l *Item) LinkedDataset() *DatasetID { if l == nil || l.linkedDataset == nil { return nil } @@ -113,7 +112,7 @@ func (l *Item) LinkedDataset() *id.DatasetID { return &id } -func (l *Item) Link(ds id.DatasetID) { +func (l *Item) Link(ds DatasetID) { if l == nil { return } @@ -136,7 +135,7 @@ func (l *Item) LayerRef() *Layer { return &layer } -func (l *Item) Properties() []id.PropertyID { +func (l *Item) Properties() []PropertyID { if l == nil { return nil } diff --git a/pkg/layer/item_builder.go b/pkg/layer/item_builder.go index c358af08..5375ee31 100644 --- a/pkg/layer/item_builder.go +++ b/pkg/layer/item_builder.go @@ -1,9 +1,5 @@ package layer -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - func ItemFromLayer(l Layer) *Item { li, ok := l.(*Item) if !ok { @@ -32,8 +28,8 @@ func NewItem() *ItemBuilder { } func (b *ItemBuilder) Build() (*Item, error) { - if id.ID(b.l.id).IsNil() { - return nil, id.ErrInvalidID + if b.l.id.IsNil() { + return nil, ErrInvalidID } return b.l, nil } @@ -51,17 +47,17 @@ func (b *ItemBuilder) base(layer layerBase) *ItemBuilder { return b } -func (b *ItemBuilder) ID(id id.LayerID) *ItemBuilder { +func (b *ItemBuilder) ID(id ID) *ItemBuilder { b.l.id = id return b } func (b *ItemBuilder) NewID() *ItemBuilder { - b.l.id = id.NewLayerID() + b.l.id = NewID() return b } -func (b *ItemBuilder) Scene(s id.SceneID) *ItemBuilder { +func (b *ItemBuilder) Scene(s SceneID) *ItemBuilder { b.l.scene = s return b } @@ -76,17 +72,17 @@ func (b *ItemBuilder) IsVisible(visible bool) *ItemBuilder { return b } -func (b *ItemBuilder) Plugin(plugin *id.PluginID) *ItemBuilder { +func (b *ItemBuilder) Plugin(plugin *PluginID) *ItemBuilder { b.l.plugin = plugin.CopyRef() return b } -func (b *ItemBuilder) Extension(extension *id.PluginExtensionID) *ItemBuilder { +func (b *ItemBuilder) Extension(extension *PluginExtensionID) *ItemBuilder { b.l.extension = extension.CopyRef() return b } -func (b *ItemBuilder) Property(p *id.PropertyID) *ItemBuilder { +func (b *ItemBuilder) Property(p *PropertyID) *ItemBuilder { b.l.property = p.CopyRef() return b } @@ -96,7 +92,7 @@ func (b *ItemBuilder) Infobox(infobox *Infobox) *ItemBuilder { return b } -func (b *ItemBuilder) LinkedDataset(linkedDataset *id.DatasetID) *ItemBuilder { +func (b *ItemBuilder) LinkedDataset(linkedDataset *DatasetID) *ItemBuilder { b.l.linkedDataset = linkedDataset.CopyRef() return b } diff --git a/pkg/layer/layer.go b/pkg/layer/layer.go index 86461c25..1119e7cf 100644 --- a/pkg/layer/layer.go +++ b/pkg/layer/layer.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) @@ -14,22 +13,22 @@ var ( ) type Layer interface { - ID() id.LayerID + ID() ID Name() string IsVisible() bool - Plugin() *id.PluginID - Extension() *id.PluginExtensionID + Plugin() *PluginID + Extension() *PluginExtensionID UsesPlugin() bool - Property() *id.PropertyID + Property() *PropertyID HasInfobox() bool Infobox() *Infobox - Scene() id.SceneID + Scene() SceneID Tags() *TagList Rename(string) SetVisible(bool) SetInfobox(*Infobox) - SetPlugin(*id.PluginID) - Properties() []id.PropertyID + SetPlugin(*PluginID) + Properties() []PropertyID ValidateProperties(property.Map) error } @@ -70,22 +69,22 @@ func ToLayerItemRef(l *Layer) *Item { } type layerBase struct { - id id.LayerID + id ID name string visible bool - plugin *id.PluginID - extension *id.PluginExtensionID - property *id.PropertyID + plugin *PluginID + extension *PluginExtensionID + property *PropertyID infobox *Infobox - scene id.SceneID + scene SceneID tags *TagList } -func (l *layerBase) ID() id.LayerID { +func (l *layerBase) ID() ID { return l.id } -func (l *layerBase) IDRef() *id.LayerID { +func (l *layerBase) IDRef() *ID { if l == nil { return nil } @@ -113,21 +112,21 @@ func (l *layerBase) UsesPlugin() bool { return l.plugin != nil && l.extension != nil } -func (l *layerBase) Plugin() *id.PluginID { +func (l *layerBase) Plugin() *PluginID { if l == nil { return nil } return l.plugin.CopyRef() } -func (l *layerBase) Extension() *id.PluginExtensionID { +func (l *layerBase) Extension() *PluginExtensionID { if l == nil { return nil } return l.extension.CopyRef() } -func (l *layerBase) Property() *id.PropertyID { +func (l *layerBase) Property() *PropertyID { if l == nil { return nil } @@ -148,7 +147,7 @@ func (l *layerBase) Infobox() *Infobox { return l.infobox } -func (l *layerBase) Scene() id.SceneID { +func (l *layerBase) Scene() SceneID { return l.scene } @@ -173,18 +172,18 @@ func (l *layerBase) SetInfobox(infobox *Infobox) { l.infobox = infobox } -func (l *layerBase) SetPlugin(plugin *id.PluginID) { +func (l *layerBase) SetPlugin(plugin *PluginID) { if l == nil { return } l.plugin = plugin.CopyRef() } -func (l *layerBase) Properties() []id.PropertyID { +func (l *layerBase) Properties() []PropertyID { if l == nil { return nil } - res := []id.PropertyID{} + res := []PropertyID{} if l.property != nil { res = append(res, *l.property) } @@ -208,7 +207,7 @@ func (l *layerBase) ValidateProperties(pm property.Map) error { return errors.New("layer should have plugin id and extension id") } - psid, err := id.PropertySchemaIDFromExtension(*l.plugin, *l.extension) + psid, err := PropertySchemaIDFromExtension(*l.plugin, *l.extension) if err != nil { return errors.New("layer has invalid plugin id and extension id") } diff --git a/pkg/layer/layerops/initializer.go b/pkg/layer/layerops/initializer.go index f69b3e2b..c1943380 100644 --- a/pkg/layer/layerops/initializer.go +++ b/pkg/layer/layerops/initializer.go @@ -3,19 +3,18 @@ package layerops import ( "errors" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" ) type LayerItem struct { - SceneID id.SceneID - ParentLayerID id.LayerID + SceneID layer.SceneID + ParentLayerID layer.ID Plugin *plugin.Plugin - ExtensionID *id.PluginExtensionID + ExtensionID *layer.PluginExtensionID Index *int - LinkedDatasetID *id.DatasetID + LinkedDatasetID *layer.DatasetID Name string LinkablePropertySchema *property.Schema LatLng *property.LatLng diff --git a/pkg/layer/layerops/initializer_test.go b/pkg/layer/layerops/initializer_test.go index d016a31c..b38bd827 100644 --- a/pkg/layer/layerops/initializer_test.go +++ b/pkg/layer/layerops/initializer_test.go @@ -5,16 +5,16 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/stretchr/testify/assert" ) func TestInitialize(t *testing.T) { - lid := id.MustLayerID(id.New().String()) - ps := id.MustPropertySchemaID("xxx~1.1.1/aa") - eid := id.PluginExtensionID("foo") - eid2 := id.PluginExtensionID("foo2") + lid := layer.NewID() + ps := plugin.MustPropertySchemaID("xxx~1.1.1/aa") + eid := plugin.ExtensionID("foo") + eid2 := plugin.ExtensionID("foo2") e := plugin.NewExtension(). ID("foo"). Description(i18n.StringFrom("foo/des")). @@ -29,17 +29,17 @@ func TestInitialize(t *testing.T) { es := append(make([]*plugin.Extension, 0), e) es = append(es, e2) p := plugin.New(). - ID(id.MustPluginID("xxx~1.1.1")). + ID(layer.MustPluginID("xxx~1.1.1")). Schema(&ps). Extensions(es). MustBuild() - s := id.NewSceneID() + s := layer.NewSceneID() testCases := []struct { name string - sceneID *id.SceneID - parentLayerID *id.LayerID + sceneID *layer.SceneID + parentLayerID *layer.ID plugin *plugin.Plugin - extID *id.PluginExtensionID + extID *layer.PluginExtensionID err error }{ { diff --git a/pkg/layer/layerops/processor.go b/pkg/layer/layerops/processor.go index aa02737a..ce59fbd7 100644 --- a/pkg/layer/layerops/processor.go +++ b/pkg/layer/layerops/processor.go @@ -3,22 +3,21 @@ package layerops import ( "context" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" ) type Processor struct { - RootLayerID id.LayerID + RootLayerID layer.ID LayerLoader layer.Loader } type UninstallPluginResult struct { ModifiedLayers layer.List RemovedLayers *layer.IDList - RemovedProperties []id.PropertyID + RemovedProperties []layer.PropertyID } -func (p Processor) UninstallPlugin(ctx context.Context, pluginID id.PluginID) (res UninstallPluginResult, err error) { +func (p Processor) UninstallPlugin(ctx context.Context, pluginID layer.PluginID) (res UninstallPluginResult, err error) { err = p.LayerLoader.Walk(ctx, func(l layer.Layer, parents layer.GroupList) error { parent := parents.Last() parentRemoved := parent != nil && res.RemovedLayers.HasLayer(parent.ID()) @@ -42,7 +41,7 @@ func (p Processor) UninstallPlugin(ctx context.Context, pluginID id.PluginID) (r res.RemovedProperties = append(res.RemovedProperties, l.Properties()...) res.ModifiedLayers = res.ModifiedLayers.Remove(l.ID()) return nil - }, []id.LayerID{p.RootLayerID}) + }, []layer.ID{p.RootLayerID}) return } diff --git a/pkg/layer/layerops/processor_test.go b/pkg/layer/layerops/processor_test.go index 81993643..858ee63a 100644 --- a/pkg/layer/layerops/processor_test.go +++ b/pkg/layer/layerops/processor_test.go @@ -4,23 +4,22 @@ import ( "context" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/stretchr/testify/assert" ) func TestProcessor_UninstallPlugin(t *testing.T) { - sid := id.NewSceneID() - pid := id.MustPluginID("hoge~1.0.0") - pid2 := id.MustPluginID("hoge~1.0.1") - ibf1 := layer.NewInfoboxField().NewID().Plugin(pid).Extension("a").Property(id.NewPropertyID()).MustBuild() - ibf2 := layer.NewInfoboxField().NewID().Plugin(pid2).Extension("a").Property(id.NewPropertyID()).MustBuild() - ib := layer.NewInfobox([]*layer.InfoboxField{ibf1, ibf2}, id.NewPropertyID()) - l1 := layer.NewItem().NewID().Scene(sid).Property(id.NewPropertyID().Ref()).Plugin(&pid).MustBuild() - l2 := layer.NewItem().NewID().Scene(sid).Property(id.NewPropertyID().Ref()).Plugin(&pid2).MustBuild() - l3 := layer.NewItem().NewID().Scene(sid).Property(id.NewPropertyID().Ref()).Plugin(&pid2).Infobox(ib).MustBuild() - l4 := layer.NewGroup().NewID().Scene(sid).Property(id.NewPropertyID().Ref()).Layers(layer.NewIDList([]id.LayerID{l1.ID(), l2.ID()})).MustBuild() - l5 := layer.NewGroup().NewID().Scene(sid).Layers(layer.NewIDList([]id.LayerID{l3.ID(), l4.ID()})).MustBuild() + sid := layer.NewSceneID() + pid := layer.MustPluginID("hoge~1.0.0") + pid2 := layer.MustPluginID("hoge~1.0.1") + ibf1 := layer.NewInfoboxField().NewID().Plugin(pid).Extension("a").Property(layer.NewPropertyID()).MustBuild() + ibf2 := layer.NewInfoboxField().NewID().Plugin(pid2).Extension("a").Property(layer.NewPropertyID()).MustBuild() + ib := layer.NewInfobox([]*layer.InfoboxField{ibf1, ibf2}, layer.NewPropertyID()) + l1 := layer.NewItem().NewID().Scene(sid).Property(layer.NewPropertyID().Ref()).Plugin(&pid).MustBuild() + l2 := layer.NewItem().NewID().Scene(sid).Property(layer.NewPropertyID().Ref()).Plugin(&pid2).MustBuild() + l3 := layer.NewItem().NewID().Scene(sid).Property(layer.NewPropertyID().Ref()).Plugin(&pid2).Infobox(ib).MustBuild() + l4 := layer.NewGroup().NewID().Scene(sid).Property(layer.NewPropertyID().Ref()).Layers(layer.NewIDList([]layer.ID{l1.ID(), l2.ID()})).MustBuild() + l5 := layer.NewGroup().NewID().Scene(sid).Layers(layer.NewIDList([]layer.ID{l3.ID(), l4.ID()})).MustBuild() res, err := Processor{ LayerLoader: layer.LoaderFrom([]layer.Layer{l1, l2, l3, l4, l5}), @@ -30,10 +29,10 @@ func TestProcessor_UninstallPlugin(t *testing.T) { assert.NoError(t, err) assert.Equal(t, UninstallPluginResult{ ModifiedLayers: layer.List{l3.LayerRef(), l4.LayerRef()}, - RemovedLayers: layer.NewIDList([]id.LayerID{l1.ID()}), - RemovedProperties: []id.PropertyID{ibf1.Property(), *l1.Property()}, + RemovedLayers: layer.NewIDList([]layer.ID{l1.ID()}), + RemovedProperties: []layer.PropertyID{ibf1.Property(), *l1.Property()}, }, res) - assert.Equal(t, layer.NewIDList([]id.LayerID{l2.ID()}), l4.Layers()) + assert.Equal(t, layer.NewIDList([]layer.ID{l2.ID()}), l4.Layers()) assert.Equal(t, []*layer.InfoboxField{ibf2}, ib.Fields()) } diff --git a/pkg/layer/list.go b/pkg/layer/list.go index d6fb1b31..1ce98849 100644 --- a/pkg/layer/list.go +++ b/pkg/layer/list.go @@ -1,11 +1,5 @@ package layer -import ( - "sort" - - "github.com/reearth/reearth-backend/pkg/id" -) - type List []*Layer func (ll List) Last() *Layer { @@ -29,7 +23,7 @@ func (ll List) Pick(il *IDList) List { return layers } -func (ll List) Find(lid id.LayerID) *Layer { +func (ll List) Find(lid ID) *Layer { for _, l := range ll { if l == nil { continue @@ -41,7 +35,7 @@ func (ll List) Find(lid id.LayerID) *Layer { return nil } -func (ll List) FindByDataset(ds id.DatasetID) *Item { +func (ll List) FindByDataset(ds DatasetID) *Item { for _, l := range ll { if li := ItemFromLayerRef(l); li != nil { dsid := li.LinkedDataset() @@ -111,7 +105,7 @@ func (ll List) Map() Map { return m } -func (ll List) Remove(lids ...id.LayerID) List { +func (ll List) Remove(lids ...ID) List { if ll == nil { return nil } @@ -139,7 +133,7 @@ func (ll List) Remove(lids ...id.LayerID) List { type ItemList []*Item -func (ll ItemList) FindByDataset(ds id.DatasetID) *Item { +func (ll ItemList) FindByDataset(ds DatasetID) *Item { for _, li := range ll { dsid := li.LinkedDataset() if dsid != nil && *dsid == ds { @@ -183,7 +177,7 @@ func (ll GroupList) Last() *Group { return ll[len(ll)-1] } -type Map map[id.LayerID]*Layer +type Map map[ID]*Layer func MapFrom(l Layer) Map { return List{&l}.Map() @@ -191,7 +185,7 @@ func MapFrom(l Layer) Map { func (m Map) Add(layers ...*Layer) Map { if m == nil { - m = map[id.LayerID]*Layer{} + m = map[ID]*Layer{} } for _, l := range layers { if l == nil { @@ -254,35 +248,33 @@ func (m Map) Pick(il *IDList) List { return layers } -func (m Map) Layer(i id.LayerID) Layer { +func (m Map) Layer(i ID) Layer { if l := m[i]; l != nil { return *l } return nil } -func (m Map) Item(i id.LayerID) *Item { +func (m Map) Item(i ID) *Item { if l := ToLayerItem(m.Layer(i)); l != nil { return l } return nil } -func (m Map) Group(i id.LayerID) *Group { +func (m Map) Group(i ID) *Group { if l := ToLayerGroup(m.Layer(i)); l != nil { return l } return nil } -func (m Map) Keys() []id.LayerID { - keys := make([]id.LayerID, 0, len(m)) +func (m Map) Keys() []ID { + keys := make([]ID, 0, len(m)) for k := range m { keys = append(keys, k) } - sort.SliceStable(keys, func(i, j int) bool { - return id.ID(keys[i]).Compare(id.ID(keys[j])) < 0 - }) + sortIDs(keys) return keys } diff --git a/pkg/layer/list_test.go b/pkg/layer/list_test.go index 398325dc..067f2455 100644 --- a/pkg/layer/list_test.go +++ b/pkg/layer/list_test.go @@ -3,12 +3,11 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestList_Remove(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() l1 := NewItem().NewID().Scene(sid).MustBuild() l2 := NewItem().NewID().Scene(sid).MustBuild() l3 := NewItem().NewID().Scene(sid).MustBuild() diff --git a/pkg/layer/loader.go b/pkg/layer/loader.go index 0cce4aa7..896c8284 100644 --- a/pkg/layer/loader.go +++ b/pkg/layer/loader.go @@ -3,17 +3,15 @@ package layer import ( "context" "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) -type Loader func(context.Context, ...id.LayerID) (List, error) -type LoaderByScene func(context.Context, id.SceneID) (List, error) +type Loader func(context.Context, ...ID) (List, error) +type LoaderByScene func(context.Context, SceneID) (List, error) var WalkerSkipChildren = errors.New("LAYER_WALKER_SKIP_CHILDREN") func LoaderFrom(data []Layer) Loader { - return func(ctx context.Context, ids ...id.LayerID) (List, error) { + return func(ctx context.Context, ids ...ID) (List, error) { res := make([]*Layer, 0, len(ids)) for _, i := range ids { found := false @@ -32,8 +30,8 @@ func LoaderFrom(data []Layer) Loader { } } -func LoaderFromMap(data map[id.LayerID]Layer) Loader { - return func(ctx context.Context, ids ...id.LayerID) (List, error) { +func LoaderFromMap(data map[ID]Layer) Loader { + return func(ctx context.Context, ids ...ID) (List, error) { res := make([]*Layer, 0, len(ids)) for _, i := range ids { if d, ok := data[i]; ok { @@ -46,9 +44,9 @@ func LoaderFromMap(data map[id.LayerID]Layer) Loader { } } -func (l Loader) Walk(ctx context.Context, walker func(Layer, GroupList) error, init []id.LayerID) error { - var walk func(ids []id.LayerID, parents GroupList) error - walk = func(ids []id.LayerID, parents GroupList) error { +func (l Loader) Walk(ctx context.Context, walker func(Layer, GroupList) error, init []ID) error { + var walk func(ids []ID, parents GroupList) error + walk = func(ids []ID, parents GroupList) error { loaded, err := l(ctx, ids...) if err != nil { return err diff --git a/pkg/layer/loader_test.go b/pkg/layer/loader_test.go index e51b9559..f5a5ad4d 100644 --- a/pkg/layer/loader_test.go +++ b/pkg/layer/loader_test.go @@ -5,17 +5,16 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestLoader_Walk(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() l1 := NewItem().NewID().Scene(sid).MustBuild() l2 := NewItem().NewID().Scene(sid).MustBuild() l3 := NewItem().NewID().Scene(sid).MustBuild() - l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l1.ID(), l2.ID()})).MustBuild() - l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l3.ID(), l4.ID()})).MustBuild() + l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l1.ID(), l2.ID()})).MustBuild() + l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l3.ID(), l4.ID()})).MustBuild() w := LoaderFrom([]Layer{l1, l2, l3, l4, l5}) layers := []Layer{} @@ -24,7 +23,7 @@ func TestLoader_Walk(t *testing.T) { layers = append(layers, l) parents = append(parents, p) return nil - }, []id.LayerID{l5.ID()}) + }, []ID{l5.ID()}) assert.NoError(t, err) assert.Equal(t, []Layer{l5, l3, l4, l1, l2}, layers) @@ -32,12 +31,12 @@ func TestLoader_Walk(t *testing.T) { } func TestLoader_Walk2(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() l1 := NewItem().NewID().Scene(sid).MustBuild() l2 := NewItem().NewID().Scene(sid).MustBuild() l3 := NewItem().NewID().Scene(sid).MustBuild() - l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l1.ID(), l2.ID()})).MustBuild() - l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l3.ID(), l4.ID()})).MustBuild() + l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l1.ID(), l2.ID()})).MustBuild() + l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l3.ID(), l4.ID()})).MustBuild() w := LoaderFrom([]Layer{l1, l2, l3, l4, l5}) layers := []Layer{} @@ -46,7 +45,7 @@ func TestLoader_Walk2(t *testing.T) { layers = append(layers, l) parents = append(parents, p) return WalkerSkipChildren - }, []id.LayerID{l5.ID()}) + }, []ID{l5.ID()}) assert.NoError(t, err) assert.Equal(t, []Layer{l5}, layers) @@ -54,12 +53,12 @@ func TestLoader_Walk2(t *testing.T) { } func TestLoader_Walk3(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() l1 := NewItem().NewID().Scene(sid).MustBuild() l2 := NewItem().NewID().Scene(sid).MustBuild() l3 := NewItem().NewID().Scene(sid).MustBuild() - l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l1.ID(), l2.ID()})).MustBuild() - l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]id.LayerID{l3.ID(), l4.ID()})).MustBuild() + l4 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l1.ID(), l2.ID()})).MustBuild() + l5 := NewGroup().NewID().Scene(sid).Layers(NewIDList([]ID{l3.ID(), l4.ID()})).MustBuild() w := LoaderFrom([]Layer{l1, l2, l3, l4, l5}) err := errors.New("Error") @@ -72,7 +71,7 @@ func TestLoader_Walk3(t *testing.T) { return err } return nil - }, []id.LayerID{l5.ID()}) + }, []ID{l5.ID()}) assert.Same(t, err, err2) assert.Equal(t, []Layer{l5, l3, l4}, layers) diff --git a/pkg/layer/merged.go b/pkg/layer/merged.go index 59f900c8..dfbeb2e8 100644 --- a/pkg/layer/merged.go +++ b/pkg/layer/merged.go @@ -1,20 +1,19 @@ package layer import ( - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" ) // Merged represents a merged layer from two layers type Merged struct { - Original id.LayerID - Parent *id.LayerID + Original ID + Parent *ID Name string - Scene id.SceneID + Scene SceneID Property *property.MergedMetadata Infobox *MergedInfobox - PluginID *id.PluginID - ExtensionID *id.PluginExtensionID + PluginID *PluginID + ExtensionID *PluginExtensionID } // MergedInfobox represents a merged info box from two layers @@ -25,9 +24,9 @@ type MergedInfobox struct { // MergedInfoboxField represents a field of MergedInfobox type MergedInfoboxField struct { - ID id.InfoboxFieldID - Plugin id.PluginID - Extension id.PluginExtensionID + ID InfoboxFieldID + Plugin PluginID + Extension PluginExtensionID Property *property.MergedMetadata } @@ -54,7 +53,7 @@ func Merge(o Layer, p *Group) *Merged { } // MergeInfobox merges two infoboxes -func MergeInfobox(o *Infobox, p *Infobox, linked *id.DatasetID) *MergedInfobox { +func MergeInfobox(o *Infobox, p *Infobox, linked *DatasetID) *MergedInfobox { if o == nil && p == nil { return nil } @@ -92,12 +91,12 @@ func MergeInfobox(o *Infobox, p *Infobox, linked *id.DatasetID) *MergedInfobox { } // Properties returns all property IDs in Merged -func (m *Merged) Properties() []id.PropertyID { +func (m *Merged) Properties() []PropertyID { if m == nil { return nil } - added := map[id.PropertyID]struct{}{} - result := []id.PropertyID{} + added := map[PropertyID]struct{}{} + result := []PropertyID{} if m.Property != nil { if m.Property.Original != nil { t := *m.Property.Original diff --git a/pkg/layer/merged_test.go b/pkg/layer/merged_test.go index d98b9c3a..eadd791c 100644 --- a/pkg/layer/merged_test.go +++ b/pkg/layer/merged_test.go @@ -3,24 +3,23 @@ package layer import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" ) func TestMerge(t *testing.T) { - scene := id.NewSceneID() - dataset1 := id.NewDatasetID() - p := id.MustPluginID("xxx~1.1.1") - e := id.PluginExtensionID("foo") + scene := NewSceneID() + dataset1 := NewDatasetID() + p := MustPluginID("xxx~1.1.1") + e := PluginExtensionID("foo") - itemProperty := id.NewPropertyID() - groupProperty := id.NewPropertyID() - ib1pr := id.NewPropertyID() - ib2pr := id.NewPropertyID() - f1pr := id.NewPropertyID() - f2pr := id.NewPropertyID() - f3pr := id.NewPropertyID() + itemProperty := NewPropertyID() + groupProperty := NewPropertyID() + ib1pr := NewPropertyID() + ib2pr := NewPropertyID() + f1pr := NewPropertyID() + f2pr := NewPropertyID() + f3pr := NewPropertyID() f1 := NewInfoboxField().NewID().Plugin(p).Extension(e).Property(f1pr).MustBuild() f2 := NewInfoboxField().NewID().Plugin(p).Extension(e).Property(f2pr).MustBuild() @@ -317,13 +316,13 @@ func TestMerge(t *testing.T) { } func TestMergedProperties(t *testing.T) { - itemProperty := id.NewPropertyID() - groupProperty := id.NewPropertyID() - ib1pr := id.NewPropertyID() - ib2pr := id.NewPropertyID() - f1pr := id.NewPropertyID() - f2pr := id.NewPropertyID() - f3pr := id.NewPropertyID() + itemProperty := NewPropertyID() + groupProperty := NewPropertyID() + ib1pr := NewPropertyID() + ib2pr := NewPropertyID() + f1pr := NewPropertyID() + f2pr := NewPropertyID() + f3pr := NewPropertyID() merged := &Merged{ Property: &property.MergedMetadata{ @@ -352,7 +351,7 @@ func TestMergedProperties(t *testing.T) { }, } - assert.Equal(t, []id.PropertyID{ + assert.Equal(t, []PropertyID{ itemProperty, groupProperty, ib1pr, ib2pr, f1pr, f2pr, f3pr, }, merged.Properties()) } diff --git a/pkg/layer/merging/merged.go b/pkg/layer/merging/merged.go index c9ed65df..3111b172 100644 --- a/pkg/layer/merging/merged.go +++ b/pkg/layer/merging/merged.go @@ -1,7 +1,6 @@ package merging import ( - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) @@ -13,7 +12,7 @@ var ( type MergedLayer interface { Common() *MergedLayerCommon - AllDatasets() []id.DatasetID + AllDatasets() []layer.DatasetID } type MergedLayerGroup struct { @@ -56,15 +55,15 @@ func (l *MergedLayerItem) Common() *MergedLayerCommon { return &l.MergedLayerCommon } -func (l *MergedLayerCommon) Datasets() []id.DatasetID { +func (l *MergedLayerCommon) Datasets() []layer.DatasetID { return l.datasetIDSet().All() } -func (l *MergedLayerCommon) datasetIDSet() *id.DatasetIDSet { +func (l *MergedLayerCommon) datasetIDSet() *layer.DatasetIDSet { if l == nil { return nil } - res := id.NewDatasetIDSet() + res := layer.NewDatasetIDSet() res.Add(l.Property.Datasets()...) res.Add(l.Infobox.Property.Datasets()...) for _, f := range l.Infobox.Fields { @@ -73,18 +72,18 @@ func (l *MergedLayerCommon) datasetIDSet() *id.DatasetIDSet { return res } -func (l *MergedLayerItem) AllDatasets() []id.DatasetID { +func (l *MergedLayerItem) AllDatasets() []layer.DatasetID { if l == nil { return nil } return l.Datasets() } -func (l *MergedLayerGroup) AllDatasets() []id.DatasetID { +func (l *MergedLayerGroup) AllDatasets() []layer.DatasetID { return l.allDatasetIDSet().All() } -func (l *MergedLayerGroup) allDatasetIDSet() *id.DatasetIDSet { +func (l *MergedLayerGroup) allDatasetIDSet() *layer.DatasetIDSet { if l == nil { return nil } diff --git a/pkg/layer/merging/merger.go b/pkg/layer/merging/merger.go index c2991971..41a9a0bd 100644 --- a/pkg/layer/merging/merger.go +++ b/pkg/layer/merging/merger.go @@ -3,7 +3,6 @@ package merging import ( "context" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" ) @@ -57,7 +56,7 @@ func (m *Merger) MergeLayer(ctx context.Context, l layer.Layer, parent *layer.Gr return nil, nil } -func (m *Merger) MergeLayerFromID(ctx context.Context, i id.LayerID, parent *layer.Group) (MergedLayer, error) { +func (m *Merger) MergeLayerFromID(ctx context.Context, i layer.ID, parent *layer.Group) (MergedLayer, error) { l, err := m.LayerLoader(ctx, i) if err != nil { return nil, err diff --git a/pkg/layer/merging/merger_test.go b/pkg/layer/merging/merger_test.go index cc9263dc..52c81b0b 100644 --- a/pkg/layer/merging/merger_test.go +++ b/pkg/layer/merging/merger_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/stretchr/testify/assert" @@ -12,19 +11,19 @@ import ( func TestMergeLayer(t *testing.T) { // ids - scene := id.NewSceneID() - dataset1 := id.NewDatasetID() - ps := id.MustPropertySchemaID("xxx~1.1.1/aa") - p := id.MustPluginID("xxx~1.1.1") - e := id.PluginExtensionID("foo") - itemProperty := id.NewPropertyID() - groupProperty := id.NewPropertyID() - ib1pr := id.NewPropertyID() - ib2pr := id.NewPropertyID() - fpr := id.NewPropertyID() - l1 := id.NewLayerID() - l2 := id.NewLayerID() - l1if1 := id.NewInfoboxFieldID() + scene := layer.NewSceneID() + dataset1 := layer.NewDatasetID() + ps := property.MustSchemaID("xxx~1.1.1/aa") + p := layer.MustPluginID("xxx~1.1.1") + e := layer.PluginExtensionID("foo") + itemProperty := property.NewID() + groupProperty := property.NewID() + ib1pr := property.NewID() + ib2pr := property.NewID() + fpr := property.NewID() + l1 := layer.NewID() + l2 := layer.NewID() + l1if1 := layer.NewInfoboxFieldID() // property loader ploader := property.LoaderFrom([]*property.Property{ @@ -51,7 +50,7 @@ func TestMergeLayer(t *testing.T) { Infobox(layer.NewInfobox([]*layer.InfoboxField{ layer.NewInfoboxField().ID(l1if1).Plugin(p).Extension(e).Property(fpr).MustBuild(), }, ib2pr)). - Layers(layer.NewIDList([]id.LayerID{l1})). + Layers(layer.NewIDList([]layer.ID{l1})). MustBuild(), }) diff --git a/pkg/layer/tag.go b/pkg/layer/tag.go index d3446473..715886f4 100644 --- a/pkg/layer/tag.go +++ b/pkg/layer/tag.go @@ -1,11 +1,5 @@ package layer -import "github.com/reearth/reearth-backend/pkg/id" - -type TagID = id.TagID - -var NewTagID = id.NewTagID - type TagList struct { tags []Tag } diff --git a/pkg/plugin/builder.go b/pkg/plugin/builder.go index 44e45910..4bdb9c3f 100644 --- a/pkg/plugin/builder.go +++ b/pkg/plugin/builder.go @@ -2,7 +2,6 @@ package plugin import ( "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) type Builder struct { @@ -26,7 +25,7 @@ func (b *Builder) MustBuild() *Plugin { return p } -func (b *Builder) ID(id id.PluginID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.p.id = id return b } @@ -58,8 +57,8 @@ func (b *Builder) Extensions(extensions []*Extension) *Builder { return b } - b.p.extensions = make(map[id.PluginExtensionID]*Extension, len(extensions)) - b.p.extensionOrder = make([]id.PluginExtensionID, 0, len(extensions)) + b.p.extensions = make(map[ExtensionID]*Extension, len(extensions)) + b.p.extensionOrder = make([]ExtensionID, 0, len(extensions)) for _, e := range extensions { b.p.extensions[e.ID()] = e b.p.extensionOrder = append(b.p.extensionOrder, e.ID()) @@ -67,7 +66,7 @@ func (b *Builder) Extensions(extensions []*Extension) *Builder { return b } -func (b *Builder) Schema(schema *id.PropertySchemaID) *Builder { +func (b *Builder) Schema(schema *PropertySchemaID) *Builder { if schema == nil { b.p.schema = nil } else { diff --git a/pkg/plugin/builder_test.go b/pkg/plugin/builder_test.go index e4b5e94b..a773130f 100644 --- a/pkg/plugin/builder_test.go +++ b/pkg/plugin/builder_test.go @@ -5,14 +5,13 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestBuilder_ID(t *testing.T) { var b = New() - res := b.ID(id.MustPluginID("aaa~1.1.1")).MustBuild() - assert.Equal(t, id.MustPluginID("aaa~1.1.1"), res.ID()) + res := b.ID(MustID("aaa~1.1.1")).MustBuild() + assert.Equal(t, MustID("aaa~1.1.1"), res.ID()) } func TestBuilder_Name(t *testing.T) { @@ -36,7 +35,7 @@ func TestBuilder_Description(t *testing.T) { func TestBuilder_Schema(t *testing.T) { testCases := []struct { name string - sid, expected *id.PropertySchemaID + sid, expected *PropertySchemaID }{ { name: "nil schema", @@ -45,8 +44,8 @@ func TestBuilder_Schema(t *testing.T) { }, { name: "build schema", - sid: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), - expected: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + sid: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + expected: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), }, } for _, tc := range testCases { @@ -78,15 +77,15 @@ func TestBuilder_RepositoryURL(t *testing.T) { func TestBuilder_Build(t *testing.T) { testCases := []struct { name, author, repositoryURL string - id id.PluginID + id ID pname, description i18n.String ext []*Extension - schema *id.PropertySchemaID + schema *PropertySchemaID expected *Plugin err error // skip for now as error is always nil }{ { - id: id.MustPluginID("hoge~0.1.0"), + id: MustID("hoge~0.1.0"), name: "success build new plugin", author: "aaa", repositoryURL: "uuu", @@ -96,19 +95,19 @@ func TestBuilder_Build(t *testing.T) { NewExtension().ID("xxx").MustBuild(), NewExtension().ID("yyy").MustBuild(), }, - schema: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + schema: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), expected: &Plugin{ - id: id.MustPluginID("hoge~0.1.0"), + id: MustID("hoge~0.1.0"), name: i18n.StringFrom("nnn"), author: "aaa", description: i18n.StringFrom("ddd"), repositoryURL: "uuu", - extensions: map[id.PluginExtensionID]*Extension{ - id.PluginExtensionID("xxx"): NewExtension().ID("xxx").MustBuild(), - id.PluginExtensionID("yyy"): NewExtension().ID("yyy").MustBuild(), + extensions: map[ExtensionID]*Extension{ + ExtensionID("xxx"): NewExtension().ID("xxx").MustBuild(), + ExtensionID("yyy"): NewExtension().ID("yyy").MustBuild(), }, - extensionOrder: []id.PluginExtensionID{id.PluginExtensionID("xxx"), id.PluginExtensionID("yyy")}, - schema: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + extensionOrder: []ExtensionID{ExtensionID("xxx"), ExtensionID("yyy")}, + schema: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), }, }, } @@ -137,14 +136,14 @@ func TestBuilder_Build(t *testing.T) { func TestBuilder_MustBuild(t *testing.T) { testCases := []struct { name, author, repositoryURL string - id id.PluginID + id ID pname, description i18n.String ext []*Extension - schema *id.PropertySchemaID + schema *PropertySchemaID expected *Plugin }{ { - id: id.MustPluginID("hoge~0.1.0"), + id: MustID("hoge~0.1.0"), name: "success build new plugin", author: "aaa", repositoryURL: "uuu", @@ -154,19 +153,19 @@ func TestBuilder_MustBuild(t *testing.T) { NewExtension().ID("xxx").MustBuild(), NewExtension().ID("yyy").MustBuild(), }, - schema: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + schema: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), expected: &Plugin{ - id: id.MustPluginID("hoge~0.1.0"), + id: MustID("hoge~0.1.0"), name: i18n.StringFrom("nnn"), author: "aaa", description: i18n.StringFrom("ddd"), repositoryURL: "uuu", - extensions: map[id.PluginExtensionID]*Extension{ - id.PluginExtensionID("xxx"): NewExtension().ID("xxx").MustBuild(), - id.PluginExtensionID("yyy"): NewExtension().ID("yyy").MustBuild(), + extensions: map[ExtensionID]*Extension{ + ExtensionID("xxx"): NewExtension().ID("xxx").MustBuild(), + ExtensionID("yyy"): NewExtension().ID("yyy").MustBuild(), }, - extensionOrder: []id.PluginExtensionID{id.PluginExtensionID("xxx"), id.PluginExtensionID("yyy")}, - schema: id.MustPropertySchemaID("hoge~0.1.0/fff").Ref(), + extensionOrder: []ExtensionID{ExtensionID("xxx"), ExtensionID("yyy")}, + schema: MustPropertySchemaID("hoge~0.1.0/fff").Ref(), }, }, } diff --git a/pkg/plugin/extension.go b/pkg/plugin/extension.go index 4c279500..4578ad30 100644 --- a/pkg/plugin/extension.go +++ b/pkg/plugin/extension.go @@ -4,7 +4,6 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" ) @@ -21,18 +20,18 @@ var ( ) type Extension struct { - id id.PluginExtensionID + id ExtensionID extensionType ExtensionType name i18n.String description i18n.String icon string - schema id.PropertySchemaID + schema PropertySchemaID visualizer visualizer.Visualizer singleOnly bool widgetLayout *WidgetLayout } -func (w *Extension) ID() id.PluginExtensionID { +func (w *Extension) ID() ExtensionID { return w.id } @@ -52,7 +51,7 @@ func (w *Extension) Icon() string { return w.icon } -func (w *Extension) Schema() id.PropertySchemaID { +func (w *Extension) Schema() PropertySchemaID { return w.schema } diff --git a/pkg/plugin/extension_builder.go b/pkg/plugin/extension_builder.go index 65f3e7d2..bd8781ff 100644 --- a/pkg/plugin/extension_builder.go +++ b/pkg/plugin/extension_builder.go @@ -4,7 +4,6 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" ) @@ -19,7 +18,7 @@ func NewExtension() *ExtensionBuilder { func (b *ExtensionBuilder) Build() (*Extension, error) { if string(b.p.id) == "" { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if !b.s { if b.p.extensionType == ExtensionTypeVisualizer || b.p.extensionType == ExtensionTypeInfobox { @@ -37,7 +36,7 @@ func (b *ExtensionBuilder) MustBuild() *Extension { return p } -func (b *ExtensionBuilder) ID(id id.PluginExtensionID) *ExtensionBuilder { +func (b *ExtensionBuilder) ID(id ExtensionID) *ExtensionBuilder { b.p.id = id return b } @@ -62,7 +61,7 @@ func (b *ExtensionBuilder) Icon(icon string) *ExtensionBuilder { return b } -func (b *ExtensionBuilder) Schema(schema id.PropertySchemaID) *ExtensionBuilder { +func (b *ExtensionBuilder) Schema(schema PropertySchemaID) *ExtensionBuilder { b.p.schema = schema return b } diff --git a/pkg/plugin/extension_builder_test.go b/pkg/plugin/extension_builder_test.go index 8da82fe2..d281ac02 100644 --- a/pkg/plugin/extension_builder_test.go +++ b/pkg/plugin/extension_builder_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" "github.com/stretchr/testify/assert" ) @@ -24,7 +23,7 @@ func TestExtensionBuilder_Description(t *testing.T) { func TestExtensionBuilder_ID(t *testing.T) { var b = NewExtension() res := b.ID("xxx").MustBuild() - assert.Equal(t, id.PluginExtensionID("xxx"), res.ID()) + assert.Equal(t, ExtensionID("xxx"), res.ID()) } func TestExtensionBuilder_Type(t *testing.T) { @@ -47,8 +46,8 @@ func TestExtensionBuilder_SingleOnly(t *testing.T) { func TestExtensionBuilder_Schema(t *testing.T) { var b = NewExtension() - res := b.ID("xxx").Schema(id.MustPropertySchemaID("hoge~0.1.0/fff")).MustBuild() - assert.Equal(t, id.MustPropertySchemaID("hoge~0.1.0/fff"), res.Schema()) + res := b.ID("xxx").Schema(MustPropertySchemaID("hoge~0.1.0/fff")).MustBuild() + assert.Equal(t, MustPropertySchemaID("hoge~0.1.0/fff"), res.Schema()) } func TestExtensionBuilder_Visualizer(t *testing.T) { @@ -69,12 +68,12 @@ func TestExtensionBuilder_WidgetLayout(t *testing.T) { func TestExtensionBuilder_Build(t *testing.T) { testCases := []struct { name, icon string - id id.PluginExtensionID + id ExtensionID extensionType ExtensionType system bool ename i18n.String description i18n.String - schema id.PropertySchemaID + schema PropertySchemaID visualizer visualizer.Visualizer widgetLayout *WidgetLayout expected *Extension @@ -88,7 +87,7 @@ func TestExtensionBuilder_Build(t *testing.T) { system: false, ename: i18n.StringFrom("nnn"), description: i18n.StringFrom("ddd"), - schema: id.MustPropertySchemaID("foo~1.1.1/hhh"), + schema: MustPropertySchemaID("foo~1.1.1/hhh"), visualizer: "vvv", widgetLayout: NewWidgetLayout( false, false, true, false, &WidgetLocation{ @@ -103,7 +102,7 @@ func TestExtensionBuilder_Build(t *testing.T) { name: i18n.StringFrom("nnn"), description: i18n.StringFrom("ddd"), icon: "ttt", - schema: id.MustPropertySchemaID("foo~1.1.1/hhh"), + schema: MustPropertySchemaID("foo~1.1.1/hhh"), visualizer: "vvv", widgetLayout: NewWidgetLayout( false, false, true, false, &WidgetLocation{ @@ -118,16 +117,16 @@ func TestExtensionBuilder_Build(t *testing.T) { { name: "fail not system type visualizer", extensionType: ExtensionTypeVisualizer, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { name: "fail not system type infobox", extensionType: ExtensionTypeInfobox, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { name: "fail nil id", - err: id.ErrInvalidID, + err: ErrInvalidID, }, } @@ -158,12 +157,12 @@ func TestExtensionBuilder_Build(t *testing.T) { func TestExtensionBuilder_MustBuild(t *testing.T) { testCases := []struct { name, icon string - id id.PluginExtensionID + id ExtensionID extensionType ExtensionType system bool ename i18n.String description i18n.String - schema id.PropertySchemaID + schema PropertySchemaID visualizer visualizer.Visualizer widgetLayout *WidgetLayout singleOnly bool @@ -177,7 +176,7 @@ func TestExtensionBuilder_MustBuild(t *testing.T) { system: false, ename: i18n.StringFrom("nnn"), description: i18n.StringFrom("ddd"), - schema: id.MustPropertySchemaID("foo~1.1.1/hhh"), + schema: MustPropertySchemaID("foo~1.1.1/hhh"), visualizer: "vvv", singleOnly: true, widgetLayout: NewWidgetLayout( @@ -192,7 +191,7 @@ func TestExtensionBuilder_MustBuild(t *testing.T) { name: i18n.StringFrom("nnn"), description: i18n.StringFrom("ddd"), icon: "ttt", - schema: id.MustPropertySchemaID("foo~1.1.1/hhh"), + schema: MustPropertySchemaID("foo~1.1.1/hhh"), visualizer: "vvv", singleOnly: true, widgetLayout: NewWidgetLayout( diff --git a/pkg/plugin/extension_test.go b/pkg/plugin/extension_test.go index ff34bd8a..1c446a4b 100644 --- a/pkg/plugin/extension_test.go +++ b/pkg/plugin/extension_test.go @@ -4,19 +4,18 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" "github.com/stretchr/testify/assert" ) func TestExtension(t *testing.T) { expected := struct { - ID id.PluginExtensionID + ID ExtensionID Type ExtensionType Name i18n.String Description i18n.String Icon string - Schema id.PropertySchemaID + Schema PropertySchemaID Visualizer visualizer.Visualizer SingleOnly bool WidgetLayout *WidgetLayout @@ -26,7 +25,7 @@ func TestExtension(t *testing.T) { Name: i18n.StringFrom("aaa"), Description: i18n.StringFrom("ddd"), Icon: "test", - Schema: id.MustPropertySchemaID("hoge~0.1.0/fff"), + Schema: MustPropertySchemaID("hoge~0.1.0/fff"), Visualizer: "vvv", SingleOnly: true, WidgetLayout: NewWidgetLayout(false, false, true, false, nil).Ref(), @@ -36,7 +35,7 @@ func TestExtension(t *testing.T) { ID("xxx"). Name(i18n.StringFrom("aaa")). Description(i18n.StringFrom("ddd")). - Schema(id.MustPropertySchemaID("hoge~0.1.0/fff")). + Schema(MustPropertySchemaID("hoge~0.1.0/fff")). Icon("test"). WidgetLayout(NewWidgetLayout(false, false, true, false, nil).Ref()). Visualizer("vvv"). diff --git a/pkg/plugin/id.go b/pkg/plugin/id.go new file mode 100644 index 00000000..ff0220ca --- /dev/null +++ b/pkg/plugin/id.go @@ -0,0 +1,31 @@ +package plugin + +import "github.com/reearth/reearth-backend/pkg/id" + +type ID = id.PluginID +type ExtensionID = id.PluginExtensionID +type PropertySchemaID = id.PropertySchemaID +type SceneID = id.SceneID + +var NewID = id.NewPluginID +var NewSceneID = id.NewSceneID + +var MustID = id.MustPluginID +var MustSceneID = id.MustSceneID +var MustPropertySchemaID = id.MustPropertySchemaID + +var IDFrom = id.PluginIDFrom +var SceneIDFrom = id.SceneIDFrom +var PropertySchemaIDFrom = id.PropertySchemaIDFrom + +var IDFromRef = id.PluginIDFromRef +var ExtensionIDFromRef = id.PluginExtensionIDFromRef +var SceneIDFromRef = id.SceneIDFromRef +var PropertySchemaIDFromRef = id.PropertySchemaIDFromRef + +var SceneIDFromRefID = id.SceneIDFromRefID + +var PropertySchemaIDFromExtension = id.PropertySchemaIDFromExtension + +var OfficialPluginID = id.OfficialPluginID +var ErrInvalidID = id.ErrInvalidID diff --git a/pkg/plugin/loader.go b/pkg/plugin/loader.go index add41da5..628b889b 100644 --- a/pkg/plugin/loader.go +++ b/pkg/plugin/loader.go @@ -2,8 +2,6 @@ package plugin import ( "context" - - "github.com/reearth/reearth-backend/pkg/id" ) -type Loader func(context.Context, []id.PluginID, []id.SceneID) ([]*Plugin, error) +type Loader func(context.Context, []ID, []SceneID) ([]*Plugin, error) diff --git a/pkg/plugin/manifest/convert.go b/pkg/plugin/manifest/convert.go index 4e9c5421..de85ae1e 100644 --- a/pkg/plugin/manifest/convert.go +++ b/pkg/plugin/manifest/convert.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/rerror" @@ -14,13 +13,13 @@ import ( var errInvalidManifestWith = rerror.With(ErrInvalidManifest) -func (i *Root) manifest(sid *id.SceneID) (*Manifest, error) { - var pid id.PluginID +func (i *Root) manifest(sid *plugin.SceneID) (*Manifest, error) { + var pid plugin.ID var err error - if i.System && string(i.ID) == id.OfficialPluginID.Name() { - pid = id.OfficialPluginID + if i.System && string(i.ID) == plugin.OfficialPluginID.Name() { + pid = plugin.OfficialPluginID } else { - pid, err = id.NewPluginID(string(i.ID), i.Version, sid) + pid, err = plugin.NewID(string(i.ID), i.Version, sid) if err != nil { return nil, errInvalidManifestWith(fmt.Errorf("invalid plugin id: %s %s %s", i.ID, i.Version, sid)) } @@ -82,7 +81,7 @@ func (i *Root) manifest(sid *id.SceneID) (*Manifest, error) { }, nil } -func (i Extension) extension(pluginID id.PluginID, sys bool) (*plugin.Extension, *property.Schema, error) { +func (i Extension) extension(pluginID plugin.ID, sys bool) (*plugin.Extension, *property.Schema, error) { eid := string(i.ID) schema, err := i.Schema.schema(pluginID, eid) if err != nil { @@ -136,7 +135,7 @@ func (i Extension) extension(pluginID id.PluginID, sys bool) (*plugin.Extension, } ext, err := plugin.NewExtension(). - ID(id.PluginExtensionID(eid)). + ID(plugin.ExtensionID(eid)). Name(i18n.StringFrom(i.Name)). Description(i18n.StringFrom(desc)). Visualizer(viz). @@ -185,8 +184,8 @@ func (l *WidgetLayout) layout() *plugin.WidgetLayout { return plugin.NewWidgetLayout(horizontallyExtendable, verticallyExtendable, extended, l.Floating, dl).Ref() } -func (i *PropertySchema) schema(pluginID id.PluginID, idstr string) (*property.Schema, error) { - psid, err := id.PropertySchemaIDFrom(pluginID.String() + "/" + idstr) +func (i *PropertySchema) schema(pluginID plugin.ID, idstr string) (*property.Schema, error) { + psid, err := property.SchemaIDFrom(pluginID.String() + "/" + idstr) if err != nil { return nil, fmt.Errorf("invalid id: %s", pluginID.String()+"/"+idstr) } @@ -235,17 +234,17 @@ func (p *PropertyPointer) pointer() *property.Pointer { return nil } return property.NewPointer( - id.PropertySchemaGroupIDFrom(&p.SchemaGroupID), + property.SchemaGroupIDFrom(&p.SchemaGroupID), nil, - id.PropertySchemaFieldIDFrom(&p.FieldID), + property.FieldIDFrom(&p.FieldID), ) } -func (i PropertySchemaGroup) schemaGroup(sid id.PropertySchemaID) (*property.SchemaGroup, error) { +func (i PropertySchemaGroup) schemaGroup(sid property.SchemaID) (*property.SchemaGroup, error) { title := i.Title - var representativeField *id.PropertySchemaFieldID + var representativeField *property.FieldID if i.RepresentativeField != nil { - representativeField = id.PropertySchemaFieldID(*i.RepresentativeField).Ref() + representativeField = property.FieldID(*i.RepresentativeField).Ref() } // fields @@ -259,7 +258,7 @@ func (i PropertySchemaGroup) schemaGroup(sid id.PropertySchemaID) (*property.Sch } return property.NewSchemaGroup(). - ID(id.PropertySchemaGroupID(i.ID)). + ID(property.SchemaGroupID(i.ID)). Schema(sid). IsList(i.List). Fields(fields). @@ -274,7 +273,7 @@ func (o *PropertyCondition) condition() *property.Condition { return nil } return &property.Condition{ - Field: id.PropertySchemaFieldID(o.Field), + Field: property.FieldID(o.Field), Value: toValue(o.Value, o.Type), } } @@ -311,7 +310,7 @@ func (i PropertySchemaField) schemaField() (*property.SchemaField, error) { } f, err := property.NewSchemaField(). - ID(id.PropertySchemaFieldID(i.ID)). + ID(property.FieldID(i.ID)). Name(i18n.StringFrom(title)). Description(i18n.StringFrom(desc)). Type(t). diff --git a/pkg/plugin/manifest/convert_test.go b/pkg/plugin/manifest/convert_test.go index 73d04540..b036b322 100644 --- a/pkg/plugin/manifest/convert_test.go +++ b/pkg/plugin/manifest/convert_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/rerror" @@ -80,7 +79,7 @@ func TestManifest(t *testing.T) { Version: "1.1.1", }, expected: &Manifest{ - Plugin: plugin.New().ID(id.OfficialPluginID).Name(i18n.StringFrom("aaa")).Extensions([]*plugin.Extension{plugin.NewExtension().ID("cesium").Visualizer("cesium").Type("visualizer").System(true).MustBuild()}).MustBuild(), + Plugin: plugin.New().ID(plugin.OfficialPluginID).Name(i18n.StringFrom("aaa")).Extensions([]*plugin.Extension{plugin.NewExtension().ID("cesium").Visualizer("cesium").Type("visualizer").System(true).MustBuild()}).MustBuild(), ExtensionSchema: nil, Schema: nil, }, @@ -93,7 +92,7 @@ func TestManifest(t *testing.T) { System: true, }, expected: &Manifest{ - Plugin: plugin.New().ID(id.OfficialPluginID).Name(i18n.StringFrom("reearth")).MustBuild(), + Plugin: plugin.New().ID(plugin.OfficialPluginID).Name(i18n.StringFrom("reearth")).MustBuild(), ExtensionSchema: nil, Schema: nil, }, @@ -118,7 +117,7 @@ func TestManifest(t *testing.T) { Version: "1.1.1", }, expected: &Manifest{ - Plugin: plugin.New().ID(id.OfficialPluginID).Name(i18n.StringFrom("aaa")).Extensions([]*plugin.Extension{plugin.NewExtension().ID("cesium").Visualizer("cesium").Type("visualizer").System(true).MustBuild()}).MustBuild(), + Plugin: plugin.New().ID(plugin.OfficialPluginID).Name(i18n.StringFrom("aaa")).Extensions([]*plugin.Extension{plugin.NewExtension().ID("cesium").Visualizer("cesium").Type("visualizer").System(true).MustBuild()}).MustBuild(), ExtensionSchema: nil, Schema: nil, }, @@ -132,7 +131,7 @@ func TestManifest(t *testing.T) { System: false, }, expected: &Manifest{ - Plugin: plugin.New().ID(id.OfficialPluginID).Name(i18n.StringFrom("reearth")).MustBuild(), + Plugin: plugin.New().ID(plugin.OfficialPluginID).Name(i18n.StringFrom("reearth")).MustBuild(), }, err: "invalid manifest: invalid plugin id: ", }, @@ -164,7 +163,7 @@ func TestExtension(t *testing.T) { name string ext Extension sys bool - pid id.PluginID + pid plugin.ID expectedPE *plugin.Extension expectedPS *property.Schema err string @@ -181,9 +180,9 @@ func TestExtension(t *testing.T) { Visualizer: &cesium, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("cesium").Type(plugin.ExtensionTypeVisualizer).System(true).Description(i18n.StringFrom("ddd")).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "primitive", @@ -196,9 +195,9 @@ func TestExtension(t *testing.T) { Visualizer: &cesium, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("cesium").Type(plugin.ExtensionTypePrimitive).System(true).Description(i18n.StringFrom("ddd")).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "widget", @@ -211,9 +210,9 @@ func TestExtension(t *testing.T) { SingleOnly: &tr, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("").Type(plugin.ExtensionTypeWidget).System(true).Description(i18n.StringFrom("ddd")).SingleOnly(true).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "block", @@ -225,9 +224,9 @@ func TestExtension(t *testing.T) { Type: "block", }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("").Type(plugin.ExtensionTypeBlock).System(true).Description(i18n.StringFrom("ddd")).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "infobox", @@ -240,9 +239,9 @@ func TestExtension(t *testing.T) { Visualizer: &cesium, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("cesium").Type(plugin.ExtensionTypeInfobox).System(true).Description(i18n.StringFrom("ddd")).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "cluster", @@ -255,9 +254,9 @@ func TestExtension(t *testing.T) { Visualizer: &cesium, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: plugin.NewExtension().ID("cesium").Name(i18n.StringFrom("Cesium")).Visualizer("cesium").Type(plugin.ExtensionTypeCluster).System(true).Description(i18n.StringFrom("ddd")).MustBuild(), - expectedPS: property.NewSchema().ID(id.MustPropertySchemaID("reearth/cesium")).MustBuild(), + expectedPS: property.NewSchema().ID(property.MustSchemaID("reearth/cesium")).MustBuild(), }, { name: "empty visualizer", @@ -270,7 +269,7 @@ func TestExtension(t *testing.T) { Visualizer: &es, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: nil, expectedPS: nil, err: "visualizer missing", @@ -286,7 +285,7 @@ func TestExtension(t *testing.T) { Visualizer: nil, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: nil, expectedPS: nil, err: "visualizer missing", @@ -302,7 +301,7 @@ func TestExtension(t *testing.T) { Visualizer: &cesium, }, sys: true, - pid: id.OfficialPluginID, + pid: plugin.OfficialPluginID, expectedPE: nil, expectedPS: nil, err: "type missing", @@ -355,7 +354,7 @@ func TestPointer(t *testing.T) { FieldID: "xxx", SchemaGroupID: "aaa", }, - expected: property.NewPointer(id.PropertySchemaGroupIDFrom(&sg), nil, id.PropertySchemaFieldIDFrom(&f)), + expected: property.NewPointer(property.SchemaGroupIDFrom(&sg), nil, property.FieldIDFrom(&f)), }, } for _, tc := range testCases { @@ -427,8 +426,8 @@ func TestLinkable(t *testing.T) { }, }, expected: property.LinkableFields{ - LatLng: property.NewPointer(id.PropertySchemaGroupIDFrom(&d), nil, id.PropertySchemaFieldIDFrom(&l)), - URL: property.NewPointer(id.PropertySchemaGroupIDFrom(&d), nil, id.PropertySchemaFieldIDFrom(&u)), + LatLng: property.NewPointer(property.SchemaGroupIDFrom(&d), nil, property.FieldIDFrom(&l)), + URL: property.NewPointer(property.SchemaGroupIDFrom(&d), nil, property.FieldIDFrom(&u)), }, }, } @@ -446,7 +445,7 @@ func TestSchema(t *testing.T) { testCases := []struct { name, psid string ps *PropertySchema - pid id.PluginID + pid plugin.ID expected *property.Schema err string }{ @@ -458,7 +457,7 @@ func TestSchema(t *testing.T) { Linkable: nil, Version: 0, }, - pid: id.MustPluginID("aaa~1.1.1"), + pid: plugin.MustID("aaa~1.1.1"), expected: nil, err: "invalid id: aaa~1.1.1/@", }, @@ -466,8 +465,8 @@ func TestSchema(t *testing.T) { name: "success nil PropertySchema", psid: "marker", ps: nil, - pid: id.OfficialPluginID, - expected: property.NewSchema().ID(id.MustPropertySchemaID("reearth/marker")).MustBuild(), + pid: plugin.OfficialPluginID, + expected: property.NewSchema().ID(property.MustSchemaID("reearth/marker")).MustBuild(), }, { name: "success ", @@ -497,8 +496,8 @@ func TestSchema(t *testing.T) { Linkable: nil, Version: 0, }, - pid: id.OfficialPluginID, - expected: property.NewSchema().ID(id.MustPropertySchemaID("reearth/marker")).Groups([]*property.SchemaGroup{property.NewSchemaGroup().ID("default").Schema(id.MustPropertySchemaID("reearth/cesium")).Fields([]*property.SchemaField{property.NewSchemaField().ID("location").Type(property.ValueTypeLatLng).MustBuild()}).MustBuild()}).MustBuild(), + pid: plugin.OfficialPluginID, + expected: property.NewSchema().ID(property.MustSchemaID("reearth/marker")).Groups([]*property.SchemaGroup{property.NewSchemaGroup().ID("default").Schema(property.MustSchemaID("reearth/cesium")).Fields([]*property.SchemaField{property.NewSchemaField().ID("location").Type(property.ValueTypeLatLng).MustBuild()}).MustBuild()}).MustBuild(), }, } for _, tc := range testCases { @@ -527,7 +526,7 @@ func TestSchemaGroup(t *testing.T) { testCases := []struct { name string psg PropertySchemaGroup - sid id.PropertySchemaID + sid property.SchemaID expected *property.SchemaGroup err string }{ @@ -554,8 +553,8 @@ func TestSchemaGroup(t *testing.T) { List: false, Title: "marker", }, - sid: id.MustPropertySchemaID("reearth/cesium"), - expected: property.NewSchemaGroup().ID("default").Title(i18n.StringFrom("marker")).Title(i18n.StringFrom(str)).Schema(id.MustPropertySchemaID("reearth/cesium")).Fields([]*property.SchemaField{property.NewSchemaField().ID("location").Type(property.ValueTypeLatLng).MustBuild()}).MustBuild(), + sid: property.MustSchemaID("reearth/cesium"), + expected: property.NewSchemaGroup().ID("default").Title(i18n.StringFrom("marker")).Title(i18n.StringFrom(str)).Schema(property.MustSchemaID("reearth/cesium")).Fields([]*property.SchemaField{property.NewSchemaField().ID("location").Type(property.ValueTypeLatLng).MustBuild()}).MustBuild(), }, { name: "fail invalid schema field", @@ -580,7 +579,7 @@ func TestSchemaGroup(t *testing.T) { List: false, Title: "marker", }, - sid: id.MustPropertySchemaID("reearth/cesium"), + sid: property.MustSchemaID("reearth/cesium"), expected: nil, err: "field (location): invalid value type: xx", }, diff --git a/pkg/plugin/manifest/parser.go b/pkg/plugin/manifest/parser.go index 8f059bb7..83c9f1ee 100644 --- a/pkg/plugin/manifest/parser.go +++ b/pkg/plugin/manifest/parser.go @@ -7,7 +7,7 @@ import ( "io" "github.com/goccy/go-yaml" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/plugin" ) var ( @@ -16,7 +16,7 @@ var ( ErrSystemManifest = errors.New("cannot build system manifest") ) -func Parse(source io.Reader, scene *id.SceneID) (*Manifest, error) { +func Parse(source io.Reader, scene *plugin.SceneID) (*Manifest, error) { root := Root{} if err := yaml.NewDecoder(source).Decode(&root); err != nil { return nil, ErrFailedToParseManifest @@ -34,7 +34,7 @@ func Parse(source io.Reader, scene *id.SceneID) (*Manifest, error) { return manifest, nil } -func ParseSystemFromBytes(source []byte, scene *id.SceneID) (*Manifest, error) { +func ParseSystemFromBytes(source []byte, scene *plugin.SceneID) (*Manifest, error) { root := Root{} if err := yaml.Unmarshal(source, &root); err != nil { return nil, ErrFailedToParseManifest @@ -49,7 +49,7 @@ func ParseSystemFromBytes(source []byte, scene *id.SceneID) (*Manifest, error) { return manifest, nil } -func MustParseSystemFromBytes(source []byte, scene *id.SceneID) *Manifest { +func MustParseSystemFromBytes(source []byte, scene *plugin.SceneID) *Manifest { m, err := ParseSystemFromBytes(source, scene) if err != nil { panic(err) diff --git a/pkg/plugin/manifest/parser_test.go b/pkg/plugin/manifest/parser_test.go index 08d9661e..d90501f3 100644 --- a/pkg/plugin/manifest/parser_test.go +++ b/pkg/plugin/manifest/parser_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/visualizer" @@ -16,35 +15,35 @@ import ( //go:embed testdata/minimum.yml var minimum string var minimumExpected = &Manifest{ - Plugin: plugin.New().ID(id.MustPluginID("aaa~1.1.1")).MustBuild(), + Plugin: plugin.New().ID(plugin.MustID("aaa~1.1.1")).MustBuild(), } //go:embed testdata/test.yml var normal string var normalExpected = &Manifest{ - Plugin: plugin.New().ID(id.MustPluginID("aaa~1.1.1")).Name(i18n.StringFrom("bbb")).Extensions([]*plugin.Extension{ - plugin.NewExtension().ID(id.PluginExtensionID("hoge")). + Plugin: plugin.New().ID(plugin.MustID("aaa~1.1.1")).Name(i18n.StringFrom("bbb")).Extensions([]*plugin.Extension{ + plugin.NewExtension().ID(plugin.ExtensionID("hoge")). Visualizer(visualizer.VisualizerCesium). Type(plugin.ExtensionTypePrimitive). WidgetLayout(nil). - Schema(id.MustPropertySchemaID("aaa~1.1.1/hoge")). + Schema(property.MustSchemaID("aaa~1.1.1/hoge")). MustBuild(), }).MustBuild(), ExtensionSchema: []*property.Schema{ - property.NewSchema().ID(id.MustPropertySchemaID("aaa~1.1.1/hoge")).Groups([]*property.SchemaGroup{ - property.NewSchemaGroup().ID(id.PropertySchemaGroupID("default")). - Schema(id.MustPropertySchemaID("aaa~1.1.1/hoge")). - RepresentativeField(id.PropertySchemaFieldID("a").Ref()). + property.NewSchema().ID(property.MustSchemaID("aaa~1.1.1/hoge")).Groups([]*property.SchemaGroup{ + property.NewSchemaGroup().ID(property.SchemaGroupID("default")). + Schema(property.MustSchemaID("aaa~1.1.1/hoge")). + RepresentativeField(property.FieldID("a").Ref()). Fields([]*property.SchemaField{ - property.NewSchemaField().ID(id.PropertySchemaFieldID("a")). + property.NewSchemaField().ID(property.FieldID("a")). Type(property.ValueTypeBool). DefaultValue(property.ValueTypeBool.ValueFrom(true)). IsAvailableIf(&property.Condition{ - Field: id.PropertySchemaFieldID("b"), + Field: property.FieldID("b"), Value: property.ValueTypeNumber.ValueFrom(1), }). MustBuild(), - property.NewSchemaField().ID(id.PropertySchemaFieldID("b")). + property.NewSchemaField().ID(property.FieldID("b")). Type(property.ValueTypeNumber). MustBuild(), }).MustBuild(), diff --git a/pkg/plugin/manifest/parser_translation.go b/pkg/plugin/manifest/parser_translation.go index 1d35185b..5bcb209f 100644 --- a/pkg/plugin/manifest/parser_translation.go +++ b/pkg/plugin/manifest/parser_translation.go @@ -8,7 +8,7 @@ import ( "io" "github.com/goccy/go-yaml" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" ) @@ -69,7 +69,7 @@ func MergeManifestTranslation(m *Manifest, tl map[string]*TranslationRoot) *Mani } for key, te := range t.Extensions { - ext := m.Plugin.Extension(id.PluginExtensionID(key)) + ext := m.Plugin.Extension(plugin.ExtensionID(key)) if ext == nil { continue } @@ -104,7 +104,7 @@ func MergeManifestTranslation(m *Manifest, tl map[string]*TranslationRoot) *Mani } for key, tsg := range te.PropertySchema { - psg := ps.Group(id.PropertySchemaGroupID(key)) + psg := ps.Group(property.SchemaGroupID(key)) if psg == nil { continue } @@ -126,7 +126,7 @@ func MergeManifestTranslation(m *Manifest, tl map[string]*TranslationRoot) *Mani // } for key, tsf := range tsg.Fields { - psf := psg.Field(id.PropertySchemaFieldID(key)) + psf := psg.Field(property.FieldID(key)) if psf == nil { continue } diff --git a/pkg/plugin/manifest/parser_translation_test.go b/pkg/plugin/manifest/parser_translation_test.go index 1dd0b156..c01d1313 100644 --- a/pkg/plugin/manifest/parser_translation_test.go +++ b/pkg/plugin/manifest/parser_translation_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/plugin" "github.com/stretchr/testify/assert" ) @@ -191,7 +191,7 @@ func TestMergeManifestTranslation(t *testing.T) { } assert.Equal(tt, tc.Expected.PluginName, res.Plugin.Name()) assert.Equal(tt, tc.Expected.PluginDesc, res.Plugin.Description()) - assert.Equal(tt, tc.Expected.ExtName, res.Plugin.Extension(id.PluginExtensionID("test_ext")).Name()) + assert.Equal(tt, tc.Expected.ExtName, res.Plugin.Extension(plugin.ExtensionID("test_ext")).Name()) assert.Equal(tt, tc.Expected.PsTitle, res.ExtensionSchema[0].Group("test_ps").Title()) assert.Equal(tt, tc.Expected.FieldTitle, res.ExtensionSchema[0].Group("test_ps").Field("test_field").Title()) assert.Equal(tt, tc.Expected.FieldDesc, res.ExtensionSchema[0].Group("test_ps").Field("test_field").Description()) diff --git a/pkg/plugin/plugin.go b/pkg/plugin/plugin.go index 4757f605..e9cbcab5 100644 --- a/pkg/plugin/plugin.go +++ b/pkg/plugin/plugin.go @@ -3,52 +3,43 @@ package plugin import ( "github.com/blang/semver" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) -// Plugin _ type Plugin struct { - id id.PluginID + id ID name i18n.String author string description i18n.String repositoryURL string - extensions map[id.PluginExtensionID]*Extension - extensionOrder []id.PluginExtensionID - schema *id.PropertySchemaID + extensions map[ExtensionID]*Extension + extensionOrder []ExtensionID + schema *PropertySchemaID } -// ID _ -func (p *Plugin) ID() id.PluginID { +func (p *Plugin) ID() ID { return p.id } -// Version _ func (p *Plugin) Version() semver.Version { return p.id.Version() } -// Name _ func (p *Plugin) Name() i18n.String { return p.name.Copy() } -// Author _ func (p *Plugin) Author() string { return p.author } -// Description _ func (p *Plugin) Description() i18n.String { return p.description.Copy() } -// RepositoryURL _ func (p *Plugin) RepositoryURL() string { return p.repositoryURL } -// Extensions _ func (p *Plugin) Extensions() []*Extension { if p.extensionOrder == nil { return []*Extension{} @@ -60,7 +51,7 @@ func (p *Plugin) Extensions() []*Extension { return list } -func (p *Plugin) Extension(id id.PluginExtensionID) *Extension { +func (p *Plugin) Extension(id ExtensionID) *Extension { if p == nil { return nil } @@ -72,17 +63,16 @@ func (p *Plugin) Extension(id id.PluginExtensionID) *Extension { return nil } -// Schema _ -func (p *Plugin) Schema() *id.PropertySchemaID { +func (p *Plugin) Schema() *PropertySchemaID { return p.schema } -func (p *Plugin) PropertySchemas() []id.PropertySchemaID { +func (p *Plugin) PropertySchemas() []PropertySchemaID { if p == nil { return nil } - ps := make([]id.PropertySchemaID, 0, len(p.extensions)+1) + ps := make([]PropertySchemaID, 0, len(p.extensions)+1) if p.schema != nil { ps = append(ps, *p.schema) } @@ -96,7 +86,6 @@ func (p *Plugin) Rename(name i18n.String) { p.name = name.Copy() } -// SetDescription _ func (p *Plugin) SetDescription(des i18n.String) { p.description = des.Copy() } diff --git a/pkg/plugin/plugin_test.go b/pkg/plugin/plugin_test.go index f31ae2a8..6c7ef199 100644 --- a/pkg/plugin/plugin_test.go +++ b/pkg/plugin/plugin_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -12,7 +11,7 @@ func TestPlugin_Extension(t *testing.T) { testCases := []struct { name string plugin *Plugin - key id.PluginExtensionID + key ExtensionID expected *Extension }{ { @@ -44,29 +43,29 @@ func TestPlugin_Extension(t *testing.T) { } func TestPlugin_PropertySchemas(t *testing.T) { - ps1 := id.MustPropertySchemaID("hoge~0.1.0/a") - ps2 := id.MustPropertySchemaID("hoge~0.1.0/b") - ps3 := id.MustPropertySchemaID("hoge~0.1.0/c") + ps1 := MustPropertySchemaID("hoge~0.1.0/a") + ps2 := MustPropertySchemaID("hoge~0.1.0/b") + ps3 := MustPropertySchemaID("hoge~0.1.0/c") testCases := []struct { name string plugin *Plugin - expected []id.PropertySchemaID + expected []PropertySchemaID }{ { name: "normal", plugin: New().Schema(&ps1).Extensions([]*Extension{NewExtension().ID("xxx").Schema(ps2).MustBuild(), NewExtension().ID("yyy").Schema(ps3).MustBuild()}).MustBuild(), - expected: []id.PropertySchemaID{ps1, ps2, ps3}, + expected: []PropertySchemaID{ps1, ps2, ps3}, }, { name: "no plugin property schema", plugin: New().Extensions([]*Extension{NewExtension().ID("xxx").Schema(ps2).MustBuild(), NewExtension().ID("yyy").Schema(ps3).MustBuild()}).MustBuild(), - expected: []id.PropertySchemaID{ps2, ps3}, + expected: []PropertySchemaID{ps2, ps3}, }, { name: "nil", plugin: nil, - expected: []id.PropertySchemaID(nil), + expected: []PropertySchemaID(nil), }, } for _, tc := range testCases { @@ -96,5 +95,5 @@ func TestPlugin_Author(t *testing.T) { } func TestPlugin_ID(t *testing.T) { - assert.Equal(t, New().ID(id.MustPluginID("xxx~1.1.1")).MustBuild().ID(), id.MustPluginID("xxx~1.1.1")) + assert.Equal(t, New().ID(MustID("xxx~1.1.1")).MustBuild().ID(), MustID("xxx~1.1.1")) } diff --git a/pkg/plugin/pluginpack/package.go b/pkg/plugin/pluginpack/package.go index 18f66245..c7e9344c 100644 --- a/pkg/plugin/pluginpack/package.go +++ b/pkg/plugin/pluginpack/package.go @@ -8,7 +8,7 @@ import ( "path/filepath" "github.com/reearth/reearth-backend/pkg/file" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/plugin/manifest" "github.com/reearth/reearth-backend/pkg/rerror" ) @@ -20,7 +20,7 @@ type Package struct { Files file.Iterator } -func PackageFromZip(r io.Reader, scene *id.SceneID, sizeLimit int64) (*Package, error) { +func PackageFromZip(r io.Reader, scene *plugin.SceneID, sizeLimit int64) (*Package, error) { b, err := io.ReadAll(io.LimitReader(r, sizeLimit)) if err != nil { return nil, rerror.From("zip read error", err) diff --git a/pkg/plugin/pluginpack/package_test.go b/pkg/plugin/pluginpack/package_test.go index 09ff0eba..ecd2a807 100644 --- a/pkg/plugin/pluginpack/package_test.go +++ b/pkg/plugin/pluginpack/package_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/plugin/manifest" "github.com/stretchr/testify/assert" @@ -20,7 +19,7 @@ func TestPackageFromZip(t *testing.T) { }() expected := plugin.New(). - ID(id.MustPluginID("testplugin~1.0.1")). + ID(plugin.MustID("testplugin~1.0.1")). Name(i18n.StringFrom("testplugin")). MustBuild() diff --git a/pkg/project/builder.go b/pkg/project/builder.go index 1891ed2e..79331c1a 100644 --- a/pkg/project/builder.go +++ b/pkg/project/builder.go @@ -4,7 +4,6 @@ import ( "net/url" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" ) @@ -17,8 +16,8 @@ func New() *Builder { } func (b *Builder) Build() (*Project, error) { - if id.ID(b.p.id).IsNil() { - return nil, id.ErrInvalidID + if b.p.id.IsNil() { + return nil, ErrInvalidID } if b.p.alias != "" && !CheckAliasPattern(b.p.alias) { return nil, ErrInvalidAlias @@ -37,13 +36,13 @@ func (b *Builder) MustBuild() *Project { return r } -func (b *Builder) ID(id id.ProjectID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.p.id = id return b } func (b *Builder) NewID() *Builder { - b.p.id = id.ProjectID(id.New()) + b.p.id = NewID() return b } @@ -122,7 +121,7 @@ func (b *Builder) PublicNoIndex(publicNoIndex bool) *Builder { return b } -func (b *Builder) Team(team id.TeamID) *Builder { +func (b *Builder) Team(team TeamID) *Builder { b.p.team = team return b } diff --git a/pkg/project/builder_test.go b/pkg/project/builder_test.go index 09bbdf47..36c29eb3 100644 --- a/pkg/project/builder_test.go +++ b/pkg/project/builder_test.go @@ -7,7 +7,6 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" "github.com/stretchr/testify/assert" ) @@ -19,7 +18,7 @@ func TestNew(t *testing.T) { func TestBuilder_ID(t *testing.T) { var tb = New() - res := tb.ID(id.NewProjectID()).MustBuild() + res := tb.ID(NewID()).MustBuild() assert.NotNil(t, res.ID()) } @@ -104,7 +103,7 @@ func TestBuilder_Visualizer(t *testing.T) { func TestBuilder_Team(t *testing.T) { var tb = New().NewID() - res := tb.Team(id.NewTeamID()).MustBuild() + res := tb.Team(NewTeamID()).MustBuild() assert.NotNil(t, res.Team()) } @@ -156,19 +155,19 @@ func TestBuilder_PublicNoIndex(t *testing.T) { func TestBuilder_Build(t *testing.T) { d := time.Date(1900, 1, 1, 00, 00, 0, 1, time.UTC) i, _ := url.Parse("ttt://xxx.aa/") - pid := id.NewProjectID() - tid := id.NewTeamID() + pid := NewID() + tid := NewTeamID() testCases := []struct { name, pname, description, alias, publicTitle, publicDescription, publicImage string - id id.ProjectID + id ID isArchived bool updatedAt time.Time publishedAt time.Time imageURL *url.URL publicNoIndex bool - team id.TeamID + team TeamID visualizer visualizer.Visualizer publishmentStatus PublishmentStatus expected *Project @@ -212,7 +211,7 @@ func TestBuilder_Build(t *testing.T) { }, { name: "zero updated at", - id: id.NewProjectID(), + id: NewID(), updatedAt: time.Time{}, expected: nil, err: nil, @@ -221,11 +220,11 @@ func TestBuilder_Build(t *testing.T) { name: "failed invalid id", expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { name: "failed invalid alias", - id: id.NewProjectID(), + id: NewID(), alias: "xxx.aaa", expected: nil, err: ErrInvalidAlias, @@ -269,19 +268,19 @@ func TestBuilder_Build(t *testing.T) { func TestBuilder_MustBuild(t *testing.T) { d := time.Date(1900, 1, 1, 00, 00, 0, 1, time.UTC) i, _ := url.Parse("ttt://xxx.aa/") - pid := id.NewProjectID() - tid := id.NewTeamID() + pid := NewID() + tid := NewTeamID() testCases := []struct { name, pname, description, alias, publicTitle, publicDescription, publicImage string - id id.ProjectID + id ID isArchived bool updatedAt time.Time publishedAt time.Time imageURL *url.URL publicNoIndex bool - team id.TeamID + team TeamID visualizer visualizer.Visualizer publishmentStatus PublishmentStatus expected *Project @@ -325,7 +324,7 @@ func TestBuilder_MustBuild(t *testing.T) { }, { name: "zero updated at", - id: id.NewProjectID(), + id: NewID(), updatedAt: time.Time{}, expected: nil, err: nil, @@ -334,11 +333,11 @@ func TestBuilder_MustBuild(t *testing.T) { name: "failed invalid id", expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { name: "failed invalid alias", - id: id.NewProjectID(), + id: NewID(), alias: "xxx.aaa", expected: nil, err: ErrInvalidAlias, diff --git a/pkg/project/id.go b/pkg/project/id.go new file mode 100644 index 00000000..cafbea20 --- /dev/null +++ b/pkg/project/id.go @@ -0,0 +1,31 @@ +package project + +import ( + "time" + + "github.com/reearth/reearth-backend/pkg/id" +) + +type ID = id.ProjectID +type TeamID = id.TeamID + +var NewID = id.NewProjectID +var NewTeamID = id.NewTeamID + +var MustID = id.MustProjectID +var MustTeamID = id.MustTeamID + +var IDFrom = id.ProjectIDFrom +var TeamIDFrom = id.TeamIDFrom + +var IDFromRef = id.ProjectIDFromRef +var TeamIDFromRef = id.TeamIDFromRef + +var IDFromRefID = id.ProjectIDFromRefID +var TeamIDFromRefID = id.TeamIDFromRefID + +var ErrInvalidID = id.ErrInvalidID + +func createdAt(i ID) time.Time { + return id.ID(i).Timestamp() +} diff --git a/pkg/project/project.go b/pkg/project/project.go index c15f9f55..72cbd866 100644 --- a/pkg/project/project.go +++ b/pkg/project/project.go @@ -6,7 +6,6 @@ import ( "regexp" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" ) @@ -15,9 +14,8 @@ var ( aliasRegexp = regexp.MustCompile("^[a-zA-Z0-9_-]{5,32}$") ) -// Project _ type Project struct { - id id.ProjectID + id ID isArchived bool isBasicAuthActive bool basicAuthUsername string @@ -32,12 +30,12 @@ type Project struct { publicDescription string publicImage string publicNoIndex bool - team id.TeamID + team TeamID visualizer visualizer.Visualizer publishmentStatus PublishmentStatus } -func (p *Project) ID() id.ProjectID { +func (p *Project) ID() ID { return p.id } @@ -105,12 +103,12 @@ func (p *Project) PublishmentStatus() PublishmentStatus { return p.publishmentStatus } -func (p *Project) Team() id.TeamID { +func (p *Project) Team() TeamID { return p.team } func (p *Project) CreatedAt() time.Time { - return id.ID(p.id).Timestamp() + return createdAt(p.id) } func (p *Project) Visualizer() visualizer.Visualizer { @@ -183,7 +181,7 @@ func (p *Project) UpdatePublicNoIndex(publicNoIndex bool) { p.publicNoIndex = publicNoIndex } -func (p *Project) UpdateTeam(team id.TeamID) { +func (p *Project) UpdateTeam(team TeamID) { p.team = team } diff --git a/pkg/project/project_test.go b/pkg/project/project_test.go index 15255f7f..c471c708 100644 --- a/pkg/project/project_test.go +++ b/pkg/project/project_test.go @@ -5,7 +5,6 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/visualizer" "github.com/stretchr/testify/assert" ) @@ -174,7 +173,7 @@ func TestProject_UpdatePublicTitle(t *testing.T) { func TestProject_UpdateTeam(t *testing.T) { p := &Project{} - p.UpdateTeam(id.NewTeamID()) + p.UpdateTeam(NewTeamID()) assert.NotNil(t, p.Team()) } diff --git a/pkg/project/publishment_status.go b/pkg/project/publishment_status.go index e465e2c3..43d33917 100644 --- a/pkg/project/publishment_status.go +++ b/pkg/project/publishment_status.go @@ -1,13 +1,11 @@ package project -// PublishmentStatus _ type PublishmentStatus string const ( - // PublishmentStatusPublic _ PublishmentStatusPublic PublishmentStatus = "public" - // PublishmentStatusLimited _ + PublishmentStatusLimited PublishmentStatus = "limited" - // PublishmentStatusPrivate _ + PublishmentStatusPrivate PublishmentStatus = "private" ) diff --git a/pkg/property/builder.go b/pkg/property/builder.go index c3915680..a4312262 100644 --- a/pkg/property/builder.go +++ b/pkg/property/builder.go @@ -2,31 +2,25 @@ package property import ( "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( - // ErrInvalidItem _ ErrInvalidItem = errors.New("invalid item") ) -// Builder _ type Builder struct { p *Property } -// New _ func New() *Builder { return &Builder{p: &Property{}} } -// Build _ func (b *Builder) Build() (*Property, error) { - if id.ID(b.p.id).IsNil() { - return nil, id.ErrInvalidID + if b.p.id.IsNil() { + return nil, ErrInvalidID } - if id.ID(b.p.scene).IsNil() { + if b.p.scene.IsNil() { return nil, ErrInvalidSceneID } if b.p.schema.IsNil() { @@ -40,7 +34,6 @@ func (b *Builder) Build() (*Property, error) { return b.p, nil } -// MustBuild _ func (b *Builder) MustBuild() *Property { p, err := b.Build() if err != nil { @@ -49,31 +42,26 @@ func (b *Builder) MustBuild() *Property { return p } -// ID _ -func (b *Builder) ID(id id.PropertyID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.p.id = id return b } -// NewID _ func (b *Builder) NewID() *Builder { - b.p.id = id.PropertyID(id.New()) + b.p.id = NewID() return b } -// Scene _ -func (b *Builder) Scene(s id.SceneID) *Builder { +func (b *Builder) Scene(s SceneID) *Builder { b.p.scene = s return b } -// Schema _ -func (b *Builder) Schema(schema id.PropertySchemaID) *Builder { +func (b *Builder) Schema(schema SchemaID) *Builder { b.p.schema = schema return b } -// Items _ func (b *Builder) Items(items []Item) *Builder { if len(items) == 0 { b.p.items = nil @@ -81,7 +69,7 @@ func (b *Builder) Items(items []Item) *Builder { } newItems := []Item{} - ids := map[id.PropertyItemID]struct{}{} + ids := map[ItemID]struct{}{} for _, f := range items { if f == nil { continue diff --git a/pkg/property/builder_test.go b/pkg/property/builder_test.go index 55171030..e2966295 100644 --- a/pkg/property/builder_test.go +++ b/pkg/property/builder_test.go @@ -4,7 +4,6 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -14,32 +13,32 @@ func TestBuilder_New(t *testing.T) { } func TestBuilder_ID(t *testing.T) { - pid := id.NewPropertyID() - p := New().ID(pid).Scene(id.NewSceneID()).Schema(id.MustPropertySchemaID("xxx~1.1.1/aa")).MustBuild() + pid := NewID() + p := New().ID(pid).Scene(NewSceneID()).Schema(MustSchemaID("xxx~1.1.1/aa")).MustBuild() assert.Equal(t, pid, p.ID()) } func TestBuilder_NewID(t *testing.T) { - p := New().NewID().Scene(id.NewSceneID()).Schema(id.MustPropertySchemaID("xxx~1.1.1/aa")).MustBuild() + p := New().NewID().Scene(NewSceneID()).Schema(MustSchemaID("xxx~1.1.1/aa")).MustBuild() assert.False(t, p.ID().IsNil()) } func TestBuilder_Schema(t *testing.T) { - p := New().NewID().Scene(id.NewSceneID()).Schema(id.MustPropertySchemaID("xxx~1.1.1/aa")).MustBuild() - assert.Equal(t, id.MustPropertySchemaID("xxx~1.1.1/aa"), p.Schema()) + p := New().NewID().Scene(NewSceneID()).Schema(MustSchemaID("xxx~1.1.1/aa")).MustBuild() + assert.Equal(t, MustSchemaID("xxx~1.1.1/aa"), p.Schema()) } func TestBuilder_Scene(t *testing.T) { - sid := id.NewSceneID() - p := New().NewID().Scene(sid).Schema(id.MustPropertySchemaID("xxx~1.1.1/aa")).MustBuild() + sid := NewSceneID() + p := New().NewID().Scene(sid).Schema(MustSchemaID("xxx~1.1.1/aa")).MustBuild() assert.Equal(t, sid, p.Scene()) } func TestBuilder_Items(t *testing.T) { - iid := id.NewPropertyItemID() - propertySchemaID := id.MustPropertySchemaID("xxx~1.1.1/aa") - propertySchemaField1ID := id.PropertySchemaFieldID("a") - propertySchemaGroup1ID := id.PropertySchemaGroupID("A") + iid := NewItemID() + propertySchemaID := MustSchemaID("xxx~1.1.1/aa") + propertySchemaField1ID := FieldID("a") + propertySchemaGroup1ID := SchemaGroupID("A") testCases := []struct { Name string @@ -83,8 +82,8 @@ func TestBuilder_Items(t *testing.T) { t.Run(tc.Name, func(tt *testing.T) { tt.Parallel() res := New().NewID(). - Scene(id.NewSceneID()). - Schema(id.MustPropertySchemaID("xxx~1.1.1/aa")). + Scene(NewSceneID()). + Schema(MustSchemaID("xxx~1.1.1/aa")). Items(tc.Input). MustBuild() assert.Equal(tt, tc.Expected, res.Items()) @@ -93,24 +92,24 @@ func TestBuilder_Items(t *testing.T) { } func TestBuilder_Build(t *testing.T) { - pid := id.NewPropertyID() - sid := id.NewSceneID() - scid := id.MustPropertySchemaID("xxx~1.1.1/aa") - iid := id.NewPropertyItemID() - propertySchemaField1ID := id.PropertySchemaFieldID("a") - propertySchemaGroup1ID := id.PropertySchemaGroupID("A") + pid := NewID() + sid := NewSceneID() + scid := MustSchemaID("xxx~1.1.1/aa") + iid := NewItemID() + propertySchemaField1ID := FieldID("a") + propertySchemaGroup1ID := SchemaGroupID("A") testCases := []struct { Name string - Id id.PropertyID - Scene id.SceneID - Schema id.PropertySchemaID + Id ID + Scene SceneID + Schema SchemaID Items []Item Err error Expected struct { - Id id.PropertyID - Scene id.SceneID - Schema id.PropertySchemaID + Id ID + Scene SceneID + Schema SchemaID Items []Item } }{ @@ -128,9 +127,9 @@ func TestBuilder_Build(t *testing.T) { Build(), }).MustBuild()}, Expected: struct { - Id id.PropertyID - Scene id.SceneID - Schema id.PropertySchemaID + Id ID + Scene SceneID + Schema SchemaID Items []Item }{ Id: pid, @@ -148,9 +147,9 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "fail invalid id", - Id: id.PropertyID{}, + Id: ID{}, Items: nil, - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "fail invalid scene", @@ -171,7 +170,7 @@ func TestBuilder_Build(t *testing.T) { Scene: sid, Schema: scid, Items: []Item{ - NewGroup().ID(iid).Schema(id.MustPropertySchemaID("zzz~1.1.1/aa"), propertySchemaGroup1ID). + NewGroup().ID(iid).Schema(MustSchemaID("zzz~1.1.1/aa"), propertySchemaGroup1ID). Fields([]*Field{ NewFieldUnsafe(). FieldUnsafe(propertySchemaField1ID). diff --git a/pkg/property/condition.go b/pkg/property/condition.go index 14217f30..8424da31 100644 --- a/pkg/property/condition.go +++ b/pkg/property/condition.go @@ -1,14 +1,10 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - -// Condition _ type Condition struct { - Field id.PropertySchemaFieldID + Field FieldID Value *Value } -// Clone _ func (c *Condition) Clone() *Condition { if c == nil { return nil diff --git a/pkg/property/field.go b/pkg/property/field.go index d38ffa13..ccf54c10 100644 --- a/pkg/property/field.go +++ b/pkg/property/field.go @@ -5,7 +5,6 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) var ( @@ -16,7 +15,7 @@ var ( ) type Field struct { - field id.PropertySchemaFieldID + field FieldID links *Links v *OptionalValue } @@ -29,7 +28,7 @@ func (p *Field) Clone() *Field { } } -func (p *Field) Field() id.PropertySchemaFieldID { +func (p *Field) Field() FieldID { return p.field } @@ -74,11 +73,11 @@ func (p *Field) HasLinkedField() bool { return p.Links().IsLinked() } -func (p *Field) CollectDatasets() []id.DatasetID { +func (p *Field) CollectDatasets() []DatasetID { if p == nil { return nil } - res := []id.DatasetID{} + res := []DatasetID{} if p.Links().IsLinkedFully() { dsid := p.Links().Last().Dataset() @@ -90,7 +89,7 @@ func (p *Field) CollectDatasets() []id.DatasetID { return res } -func (p *Field) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { +func (p *Field) IsDatasetLinked(s DatasetSchemaID, i DatasetID) bool { return p.Links().HasDatasetOrSchema(s, i) } @@ -126,7 +125,7 @@ func (p *Field) Unlink() { p.links = nil } -func (p *Field) UpdateField(field id.PropertySchemaFieldID) { +func (p *Field) UpdateField(field FieldID) { if p == nil { return } @@ -201,9 +200,9 @@ func (p *Field) ValidateSchema(ps *SchemaField) error { } type DatasetMigrationParam struct { - OldDatasetSchemaMap map[id.DatasetSchemaID]id.DatasetSchemaID - OldDatasetMap map[id.DatasetID]id.DatasetID - DatasetFieldIDMap map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID - NewDatasetSchemaMap map[id.DatasetSchemaID]*dataset.Schema - NewDatasetMap map[id.DatasetID]*dataset.Dataset + OldDatasetSchemaMap map[DatasetSchemaID]DatasetSchemaID + OldDatasetMap map[DatasetID]DatasetID + DatasetFieldIDMap map[DatasetFieldID]DatasetFieldID + NewDatasetSchemaMap map[DatasetSchemaID]*dataset.Schema + NewDatasetMap map[DatasetID]*dataset.Dataset } diff --git a/pkg/property/field_builder.go b/pkg/property/field_builder.go index 00bbbae5..7cfc3df9 100644 --- a/pkg/property/field_builder.go +++ b/pkg/property/field_builder.go @@ -1,7 +1,5 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - type FieldBuilder struct { p *Field psf *SchemaField @@ -19,8 +17,8 @@ func NewField(p *SchemaField) *FieldBuilder { } func (b *FieldBuilder) Build() (*Field, error) { - if b.p.field == id.PropertySchemaFieldID("") { - return nil, id.ErrInvalidID + if b.p.field == FieldID("") { + return nil, ErrInvalidID } if b.psf != nil && !b.psf.Validate(b.p.v) { return nil, ErrInvalidPropertyValue @@ -65,7 +63,7 @@ func (b *FieldUnsafeBuilder) Build() *Field { return b.p } -func (b *FieldUnsafeBuilder) FieldUnsafe(f id.PropertySchemaFieldID) *FieldUnsafeBuilder { +func (b *FieldUnsafeBuilder) FieldUnsafe(f FieldID) *FieldUnsafeBuilder { b.p.field = f return b } diff --git a/pkg/property/field_builder_test.go b/pkg/property/field_builder_test.go index 0322ddef..ae37a952 100644 --- a/pkg/property/field_builder_test.go +++ b/pkg/property/field_builder_test.go @@ -4,7 +4,6 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -17,14 +16,14 @@ func TestFieldBuilder_Value(t *testing.T) { func TestFieldBuilder_Link(t *testing.T) { p := NewSchemaField().ID("A").Type(ValueTypeString).MustBuild() - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) ls := NewLinks([]*Link{l}) b := NewField(p).Link(ls).MustBuild() assert.Equal(t, ls, b.Links()) } func TestFieldBuilder_Build(t *testing.T) { - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) testCases := []struct { Name string Links *Links @@ -44,7 +43,7 @@ func TestFieldBuilder_Build(t *testing.T) { Links *Links Value *Value }{}, - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "fail invalid property type", @@ -91,7 +90,7 @@ func TestFieldBuilder_Build(t *testing.T) { } func TestFieldBuilder_MustBuild(t *testing.T) { - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) testCases := []struct { Name string Fails bool @@ -168,16 +167,16 @@ func TestNewFieldUnsafe(t *testing.T) { } func TestFieldUnsafeBuilder_Build(t *testing.T) { - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) testCases := []struct { Name string Links *Links Value *Value Type ValueType - Field id.PropertySchemaFieldID + Field FieldID Expected struct { PType ValueType - Field id.PropertySchemaFieldID + Field FieldID Links *Links Value *Value } @@ -190,7 +189,7 @@ func TestFieldUnsafeBuilder_Build(t *testing.T) { Field: "a", Expected: struct { PType ValueType - Field id.PropertySchemaFieldID + Field FieldID Links *Links Value *Value }{ @@ -208,7 +207,7 @@ func TestFieldUnsafeBuilder_Build(t *testing.T) { Field: "a", Expected: struct { PType ValueType - Field id.PropertySchemaFieldID + Field FieldID Links *Links Value *Value }{ diff --git a/pkg/property/field_test.go b/pkg/property/field_test.go index aade07fb..27290250 100644 --- a/pkg/property/field_test.go +++ b/pkg/property/field_test.go @@ -4,15 +4,14 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestField_ActualValue(t *testing.T) { p := NewSchemaField().ID("A").Type(ValueTypeString).MustBuild() - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - dssfid := id.NewDatasetSchemaFieldID() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + dssfid := NewDatasetFieldID() l := NewLink(dsid, dssid, dssfid) ls := NewLinks([]*Link{l}) @@ -57,21 +56,21 @@ func TestField_ActualValue(t *testing.T) { func TestField_CollectDatasets(t *testing.T) { p := NewSchemaField().ID("A").Type(ValueTypeString).MustBuild() - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - dssfid := id.NewDatasetSchemaFieldID() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + dssfid := NewDatasetFieldID() l := NewLink(dsid, dssid, dssfid) ls := NewLinks([]*Link{l}) testCases := []struct { Name string Field *Field - Expected []id.DatasetID + Expected []DatasetID }{ { Name: "list of one datasets", Field: NewField(p).Value(OptionalValueFrom(ValueTypeString.ValueFrom("vvv"))).Link(ls).MustBuild(), - Expected: []id.DatasetID{dsid}, + Expected: []DatasetID{dsid}, }, { Name: "nil field", @@ -91,7 +90,7 @@ func TestField_CollectDatasets(t *testing.T) { func TestField_Clone(t *testing.T) { p := NewSchemaField().ID("A").Type(ValueTypeString).MustBuild() - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) ls := NewLinks([]*Link{l}) b := NewField(p).Value(OptionalValueFrom(ValueTypeString.ValueFrom("vvv"))).Link(ls).MustBuild() r := b.Clone() @@ -99,12 +98,12 @@ func TestField_Clone(t *testing.T) { } func TestField(t *testing.T) { - did := id.NewDatasetID() - dsid := id.NewDatasetSchemaID() + did := NewDatasetID() + dsid := NewDatasetSchemaID() p := NewSchemaField().ID("A").Type(ValueTypeString).MustBuild() b := NewField(p).MustBuild() assert.True(t, b.IsEmpty()) - l := NewLink(did, dsid, id.NewDatasetSchemaFieldID()) + l := NewLink(did, dsid, NewDatasetFieldID()) ls := NewLinks([]*Link{l}) b.Link(ls) assert.True(t, b.IsDatasetLinked(dsid, did)) diff --git a/pkg/property/group.go b/pkg/property/group.go index bbacd6ce..80d1a28b 100644 --- a/pkg/property/group.go +++ b/pkg/property/group.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) // Group represents a group of property @@ -18,43 +17,42 @@ type Group struct { // Group implements Item interface var _ Item = &Group{} -func (g *Group) ID() id.PropertyItemID { +func (g *Group) ID() ItemID { if g == nil { - return id.PropertyItemID{} + return ItemID{} } return g.itemBase.ID } -func (g *Group) IDRef() *id.PropertyItemID { +func (g *Group) IDRef() *ItemID { if g == nil { return nil } return g.itemBase.ID.Ref() } -func (g *Group) SchemaGroup() id.PropertySchemaGroupID { +func (g *Group) SchemaGroup() SchemaGroupID { if g == nil { - return id.PropertySchemaGroupID("") + return SchemaGroupID("") } return g.itemBase.SchemaGroup } -func (g *Group) SchemaGroupRef() *id.PropertySchemaGroupID { +func (g *Group) SchemaGroupRef() *SchemaGroupID { if g == nil { return nil } return g.itemBase.SchemaGroup.Ref() } -func (g *Group) Schema() id.PropertySchemaID { +func (g *Group) Schema() SchemaID { if g == nil { - return id.PropertySchemaID{} + return SchemaID{} } return g.itemBase.Schema } -// SchemaRef _ -func (g *Group) SchemaRef() *id.PropertySchemaID { +func (g *Group) SchemaRef() *SchemaID { if g == nil { return nil } @@ -73,11 +71,11 @@ func (g *Group) HasLinkedField() bool { return false } -func (g *Group) CollectDatasets() []id.DatasetID { +func (g *Group) CollectDatasets() []DatasetID { if g == nil { return nil } - res := []id.DatasetID{} + res := []DatasetID{} for _, f := range g.fields { res = append(res, f.CollectDatasets()...) @@ -86,7 +84,7 @@ func (g *Group) CollectDatasets() []id.DatasetID { return res } -func (g *Group) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) []*Field { +func (g *Group) FieldsByLinkedDataset(s DatasetSchemaID, i DatasetID) []*Field { if g == nil { return nil } @@ -99,7 +97,7 @@ func (g *Group) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) []*F return res } -func (g *Group) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { +func (g *Group) IsDatasetLinked(s DatasetSchemaID, i DatasetID) bool { if g == nil { return false } @@ -150,7 +148,7 @@ func (g *Group) MigrateSchema(ctx context.Context, newSchema *Schema, dl dataset g.Prune() } -func (g *Group) GetOrCreateField(ps *Schema, fid id.PropertySchemaFieldID) (*Field, bool) { +func (g *Group) GetOrCreateField(ps *Schema, fid FieldID) (*Field, bool) { if g == nil || ps == nil || !g.Schema().Equal(ps.ID()) { return nil, false } @@ -180,7 +178,7 @@ func (g *Group) GetOrCreateField(ps *Schema, fid id.PropertySchemaFieldID) (*Fie return field, true } -func (g *Group) RemoveField(fid id.PropertySchemaFieldID) { +func (g *Group) RemoveField(fid FieldID) { if g == nil { return } @@ -192,11 +190,11 @@ func (g *Group) RemoveField(fid id.PropertySchemaFieldID) { } } -func (g *Group) FieldIDs() []id.PropertySchemaFieldID { +func (g *Group) FieldIDs() []FieldID { if g == nil { return nil } - fields := make([]id.PropertySchemaFieldID, 0, len(g.fields)) + fields := make([]FieldID, 0, len(g.fields)) for _, f := range g.fields { fields = append(fields, f.Field()) } @@ -212,7 +210,7 @@ func (g *Group) Fields() []*Field { } // Field returns a field whose id is specified -func (g *Group) Field(fid id.PropertySchemaFieldID) *Field { +func (g *Group) Field(fid FieldID) *Field { if g == nil { return nil } diff --git a/pkg/property/group_builder.go b/pkg/property/group_builder.go index d80d12aa..0c65712c 100644 --- a/pkg/property/group_builder.go +++ b/pkg/property/group_builder.go @@ -1,7 +1,5 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - type GroupBuilder struct { p *Group } @@ -21,8 +19,8 @@ func InitGroupFrom(g *SchemaGroup) *Group { } func (b *GroupBuilder) Build() (*Group, error) { - if id.ID(b.p.itemBase.ID).IsNil() { - return nil, id.ErrInvalidID + if b.p.itemBase.ID.IsNil() { + return nil, ErrInvalidID } return b.p, nil } @@ -40,17 +38,17 @@ func (b *GroupBuilder) base(base itemBase) *GroupBuilder { return b } -func (b *GroupBuilder) ID(id id.PropertyItemID) *GroupBuilder { +func (b *GroupBuilder) ID(id ItemID) *GroupBuilder { b.p.itemBase.ID = id return b } func (b *GroupBuilder) NewID() *GroupBuilder { - b.p.itemBase.ID = id.NewPropertyItemID() + b.p.itemBase.ID = NewItemID() return b } -func (b *GroupBuilder) Schema(s id.PropertySchemaID, g id.PropertySchemaGroupID) *GroupBuilder { +func (b *GroupBuilder) Schema(s SchemaID, g SchemaGroupID) *GroupBuilder { b.p.itemBase.Schema = s b.p.itemBase.SchemaGroup = g return b @@ -58,7 +56,7 @@ func (b *GroupBuilder) Schema(s id.PropertySchemaID, g id.PropertySchemaGroupID) func (b *GroupBuilder) Fields(fields []*Field) *GroupBuilder { var newFields []*Field - ids := map[id.PropertySchemaFieldID]struct{}{} + ids := map[FieldID]struct{}{} for _, f := range fields { if f == nil { continue diff --git a/pkg/property/group_builder_test.go b/pkg/property/group_builder_test.go index 504a3754..0b01b736 100644 --- a/pkg/property/group_builder_test.go +++ b/pkg/property/group_builder_test.go @@ -4,33 +4,32 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestGroupBuilder_Build(t *testing.T) { - iid := id.NewPropertyItemID() - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + iid := NewItemID() + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") f := NewField(sf).Value(OptionalValueFrom(v)).MustBuild() testCases := []struct { Name string - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field Expected struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field } Err error }{ { Name: "fail invalid id", - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "success", @@ -39,9 +38,9 @@ func TestGroupBuilder_Build(t *testing.T) { SchemaGroup: "a", Fields: []*Field{f}, Expected: struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field }{ Id: iid, @@ -71,22 +70,22 @@ func TestGroupBuilder_Build(t *testing.T) { } func TestGroupBuilder_MustBuild(t *testing.T) { - iid := id.NewPropertyItemID() - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + iid := NewItemID() + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") f := NewField(sf).Value(OptionalValueFrom(v)).MustBuild() testCases := []struct { Name string Fail bool - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field Expected struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field } }{ @@ -101,9 +100,9 @@ func TestGroupBuilder_MustBuild(t *testing.T) { SchemaGroup: "a", Fields: []*Field{f}, Expected: struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Fields []*Field }{ Id: iid, @@ -146,7 +145,7 @@ func TestGroupBuilder_NewID(t *testing.T) { func TestGroupBuilder_InitGroupFrom(t *testing.T) { var sg *SchemaGroup assert.Nil(t, InitGroupFrom(sg)) - sg = NewSchemaGroup().ID("a").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).MustBuild() + sg = NewSchemaGroup().ID("a").Schema(MustSchemaID("xx~1.0.0/aa")).MustBuild() g := InitGroupFrom(sg) assert.Equal(t, sg.ID(), g.SchemaGroup()) assert.Equal(t, sg.Schema(), g.Schema()) diff --git a/pkg/property/group_list.go b/pkg/property/group_list.go index e6ddb1cf..7eeec815 100644 --- a/pkg/property/group_list.go +++ b/pkg/property/group_list.go @@ -6,10 +6,8 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) -// GroupList _ type GroupList struct { itemBase groups []*Group @@ -19,15 +17,15 @@ type GroupList struct { var _ Item = &GroupList{} // ID returns id -func (g *GroupList) ID() id.PropertyItemID { +func (g *GroupList) ID() ItemID { if g == nil { - return id.PropertyItemID{} + return ItemID{} } return g.itemBase.ID } // IDRef returns a reference of id -func (g *GroupList) IDRef() *id.PropertyItemID { +func (g *GroupList) IDRef() *ItemID { if g == nil { return nil } @@ -35,38 +33,34 @@ func (g *GroupList) IDRef() *id.PropertyItemID { } // SchemaGroup returns id of schema group -func (g *GroupList) SchemaGroup() id.PropertySchemaGroupID { +func (g *GroupList) SchemaGroup() SchemaGroupID { if g == nil { - return id.PropertySchemaGroupID("") + return SchemaGroupID("") } return g.itemBase.SchemaGroup } -// SchemaGroupRef _ -func (g *GroupList) SchemaGroupRef() *id.PropertySchemaGroupID { +func (g *GroupList) SchemaGroupRef() *SchemaGroupID { if g == nil { return nil } return g.itemBase.SchemaGroup.Ref() } -// Schema _ -func (g *GroupList) Schema() id.PropertySchemaID { +func (g *GroupList) Schema() SchemaID { if g == nil { - return id.PropertySchemaID{} + return SchemaID{} } return g.itemBase.Schema } -// SchemaRef _ -func (g *GroupList) SchemaRef() *id.PropertySchemaID { +func (g *GroupList) SchemaRef() *SchemaID { if g == nil { return nil } return g.itemBase.Schema.Ref() } -// HasLinkedField _ func (g *GroupList) HasLinkedField() bool { if g == nil { return false @@ -79,12 +73,11 @@ func (g *GroupList) HasLinkedField() bool { return false } -// CollectDatasets _ -func (g *GroupList) CollectDatasets() []id.DatasetID { +func (g *GroupList) CollectDatasets() []DatasetID { if g == nil { return nil } - res := []id.DatasetID{} + res := []DatasetID{} for _, f := range g.groups { res = append(res, f.CollectDatasets()...) @@ -93,8 +86,7 @@ func (g *GroupList) CollectDatasets() []id.DatasetID { return res } -// FieldsByLinkedDataset _ -func (g *GroupList) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) []*Field { +func (g *GroupList) FieldsByLinkedDataset(s DatasetSchemaID, i DatasetID) []*Field { if g == nil { return nil } @@ -105,8 +97,7 @@ func (g *GroupList) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) return res } -// IsDatasetLinked _ -func (g *GroupList) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { +func (g *GroupList) IsDatasetLinked(s DatasetSchemaID, i DatasetID) bool { if g == nil { return false } @@ -118,12 +109,10 @@ func (g *GroupList) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { return false } -// IsEmpty _ func (g *GroupList) IsEmpty() bool { return g != nil && (g.groups == nil || len(g.groups) == 0) } -// Prune _ func (g *GroupList) Prune() { if g == nil { return @@ -133,7 +122,6 @@ func (g *GroupList) Prune() { } } -// MigrateSchema _ func (g *GroupList) MigrateSchema(ctx context.Context, newSchema *Schema, dl dataset.Loader) { if g == nil || dl == nil { return @@ -157,7 +145,7 @@ func (g *GroupList) Groups() []*Group { } // GetGroup returns a group whose id is specified -func (g *GroupList) GetGroup(gid id.PropertyItemID) *Group { +func (g *GroupList) GetGroup(gid ItemID) *Group { if g == nil { return nil } @@ -177,8 +165,7 @@ func (g *GroupList) GroupAt(i int) *Group { return g.groups[i] } -// Has _ -func (g *GroupList) Has(i id.PropertyItemID) bool { +func (g *GroupList) Has(i ItemID) bool { if g == nil { return false } @@ -190,7 +177,6 @@ func (g *GroupList) Has(i id.PropertyItemID) bool { return false } -// Count _ func (g *GroupList) Count() int { if g == nil { return 0 @@ -198,7 +184,6 @@ func (g *GroupList) Count() int { return len(g.groups) } -// Add _ func (g *GroupList) Add(gg *Group, index int) { if g == nil || g.Has(gg.ID()) { return @@ -212,7 +197,6 @@ func (g *GroupList) Add(gg *Group, index int) { } } -// AddOrMove _ func (g *GroupList) AddOrMove(gg *Group, index int) { if g == nil { return @@ -231,8 +215,7 @@ func (g *GroupList) AddOrMove(gg *Group, index int) { g.groups = append(g.groups[:index], append([]*Group{gg}, g.groups[index:]...)...) } -// Move _ -func (g *GroupList) Move(id id.PropertyItemID, toIndex int) { +func (g *GroupList) Move(id ItemID, toIndex int) { if g == nil { return } @@ -245,7 +228,6 @@ func (g *GroupList) Move(id id.PropertyItemID, toIndex int) { } } -// MoveAt _ func (g *GroupList) MoveAt(fromIndex int, toIndex int) { if g == nil { return @@ -270,8 +252,7 @@ func (g *GroupList) MoveAt(fromIndex int, toIndex int) { g.groups = append(newSlice, g.groups[toIndex:]...) } -// Remove _ -func (g *GroupList) Remove(id id.PropertyItemID) bool { +func (g *GroupList) Remove(id ItemID) bool { if g == nil { return false } @@ -286,7 +267,6 @@ func (g *GroupList) Remove(id id.PropertyItemID) bool { return false } -// RemoveAt _ func (g *GroupList) RemoveAt(index int) { if g == nil { return @@ -305,7 +285,6 @@ func (g *GroupList) RemoveAt(index int) { g.groups = append(g.groups[:index], groups...) } -// Empty _ func (g *GroupList) Empty() { if g == nil { return @@ -314,7 +293,6 @@ func (g *GroupList) Empty() { g.groups = []*Group{} } -// GetOrCreateField _ func (g *GroupList) GetOrCreateField(ps *Schema, ptr *Pointer) (*Field, bool) { if g == nil || ptr == nil || ps == nil || ps.ID() != g.Schema() { return nil, false @@ -337,7 +315,6 @@ func (g *GroupList) GetOrCreateField(ps *Schema, ptr *Pointer) (*Field, bool) { return i.GetOrCreateField(ps, fid) } -// CreateAndAddListItem _ func (g *GroupList) CreateAndAddListItem(ps *Schema, index *int) *Group { if g == nil || ps == nil || !g.Schema().Equal(ps.ID()) { return nil @@ -360,7 +337,6 @@ func (g *GroupList) CreateAndAddListItem(ps *Schema, index *int) *Group { return nil } -// MigrateDataset _ func (g *GroupList) MigrateDataset(q DatasetMigrationParam) { if g == nil { return diff --git a/pkg/property/group_list_builder.go b/pkg/property/group_list_builder.go index bebb6a9b..1affcd1d 100644 --- a/pkg/property/group_list_builder.go +++ b/pkg/property/group_list_builder.go @@ -1,7 +1,5 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - type GroupListBuilder struct { p *GroupList } @@ -21,8 +19,8 @@ func InitGroupListFrom(g *SchemaGroup) *GroupList { } func (b *GroupListBuilder) Build() (*GroupList, error) { - if id.ID(b.p.itemBase.ID).IsNil() { - return nil, id.ErrInvalidID + if b.p.itemBase.ID.IsNil() { + return nil, ErrInvalidID } return b.p, nil } @@ -40,17 +38,17 @@ func (b *GroupListBuilder) base(base itemBase) *GroupListBuilder { return b } -func (b *GroupListBuilder) ID(id id.PropertyItemID) *GroupListBuilder { +func (b *GroupListBuilder) ID(id ItemID) *GroupListBuilder { b.p.itemBase.ID = id return b } func (b *GroupListBuilder) NewID() *GroupListBuilder { - b.p.itemBase.ID = id.NewPropertyItemID() + b.p.itemBase.ID = NewItemID() return b } -func (b *GroupListBuilder) Schema(s id.PropertySchemaID, g id.PropertySchemaGroupID) *GroupListBuilder { +func (b *GroupListBuilder) Schema(s SchemaID, g SchemaGroupID) *GroupListBuilder { b.p.itemBase.Schema = s b.p.itemBase.SchemaGroup = g return b @@ -58,7 +56,7 @@ func (b *GroupListBuilder) Schema(s id.PropertySchemaID, g id.PropertySchemaGrou func (b *GroupListBuilder) Groups(fields []*Group) *GroupListBuilder { newGroups := []*Group{} - ids := map[id.PropertyItemID]struct{}{} + ids := map[ItemID]struct{}{} for _, f := range fields { if f == nil { continue diff --git a/pkg/property/group_list_builder_test.go b/pkg/property/group_list_builder_test.go index 8ef9d7d6..cdf459d8 100644 --- a/pkg/property/group_list_builder_test.go +++ b/pkg/property/group_list_builder_test.go @@ -4,24 +4,23 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestGroupListBuilder_Build(t *testing.T) { - pid := id.NewPropertyItemID() - scid := id.MustPropertySchemaID("xx~1.0.0/aa") + pid := NewItemID() + scid := MustSchemaID("xx~1.0.0/aa") groups := []*Group{NewGroup().ID(pid).MustBuild()} testCases := []struct { Name string - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group Expected struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group } Err error @@ -33,9 +32,9 @@ func TestGroupListBuilder_Build(t *testing.T) { SchemaGroup: "aa", Groups: groups, Expected: struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group }{ Id: pid, @@ -46,7 +45,7 @@ func TestGroupListBuilder_Build(t *testing.T) { }, { Name: "fail invalid id", - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, } for _, tc := range testCases { @@ -72,20 +71,20 @@ func TestGroupListBuilder_NewID(t *testing.T) { } func TestGroupListBuilder_MustBuild(t *testing.T) { - pid := id.NewPropertyItemID() - scid := id.MustPropertySchemaID("xx~1.0.0/aa") + pid := NewItemID() + scid := MustSchemaID("xx~1.0.0/aa") groups := []*Group{NewGroup().ID(pid).MustBuild()} testCases := []struct { Name string Fails bool - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group Expected struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group } }{ @@ -96,9 +95,9 @@ func TestGroupListBuilder_MustBuild(t *testing.T) { SchemaGroup: "aa", Groups: groups, Expected: struct { - Id id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + Id ItemID + Schema SchemaID + SchemaGroup SchemaGroupID Groups []*Group }{ Id: pid, @@ -140,17 +139,17 @@ func TestInitGroupListFrom(t *testing.T) { testCases := []struct { Name string SchemaGroup *SchemaGroup - ExpectedSG id.PropertySchemaGroupID - ExpectedSchema id.PropertySchemaID + ExpectedSG SchemaGroupID + ExpectedSchema SchemaID }{ { Name: "nil schema group", }, { Name: "success", - SchemaGroup: NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).MustBuild(), + SchemaGroup: NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).MustBuild(), ExpectedSG: "aa", - ExpectedSchema: id.MustPropertySchemaID("xx~1.0.0/aa"), + ExpectedSchema: MustSchemaID("xx~1.0.0/aa"), }, } diff --git a/pkg/property/group_list_test.go b/pkg/property/group_list_test.go index 39329d43..343ab2cd 100644 --- a/pkg/property/group_list_test.go +++ b/pkg/property/group_list_test.go @@ -3,7 +3,6 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -18,17 +17,17 @@ func TestGroupList_SchemaRef(t *testing.T) { testCases := []struct { Name string GL *GroupList - ExpectedSG *id.PropertySchemaGroupID - ExpectedSchema *id.PropertySchemaID + ExpectedSG *SchemaGroupID + ExpectedSchema *SchemaID }{ { Name: "nil group list", }, { Name: "success", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), id.PropertySchemaGroupID("xx")).MustBuild(), - ExpectedSG: id.PropertySchemaGroupID("xx").Ref(), - ExpectedSchema: id.MustPropertySchemaID("xx~1.0.0/aa").Ref(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), SchemaGroupID("xx")).MustBuild(), + ExpectedSG: SchemaGroupID("xx").Ref(), + ExpectedSchema: MustSchemaID("xx~1.0.0/aa").Ref(), }, } for _, tc := range testCases { @@ -42,12 +41,12 @@ func TestGroupList_SchemaRef(t *testing.T) { } func TestGroupList_HasLinkedField(t *testing.T) { - pid := id.NewPropertyItemID() + pid := NewItemID() sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, id.NewDatasetSchemaFieldID())}}).MustBuild() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, NewDatasetFieldID())}}).MustBuild() groups := []*Group{NewGroup().ID(pid).Fields([]*Field{f}).MustBuild()} groups2 := []*Group{NewGroup().ID(pid).MustBuild()} testCases := []struct { @@ -60,12 +59,12 @@ func TestGroupList_HasLinkedField(t *testing.T) { }, { Name: "has linked field", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), Expected: true, }, { Name: "no linked field", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), Expected: false, }, } @@ -80,31 +79,31 @@ func TestGroupList_HasLinkedField(t *testing.T) { } func TestGroupList_CollectDatasets(t *testing.T) { - pid := id.NewPropertyItemID() + pid := NewItemID() sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, id.NewDatasetSchemaFieldID())}}).MustBuild() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, NewDatasetFieldID())}}).MustBuild() groups := []*Group{NewGroup().ID(pid).Fields([]*Field{f}).MustBuild()} groups2 := []*Group{NewGroup().ID(pid).MustBuild()} testCases := []struct { Name string GL *GroupList - Expected []id.DatasetID + Expected []DatasetID }{ { Name: "nil group list", }, { Name: "one dataset", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), - Expected: []id.DatasetID{dsid}, + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), + Expected: []DatasetID{dsid}, }, { Name: "empty list", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), - Expected: []id.DatasetID{}, + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), + Expected: []DatasetID{}, }, } for _, tc := range testCases { @@ -117,12 +116,12 @@ func TestGroupList_CollectDatasets(t *testing.T) { } func TestGroupList_FieldsByLinkedDataset(t *testing.T) { - pid := id.NewPropertyItemID() + pid := NewItemID() sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, id.NewDatasetSchemaFieldID())}}).MustBuild() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, NewDatasetFieldID())}}).MustBuild() groups := []*Group{NewGroup().ID(pid).Fields([]*Field{f}).MustBuild()} groups2 := []*Group{NewGroup().ID(pid).MustBuild()} testCases := []struct { @@ -135,12 +134,12 @@ func TestGroupList_FieldsByLinkedDataset(t *testing.T) { }, { Name: "one field list", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), Expected: []*Field{f}, }, { Name: "empty list", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups2).MustBuild(), Expected: []*Field{}, }, } @@ -154,12 +153,12 @@ func TestGroupList_FieldsByLinkedDataset(t *testing.T) { } func TestGroupList_IsEmpty(t *testing.T) { - pid := id.NewPropertyItemID() + pid := NewItemID() sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, id.NewDatasetSchemaFieldID())}}).MustBuild() + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + f := NewField(sf).Value(OptionalValueFrom(v)).Link(&Links{links: []*Link{NewLink(dsid, dssid, NewDatasetFieldID())}}).MustBuild() groups := []*Group{NewGroup().ID(pid).Fields([]*Field{f}).MustBuild()} testCases := []struct { Name string @@ -171,12 +170,12 @@ func TestGroupList_IsEmpty(t *testing.T) { }, { Name: "is empty", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").MustBuild(), Expected: true, }, { Name: "is not empty", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), Expected: false, }, } @@ -194,7 +193,7 @@ func TestGroupList_Prune(t *testing.T) { v := ValueTypeString.ValueFrom("vvv") f := NewField(sf).Value(OptionalValueFrom(v)).MustBuild() f2 := NewField(sf).MustBuild() - pid := id.NewPropertyItemID() + pid := NewItemID() groups := []*Group{NewGroup().ID(pid).Fields([]*Field{f, f2}).MustBuild()} pruned := []*Group{NewGroup().ID(pid).Fields([]*Field{f}).MustBuild()} testCases := []struct { @@ -207,7 +206,7 @@ func TestGroupList_Prune(t *testing.T) { }, { Name: "pruned list", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups(groups).MustBuild(), Expected: pruned, }, } @@ -222,11 +221,11 @@ func TestGroupList_Prune(t *testing.T) { } func TestGroupList_GetGroup(t *testing.T) { - pid := id.NewPropertyItemID() + pid := NewItemID() g := NewGroup().ID(pid).MustBuild() testCases := []struct { Name string - Input id.PropertyItemID + Input ItemID GL *GroupList Expected *Group }{ @@ -236,13 +235,13 @@ func TestGroupList_GetGroup(t *testing.T) { { Name: "found", Input: pid, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g}).MustBuild(), Expected: g, }, { Name: "not found", - Input: id.NewPropertyItemID(), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g}).MustBuild(), + Input: NewItemID(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g}).MustBuild(), Expected: nil, }, } @@ -256,10 +255,10 @@ func TestGroupList_GetGroup(t *testing.T) { } func TestGroupList_GroupAt(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string Index int @@ -280,7 +279,7 @@ func TestGroupList_GroupAt(t *testing.T) { { Name: "found", Index: 2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: g3, }, } @@ -294,13 +293,13 @@ func TestGroupList_GroupAt(t *testing.T) { } func TestGroupList_Has(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string - Input id.PropertyItemID + Input ItemID GL *GroupList Expected bool }{ @@ -310,13 +309,13 @@ func TestGroupList_Has(t *testing.T) { { Name: "found", Input: g2.ID(), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: true, }, { Name: "not found", Input: g3.ID(), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g4}).MustBuild(), Expected: false, }, } @@ -330,10 +329,10 @@ func TestGroupList_Has(t *testing.T) { } func TestGroupList_Count(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -344,7 +343,7 @@ func TestGroupList_Count(t *testing.T) { }, { Name: "not found", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: 4, }, } @@ -358,10 +357,10 @@ func TestGroupList_Count(t *testing.T) { } func TestGroupList_Add(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -379,7 +378,7 @@ func TestGroupList_Add(t *testing.T) { Name: "index < 0", Index: -1, Gr: g2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), Expected: struct { Gr *Group Index int @@ -392,7 +391,7 @@ func TestGroupList_Add(t *testing.T) { Name: "len(g) > index > 0 ", Index: 2, Gr: g2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), Expected: struct { Gr *Group Index int @@ -414,10 +413,10 @@ func TestGroupList_Add(t *testing.T) { } func TestGroupList_AddOrMove(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -435,7 +434,7 @@ func TestGroupList_AddOrMove(t *testing.T) { Name: "index < 0", Index: -1, Gr: g2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), Expected: struct { Gr *Group Index int @@ -448,7 +447,7 @@ func TestGroupList_AddOrMove(t *testing.T) { Name: "len(g) > index > 0 ", Index: 2, Gr: g2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), Expected: struct { Gr *Group Index int @@ -461,7 +460,7 @@ func TestGroupList_AddOrMove(t *testing.T) { Name: "move group", Index: 2, Gr: g1, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g3, g4}).MustBuild(), Expected: struct { Gr *Group Index int @@ -483,17 +482,17 @@ func TestGroupList_AddOrMove(t *testing.T) { } func TestGroupList_Move(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList - Id id.PropertyItemID + Id ItemID ToIndex int Expected struct { - Id id.PropertyItemID + Id ItemID Index int } }{ @@ -504,9 +503,9 @@ func TestGroupList_Move(t *testing.T) { Name: "success", Id: g1.ID(), ToIndex: 2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: struct { - Id id.PropertyItemID + Id ItemID Index int }{Id: g1.ID(), Index: 2}, }, @@ -523,10 +522,10 @@ func TestGroupList_Move(t *testing.T) { } func TestGroupList_MoveAt(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -540,21 +539,21 @@ func TestGroupList_MoveAt(t *testing.T) { Name: "from = to", FromIndex: 2, ToIndex: 2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g1, g2, g3, g4}, }, { Name: "from < 0", FromIndex: -1, ToIndex: 2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g1, g2, g3, g4}, }, { Name: "success move", FromIndex: 0, ToIndex: 2, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g2, g3, g1, g4}, }, } @@ -570,10 +569,10 @@ func TestGroupList_MoveAt(t *testing.T) { } func TestGroupList_RemoveAt(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -586,19 +585,19 @@ func TestGroupList_RemoveAt(t *testing.T) { { Name: "success", Index: 1, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g1, g3, g4}, }, { Name: "index < 0", Index: -1, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g1, g2, g3, g4}, }, { Name: "index > length", Index: 5, - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: []*Group{g1, g2, g3, g4}, }, } @@ -613,14 +612,14 @@ func TestGroupList_RemoveAt(t *testing.T) { } } func TestGroupList_Remove(t *testing.T) { - g1 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g2 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g3 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() - g4 := NewGroup().ID(id.NewPropertyItemID()).MustBuild() + g1 := NewGroup().ID(NewItemID()).MustBuild() + g2 := NewGroup().ID(NewItemID()).MustBuild() + g3 := NewGroup().ID(NewItemID()).MustBuild() + g4 := NewGroup().ID(NewItemID()).MustBuild() testCases := []struct { Name string GL *GroupList - Input id.PropertyItemID + Input ItemID Expected bool }{ { @@ -629,13 +628,13 @@ func TestGroupList_Remove(t *testing.T) { { Name: "success", Input: g1.ID(), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3, g4}).MustBuild(), Expected: true, }, { Name: "not found", Input: g4.ID(), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "xx").Groups([]*Group{g1, g2, g3}).MustBuild(), Expected: false, }, } @@ -652,8 +651,8 @@ func TestGroupList_Remove(t *testing.T) { func TestGroupList_GetOrCreateField(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg := NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - g := NewGroup().ID(id.NewPropertyItemID()).Schema(sg.Schema(), sg.ID()).MustBuild() + sg := NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + g := NewGroup().ID(NewItemID()).Schema(sg.Schema(), sg.ID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -666,8 +665,8 @@ func TestGroupList_GetOrCreateField(t *testing.T) { }{ { Name: "success", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").Groups([]*Group{g}).MustBuild(), - Schema: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").Groups([]*Group{g}).MustBuild(), + Schema: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Ptr: NewPointer(nil, g.IDRef(), sf.ID().Ref()), Expected: struct { Ok bool @@ -679,20 +678,20 @@ func TestGroupList_GetOrCreateField(t *testing.T) { }, { Name: "can't get a group", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), - Schema: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + Schema: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Ptr: NewPointer(nil, g.IDRef(), sf.ID().Ref()), }, { Name: "FieldByItem not ok: sg!=nil", - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").Groups([]*Group{g}).MustBuild(), - Schema: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").Groups([]*Group{g}).MustBuild(), + Schema: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Ptr: NewPointer(sg.IDRef(), g.IDRef(), sf.ID().Ref()), }, { Name: "psg == nil", GL: NewGroupList().NewID().Groups([]*Group{g}).MustBuild(), - Schema: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Schema: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Ptr: NewPointer(nil, g.IDRef(), sf.ID().Ref()), }, } @@ -711,8 +710,8 @@ func TestGroupList_GetOrCreateField(t *testing.T) { func TestGroupList_CreateAndAddListItem(t *testing.T) { getIntRef := func(i int) *int { return &i } sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg := NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - g := NewGroup().ID(id.NewPropertyItemID()).Schema(sg.Schema(), sg.ID()).MustBuild() + sg := NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + g := NewGroup().ID(NewItemID()).Schema(sg.Schema(), sg.ID()).MustBuild() testCases := []struct { Name string GL *GroupList @@ -723,8 +722,8 @@ func TestGroupList_CreateAndAddListItem(t *testing.T) { { Name: "success", Index: getIntRef(0), - GL: NewGroupList().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), - Schema: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + GL: NewGroupList().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + Schema: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Expected: g, }, } diff --git a/pkg/property/group_test.go b/pkg/property/group_test.go index 1321a14c..5f038056 100644 --- a/pkg/property/group_test.go +++ b/pkg/property/group_test.go @@ -4,12 +4,11 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestGroup_IDRef(t *testing.T) { - gid := id.NewPropertyItemID() + gid := NewItemID() var g *Group assert.Nil(t, g.IDRef()) g = NewGroup().ID(gid).MustBuild() @@ -19,9 +18,9 @@ func TestGroup_IDRef(t *testing.T) { func TestGroup_SchemaGroup(t *testing.T) { var g *Group assert.Nil(t, g.SchemaGroupRef()) - assert.Equal(t, id.PropertySchemaGroupID(""), g.SchemaGroup()) - pfid := id.PropertySchemaGroupID("aa") - g = NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), pfid).MustBuild() + assert.Equal(t, SchemaGroupID(""), g.SchemaGroup()) + pfid := SchemaGroupID("aa") + g = NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), pfid).MustBuild() assert.Equal(t, pfid, g.SchemaGroup()) assert.Equal(t, pfid.Ref(), g.SchemaGroupRef()) } @@ -29,7 +28,7 @@ func TestGroup_SchemaGroup(t *testing.T) { func TestGroup_HasLinkedField(t *testing.T) { sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - l := NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l := NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) ls := NewLinks([]*Link{l}) f := NewField(sf).Value(OptionalValueFrom(v)).Link(ls).MustBuild() f2 := NewField(sf).Value(OptionalValueFrom(v)).MustBuild() @@ -67,9 +66,9 @@ func TestGroup_HasLinkedField(t *testing.T) { func TestGroup_IsDatasetLinked(t *testing.T) { sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - l := NewLink(dsid, dssid, id.NewDatasetSchemaFieldID()) + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + l := NewLink(dsid, dssid, NewDatasetFieldID()) ls := NewLinks([]*Link{l}) f := NewField(sf).Value(OptionalValueFrom(v)).Link(ls).MustBuild() f2 := NewField(sf).Value(OptionalValueFrom(v)).MustBuild() @@ -77,8 +76,8 @@ func TestGroup_IsDatasetLinked(t *testing.T) { testCases := []struct { Name string Group *Group - DatasetSchema id.DatasetSchemaID - Dataset id.DatasetID + DatasetSchema DatasetSchemaID + Dataset DatasetID Expected bool }{ { @@ -110,15 +109,15 @@ func TestGroup_IsDatasetLinked(t *testing.T) { func TestGroup_CollectDatasets(t *testing.T) { sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - l := NewLink(dsid, id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + dsid := NewDatasetID() + l := NewLink(dsid, NewDatasetSchemaID(), NewDatasetFieldID()) ls := NewLinks([]*Link{l}) f := NewField(sf).Value(OptionalValueFrom(v)).Link(ls).MustBuild() testCases := []struct { Name string Group *Group - Expected []id.DatasetID + Expected []DatasetID }{ { Name: "nil group", @@ -128,7 +127,7 @@ func TestGroup_CollectDatasets(t *testing.T) { { Name: "normal case", Group: NewGroup().NewID().Fields([]*Field{f}).MustBuild(), - Expected: []id.DatasetID{dsid}, + Expected: []DatasetID{dsid}, }, } for _, tc := range testCases { @@ -144,17 +143,17 @@ func TestGroup_CollectDatasets(t *testing.T) { func TestGroup_FieldsByLinkedDataset(t *testing.T) { sf := NewSchemaField().ID("a").Type(ValueTypeString).MustBuild() v := ValueTypeString.ValueFrom("vvv") - dsid := id.NewDatasetID() - dssid := id.NewDatasetSchemaID() - l := NewLink(dsid, dssid, id.NewDatasetSchemaFieldID()) + dsid := NewDatasetID() + dssid := NewDatasetSchemaID() + l := NewLink(dsid, dssid, NewDatasetFieldID()) ls := NewLinks([]*Link{l}) f := NewField(sf).Value(OptionalValueFrom(v)).Link(ls).MustBuild() testCases := []struct { Name string Group *Group - DatasetSchema id.DatasetSchemaID - DataSet id.DatasetID + DatasetSchema DatasetSchemaID + DataSet DatasetID Expected []*Field }{ { @@ -245,12 +244,12 @@ func TestGroup_Prune(t *testing.T) { func TestGroup_GetOrCreateField(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() f := NewField(sf).MustBuild() - sg := NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg := NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() testCases := []struct { Name string Group *Group PS *Schema - FID id.PropertySchemaFieldID + FID FieldID Expected struct { Field *Field Bool bool @@ -261,17 +260,17 @@ func TestGroup_GetOrCreateField(t *testing.T) { }, { Name: "nil ps", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), }, { Name: "group schema doesn't equal to ps", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aaa"), "aa").MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aaa"), "aa").MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), }, { Name: "create field", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), FID: "aa", Expected: struct { Field *Field @@ -283,8 +282,8 @@ func TestGroup_GetOrCreateField(t *testing.T) { }, { Name: "get field", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").Fields([]*Field{f}).MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").Fields([]*Field{f}).MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), FID: "aa", Expected: struct { Field *Field @@ -316,7 +315,7 @@ func TestGroup_RemoveField(t *testing.T) { testCases := []struct { Name string Group *Group - Input id.PropertySchemaFieldID + Input FieldID Expected []*Field }{ @@ -350,7 +349,7 @@ func TestGroup_FieldIDs(t *testing.T) { testCases := []struct { Name string Group *Group - Expected []id.PropertySchemaFieldID + Expected []FieldID }{ { @@ -359,7 +358,7 @@ func TestGroup_FieldIDs(t *testing.T) { { Name: "normal case", Group: NewGroup().NewID().Fields([]*Field{f, f2}).MustBuild(), - Expected: []id.PropertySchemaFieldID{"a", "b"}, + Expected: []FieldID{"a", "b"}, }, } for _, tc := range testCases { @@ -382,7 +381,7 @@ func TestGroup_Field(t *testing.T) { testCases := []struct { Name string Group *Group - Input id.PropertySchemaFieldID + Input FieldID Expected *Field }{ @@ -415,14 +414,14 @@ func TestGroup_Field(t *testing.T) { func TestGroup_UpdateNameFieldValue(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() //f := NewField(sf).MustBuild() - sg := NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - sg2 := NewSchemaGroup().ID("bb").Schema(id.MustPropertySchemaID("xx~1.0.0/bb")).Fields([]*SchemaField{sf}).MustBuild() + sg := NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg2 := NewSchemaGroup().ID("bb").Schema(MustSchemaID("xx~1.0.0/bb")).Fields([]*SchemaField{sf}).MustBuild() testCases := []struct { Name string Group *Group PS *Schema Value *Value - FID id.PropertySchemaFieldID + FID FieldID Expected *Field Err error }{ @@ -431,25 +430,25 @@ func TestGroup_UpdateNameFieldValue(t *testing.T) { }, { Name: "nil ps", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), }, { Name: "group schema doesn't equal to ps", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aaa"), "aa").MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aaa"), "aa").MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), }, { Name: "update value", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/aa")).Groups([]*SchemaGroup{sg}).MustBuild(), Value: ValueTypeString.ValueFrom("abc"), FID: "aa", Expected: NewField(sf).Value(OptionalValueFrom(ValueTypeString.ValueFrom("abc"))).MustBuild(), }, { Name: "invalid property field", - Group: NewGroup().NewID().Schema(id.MustPropertySchemaID("xx~1.0.0/aa"), "aa").MustBuild(), - PS: NewSchema().ID(id.MustPropertySchemaID("xx~1.0.0/bb")).Groups([]*SchemaGroup{sg2}).MustBuild(), + Group: NewGroup().NewID().Schema(MustSchemaID("xx~1.0.0/aa"), "aa").MustBuild(), + PS: NewSchema().ID(MustSchemaID("xx~1.0.0/bb")).Groups([]*SchemaGroup{sg2}).MustBuild(), Value: ValueTypeString.ValueFrom("abc"), FID: "aa", Expected: nil, diff --git a/pkg/property/id.go b/pkg/property/id.go new file mode 100644 index 00000000..9fb862f9 --- /dev/null +++ b/pkg/property/id.go @@ -0,0 +1,71 @@ +package property + +import ( + "sort" + + "github.com/reearth/reearth-backend/pkg/id" +) + +type ID = id.PropertyID +type ItemID = id.PropertyItemID +type FieldID = id.PropertySchemaFieldID +type SchemaID = id.PropertySchemaID +type SchemaGroupID = id.PropertySchemaGroupID +type DatasetID = id.DatasetID +type DatasetFieldID = id.DatasetSchemaFieldID +type DatasetSchemaID = id.DatasetSchemaID +type SceneID = id.SceneID + +var NewID = id.NewPropertyID +var NewItemID = id.NewPropertyItemID +var NewDatasetID = id.NewDatasetID +var NewDatasetFieldID = id.NewDatasetSchemaFieldID +var NewDatasetSchemaID = id.NewDatasetSchemaID +var NewSceneID = id.NewSceneID + +var MustID = id.MustPropertyID +var MustItemID = id.MustPropertyItemID +var MustSchemaID = id.MustPropertySchemaID +var MustDatasetID = id.MustDatasetID +var MustDatasetFieldID = id.MustDatasetSchemaFieldID +var MustDatasetSchemaID = id.MustDatasetSchemaID +var MustSceneID = id.MustSceneID + +var IDFrom = id.PropertyIDFrom +var ItemIDFrom = id.PropertyItemIDFrom +var FieldIDFrom = id.PropertySchemaFieldIDFrom +var SchemaIDFrom = id.PropertySchemaIDFrom +var SchemaGroupIDFrom = id.PropertySchemaGroupIDFrom +var DatasetIDFrom = id.DatasetIDFrom +var DatasetFieldIDFrom = id.DatasetSchemaFieldIDFrom +var DatasetSchemaIDFrom = id.DatasetSchemaIDFrom +var SceneIDFrom = id.SceneIDFrom + +var IDFromRef = id.PropertyIDFromRef +var ItemIDFromRef = id.PropertyItemIDFromRef +var SchemaIDFromRef = id.PropertySchemaIDFromRef +var DatasetIDFromRef = id.DatasetIDFromRef +var DatasetFieldIDFromRef = id.DatasetSchemaFieldIDFromRef +var DatasetSchemaIDFromRef = id.DatasetSchemaIDFromRef +var SceneIDFromRef = id.SceneIDFromRef + +var IDFromRefID = id.PropertyIDFromRefID +var ItemIDFromRefID = id.PropertyItemIDFromRefID +var DatasetIDFromRefID = id.DatasetIDFromRefID +var DatasetFieldIDFromRefID = id.DatasetSchemaFieldIDFromRefID +var DatasetSchemaIDFromRefID = id.DatasetSchemaIDFromRefID +var SceneIDFromRefID = id.SceneIDFromRefID + +type IDSet = id.PropertyIDSet +type ItemIDSet = id.PropertyItemIDSet + +var NewIDSet = id.NewPropertyIDSet +var NewItemIDSet = id.NewPropertyItemIDSet + +var ErrInvalidID = id.ErrInvalidID + +func sortIDs(a []ID) { + sort.SliceStable(a, func(i, j int) bool { + return id.ID(a[i]).Compare(id.ID(a[j])) < 0 + }) +} diff --git a/pkg/property/id_test.go b/pkg/property/id_test.go new file mode 100644 index 00000000..137bb595 --- /dev/null +++ b/pkg/property/id_test.go @@ -0,0 +1,9 @@ +package property + +func mockNewItemID(id ItemID) func() { + original := NewItemID + NewItemID = func() ItemID { return id } + return func() { + NewItemID = original + } +} diff --git a/pkg/property/initializer.go b/pkg/property/initializer.go index aff489fe..77a6779d 100644 --- a/pkg/property/initializer.go +++ b/pkg/property/initializer.go @@ -4,16 +4,14 @@ package property import ( "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) var ErrSchemaDoesNotMatch = errors.New("schema of the initializer does not match schema of the argument") type Initializer struct { - ID *id.PropertyID `json:"id"` - Schema id.PropertySchemaID `json:"schema"` - Items []*InitializerItem `json:"items"` + ID *ID `json:"id"` + Schema SchemaID `json:"schema"` + Items []*InitializerItem `json:"items"` } func (p *Initializer) Clone() *Initializer { @@ -36,14 +34,14 @@ func (p *Initializer) Clone() *Initializer { } } -func (p *Initializer) Property(scene id.SceneID) (*Property, error) { +func (p *Initializer) Property(scene SceneID) (*Property, error) { if p == nil { return nil, nil } i := p.ID if i == nil { - i = id.NewPropertyID().Ref() + i = NewID().Ref() } var items []Item @@ -62,7 +60,7 @@ func (p *Initializer) Property(scene id.SceneID) (*Property, error) { } // PropertyIncludingEmpty generates a new property, but even if the initializer is empty, an empty property will be generated. -func (p *Initializer) PropertyIncludingEmpty(scene id.SceneID, schema id.PropertySchemaID) (*Property, error) { +func (p *Initializer) PropertyIncludingEmpty(scene SceneID, schema SchemaID) (*Property, error) { if p != nil && p.Schema != schema { return nil, ErrSchemaDoesNotMatch } @@ -82,7 +80,7 @@ func (p *Initializer) PropertyIncludingEmpty(scene id.SceneID, schema id.Propert return pr, nil } -func (p *Initializer) MustBeProperty(scene id.SceneID) *Property { +func (p *Initializer) MustBeProperty(scene SceneID) *Property { r, err := p.Property(scene) if err != nil { panic(err) @@ -91,10 +89,10 @@ func (p *Initializer) MustBeProperty(scene id.SceneID) *Property { } type InitializerItem struct { - ID *id.PropertyItemID `json:"id"` - SchemaItem id.PropertySchemaGroupID `json:"schemaItem"` - Groups []*InitializerGroup `json:"groups"` - Fields []*InitializerField `json:"fields"` + ID *ItemID `json:"id"` + SchemaItem SchemaGroupID `json:"schemaItem"` + Groups []*InitializerGroup `json:"groups"` + Fields []*InitializerField `json:"fields"` } func (p *InitializerItem) Clone() *InitializerItem { @@ -126,14 +124,14 @@ func (p *InitializerItem) Clone() *InitializerItem { } } -func (p *InitializerItem) PropertyItem(parent id.PropertySchemaID) (Item, error) { +func (p *InitializerItem) PropertyItem(parent SchemaID) (Item, error) { if p == nil { return nil, nil } i := p.ID if i == nil { - i = id.NewPropertyItemID().Ref() + i = NewItemID().Ref() } pi := NewItem().ID(*i).Schema(parent, p.SchemaItem) @@ -166,7 +164,7 @@ func (p *InitializerItem) PropertyItem(parent id.PropertySchemaID) (Item, error) return pi.Group().Fields(fields).Build() } -func (p *InitializerItem) PropertyGroupList(parent id.PropertySchemaID) *GroupList { +func (p *InitializerItem) PropertyGroupList(parent SchemaID) *GroupList { i, _ := p.PropertyItem(parent) if g := ToGroupList(i); g != nil { return g @@ -174,7 +172,7 @@ func (p *InitializerItem) PropertyGroupList(parent id.PropertySchemaID) *GroupLi return nil } -func (p *InitializerItem) PropertyGroup(parent id.PropertySchemaID) *Group { +func (p *InitializerItem) PropertyGroup(parent SchemaID) *Group { i, _ := p.PropertyItem(parent) if g := ToGroup(i); g != nil { return g @@ -183,7 +181,7 @@ func (p *InitializerItem) PropertyGroup(parent id.PropertySchemaID) *Group { } type InitializerGroup struct { - ID *id.PropertyItemID `json:"id"` + ID *ItemID `json:"id"` Fields []*InitializerField `json:"fields"` } @@ -206,14 +204,14 @@ func (p *InitializerGroup) Clone() *InitializerGroup { } } -func (p *InitializerGroup) PropertyGroup(parent id.PropertySchemaID, parentItem id.PropertySchemaGroupID) (*Group, error) { +func (p *InitializerGroup) PropertyGroup(parent SchemaID, parentItem SchemaGroupID) (*Group, error) { if p == nil { return nil, nil } i := p.ID if i == nil { - i = id.NewPropertyItemID().Ref() + i = NewItemID().Ref() } pi := NewItem().ID(*i).Schema(parent, parentItem) @@ -232,10 +230,10 @@ func (p *InitializerGroup) PropertyGroup(parent id.PropertySchemaID, parentItem } type InitializerField struct { - Field id.PropertySchemaFieldID `json:"field"` - Type ValueType `json:"type"` - Value *Value `json:"value"` - Links []*InitializerLink `json:"links"` + Field FieldID `json:"field"` + Type ValueType `json:"type"` + Value *Value `json:"value"` + Links []*InitializerLink `json:"links"` } func (p *InitializerField) Clone() *InitializerField { @@ -280,9 +278,9 @@ func (p *InitializerField) PropertyField() *Field { } type InitializerLink struct { - Dataset *id.DatasetID `json:"dataset"` - Schema id.DatasetSchemaID `json:"schema"` - Field id.DatasetSchemaFieldID `json:"field"` + Dataset *DatasetID `json:"dataset"` + Schema DatasetSchemaID `json:"schema"` + Field DatasetFieldID `json:"field"` } func (p *InitializerLink) Clone() *InitializerLink { diff --git a/pkg/property/initializer_test.go b/pkg/property/initializer_test.go index ebd6fe1e..980039bd 100644 --- a/pkg/property/initializer_test.go +++ b/pkg/property/initializer_test.go @@ -3,17 +3,16 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestInitializer_Clone(t *testing.T) { initializer := &Initializer{ - ID: id.NewPropertyID().Ref(), - Schema: id.MustPropertySchemaID("reearth/marker"), + ID: NewID().Ref(), + Schema: MustSchemaID("reearth/marker"), Items: []*InitializerItem{{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), }}, } @@ -26,13 +25,13 @@ func TestInitializer_Clone(t *testing.T) { } func TestInitializer_Property(t *testing.T) { - sid := id.NewSceneID() + sid := NewSceneID() initializer := &Initializer{ - ID: id.NewPropertyID().Ref(), - Schema: id.MustPropertySchemaID("reearth/marker"), + ID: NewID().Ref(), + Schema: MustSchemaID("reearth/marker"), Items: []*InitializerItem{{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), }}, } @@ -52,9 +51,9 @@ func TestInitializer_Property(t *testing.T) { } func TestInitializer_PropertyIncludingEmpty(t *testing.T) { - sid := id.NewSceneID() - psid := id.MustPropertySchemaID("reearth/hoge") - psid2 := id.MustPropertySchemaID("reearth/marker") + sid := NewSceneID() + psid := MustSchemaID("reearth/hoge") + psid2 := MustSchemaID("reearth/marker") // test case 1: should generate an empty property var initializer *Initializer @@ -65,11 +64,11 @@ func TestInitializer_PropertyIncludingEmpty(t *testing.T) { // test case 2: should returns an error when schema does not match initializer = &Initializer{ - ID: id.NewPropertyID().Ref(), + ID: NewID().Ref(), Schema: psid2, Items: []*InitializerItem{{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), }}, } @@ -87,18 +86,18 @@ func TestInitializer_PropertyIncludingEmpty(t *testing.T) { func TestInitializerItem_Clone(t *testing.T) { item := &InitializerItem{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), Groups: []*InitializerGroup{{ - ID: id.NewPropertyItemID().Ref(), + ID: NewItemID().Ref(), Fields: []*InitializerField{{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), Links: []*InitializerLink{{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), }}, }}, }}, @@ -115,10 +114,10 @@ func TestInitializerItem_Clone(t *testing.T) { } func TestInitializerItem_PropertyItem(t *testing.T) { - parent := id.MustPropertySchemaID("reearth/marker") + parent := MustSchemaID("reearth/marker") item := &InitializerItem{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), } expected := NewItem().ID(*item.ID).Schema(parent, item.SchemaItem).Group().MustBuild() @@ -134,12 +133,12 @@ func TestInitializerItem_PropertyItem(t *testing.T) { } func TestInitializerItem_PropertyGroup(t *testing.T) { - parent := id.MustPropertySchemaID("reearth/marker") + parent := MustSchemaID("reearth/marker") item := &InitializerItem{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), Fields: []*InitializerField{{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), }}, @@ -157,12 +156,12 @@ func TestInitializerItem_PropertyGroup(t *testing.T) { } func TestInitializerItem_PropertyGroupList(t *testing.T) { - parent := id.MustPropertySchemaID("reearth/marker") + parent := MustSchemaID("reearth/marker") item := &InitializerItem{ - ID: id.NewPropertyItemID().Ref(), - SchemaItem: id.PropertySchemaGroupID("hoge"), + ID: NewItemID().Ref(), + SchemaItem: SchemaGroupID("hoge"), Groups: []*InitializerGroup{{ - ID: id.NewPropertyItemID().Ref(), + ID: NewItemID().Ref(), }}, } @@ -179,15 +178,15 @@ func TestInitializerItem_PropertyGroupList(t *testing.T) { func TestInitializerGroup_Clone(t *testing.T) { item := &InitializerGroup{ - ID: id.NewPropertyItemID().Ref(), + ID: NewItemID().Ref(), Fields: []*InitializerField{{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), Links: []*InitializerLink{{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), }}, }}, } @@ -201,12 +200,12 @@ func TestInitializerGroup_Clone(t *testing.T) { } func TestInitializerGroup_PropertyGroup(t *testing.T) { - parent := id.MustPropertySchemaID("reearth/marker") - parentItem := id.PropertySchemaGroupID("hoge") + parent := MustSchemaID("reearth/marker") + parentItem := SchemaGroupID("hoge") item := &InitializerGroup{ - ID: id.NewPropertyItemID().Ref(), + ID: NewItemID().Ref(), Fields: []*InitializerField{{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), }}, @@ -229,13 +228,13 @@ func TestInitializerGroup_PropertyGroup(t *testing.T) { func TestInitializerField_Clone(t *testing.T) { field := &InitializerField{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), Links: []*InitializerLink{{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), }}, } cloned := field.Clone() @@ -247,13 +246,13 @@ func TestInitializerField_Clone(t *testing.T) { func TestInitializerField_PropertyField(t *testing.T) { field := &InitializerField{ - Field: id.PropertySchemaFieldID("name"), + Field: FieldID("name"), Type: ValueTypeString, Value: ValueTypeString.ValueFrom("aaa"), Links: []*InitializerLink{{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), }}, } @@ -268,9 +267,9 @@ func TestInitializerField_PropertyField(t *testing.T) { func TestInitializerLink_Clone(t *testing.T) { link := &InitializerLink{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), } cloned := link.Clone() @@ -280,9 +279,9 @@ func TestInitializerLink_Clone(t *testing.T) { func TestInitializerLink_PropertyLink(t *testing.T) { link := &InitializerLink{ - Dataset: id.NewDatasetID().Ref(), - Schema: id.NewDatasetSchemaID(), - Field: id.NewDatasetSchemaFieldID(), + Dataset: NewDatasetID().Ref(), + Schema: NewDatasetSchemaID(), + Field: NewDatasetFieldID(), } expected := NewLink(*link.Dataset.CopyRef(), link.Schema, link.Field) diff --git a/pkg/property/item.go b/pkg/property/item.go index 65807e0b..5128be84 100644 --- a/pkg/property/item.go +++ b/pkg/property/item.go @@ -4,20 +4,19 @@ import ( "context" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) type Item interface { - ID() id.PropertyItemID - IDRef() *id.PropertyItemID - SchemaGroup() id.PropertySchemaGroupID - SchemaGroupRef() *id.PropertySchemaGroupID - Schema() id.PropertySchemaID - SchemaRef() *id.PropertySchemaID + ID() ItemID + IDRef() *ItemID + SchemaGroup() SchemaGroupID + SchemaGroupRef() *SchemaGroupID + Schema() SchemaID + SchemaRef() *SchemaID HasLinkedField() bool - CollectDatasets() []id.DatasetID - FieldsByLinkedDataset(id.DatasetSchemaID, id.DatasetID) []*Field - IsDatasetLinked(id.DatasetSchemaID, id.DatasetID) bool + CollectDatasets() []DatasetID + FieldsByLinkedDataset(DatasetSchemaID, DatasetID) []*Field + IsDatasetLinked(DatasetSchemaID, DatasetID) bool IsEmpty() bool Prune() MigrateSchema(context.Context, *Schema, dataset.Loader) @@ -26,9 +25,9 @@ type Item interface { } type itemBase struct { - ID id.PropertyItemID - Schema id.PropertySchemaID - SchemaGroup id.PropertySchemaGroupID + ID ItemID + Schema SchemaID + SchemaGroup SchemaGroupID } func ToGroup(i Item) *Group { diff --git a/pkg/property/item_builder.go b/pkg/property/item_builder.go index 67c8d21e..fae398b2 100644 --- a/pkg/property/item_builder.go +++ b/pkg/property/item_builder.go @@ -1,7 +1,5 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - type ItemBuilder struct { base itemBase } @@ -18,17 +16,17 @@ func (b *ItemBuilder) GroupList() *GroupListBuilder { return NewGroupList().base(b.base) } -func (b *ItemBuilder) ID(id id.PropertyItemID) *ItemBuilder { +func (b *ItemBuilder) ID(id ItemID) *ItemBuilder { b.base.ID = id return b } func (b *ItemBuilder) NewID() *ItemBuilder { - b.base.ID = id.NewPropertyItemID() + b.base.ID = NewItemID() return b } -func (b *ItemBuilder) Schema(s id.PropertySchemaID, g id.PropertySchemaGroupID) *ItemBuilder { +func (b *ItemBuilder) Schema(s SchemaID, g SchemaGroupID) *ItemBuilder { b.base.Schema = s b.base.SchemaGroup = g return b diff --git a/pkg/property/item_test.go b/pkg/property/item_test.go index 8ff6eff3..887f469e 100644 --- a/pkg/property/item_test.go +++ b/pkg/property/item_test.go @@ -3,17 +3,16 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestInitItemFrom(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg := NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - sgl := NewSchemaGroup().ID("aa").IsList(true).Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - iid := id.NewPropertyItemID() - propertySchemaID := id.MustPropertySchemaID("xx~1.0.0/aa") - propertySchemaField1ID := id.PropertySchemaGroupID("aa") + sg := NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sgl := NewSchemaGroup().ID("aa").IsList(true).Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + iid := NewItemID() + propertySchemaID := MustSchemaID("xx~1.0.0/aa") + propertySchemaField1ID := SchemaGroupID("aa") testCases := []struct { Name string SG *SchemaGroup @@ -50,10 +49,10 @@ func TestInitItemFrom(t *testing.T) { } func TestToGroup(t *testing.T) { - iid := id.NewPropertyItemID() - propertySchemaID := id.MustPropertySchemaID("xxx~1.1.1/aa") - propertySchemaField1ID := id.PropertySchemaFieldID("a") - propertySchemaGroup1ID := id.PropertySchemaGroupID("A") + iid := NewItemID() + propertySchemaID := MustSchemaID("xxx~1.1.1/aa") + propertySchemaField1ID := FieldID("a") + propertySchemaGroup1ID := SchemaGroupID("A") il := []Item{ NewGroup().ID(iid).Schema(propertySchemaID, propertySchemaGroup1ID). Fields([]*Field{ @@ -63,7 +62,7 @@ func TestToGroup(t *testing.T) { Build(), }).MustBuild(), } - p := New().NewID().Scene(id.NewSceneID()).Items(il).Schema(propertySchemaID).MustBuild() + p := New().NewID().Scene(NewSceneID()).Items(il).Schema(propertySchemaID).MustBuild() g := ToGroup(p.ItemBySchema(propertySchemaGroup1ID)) assert.Equal(t, propertySchemaID, g.Schema()) assert.Equal(t, propertySchemaGroup1ID, g.SchemaGroup()) @@ -71,13 +70,13 @@ func TestToGroup(t *testing.T) { } func TestToGroupList(t *testing.T) { - iid := id.NewPropertyItemID() - propertySchemaID := id.MustPropertySchemaID("xxx~1.1.1/aa") - propertySchemaGroup1ID := id.PropertySchemaGroupID("A") + iid := NewItemID() + propertySchemaID := MustSchemaID("xxx~1.1.1/aa") + propertySchemaGroup1ID := SchemaGroupID("A") il := []Item{ NewGroupList().ID(iid).Schema(propertySchemaID, propertySchemaGroup1ID).MustBuild(), } - p := New().NewID().Scene(id.NewSceneID()).Items(il).Schema(propertySchemaID).MustBuild() + p := New().NewID().Scene(NewSceneID()).Items(il).Schema(propertySchemaID).MustBuild() g := ToGroupList(p.ItemBySchema(propertySchemaGroup1ID)) assert.Equal(t, propertySchemaID, g.Schema()) assert.Equal(t, propertySchemaGroup1ID, g.SchemaGroup()) diff --git a/pkg/property/link.go b/pkg/property/link.go index e1f62a06..4fb8df40 100644 --- a/pkg/property/link.go +++ b/pkg/property/link.go @@ -4,22 +4,18 @@ import ( "context" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) -// Links _ type Links struct { links []*Link } -// Link _ type Link struct { - dataset *id.DatasetID - schema *id.DatasetSchemaID - field *id.DatasetSchemaFieldID + dataset *DatasetID + schema *DatasetSchemaID + field *DatasetFieldID } -// NewLinks _ func NewLinks(links []*Link) *Links { if links == nil { return nil @@ -34,7 +30,6 @@ func NewLinks(links []*Link) *Links { } } -// Clone _ func (l *Links) Clone() *Links { if l == nil { return nil @@ -44,17 +39,14 @@ func (l *Links) Clone() *Links { } } -// IsLinked _ func (l *Links) IsLinked() bool { return l != nil && l.links != nil && len(l.links) > 0 } -// IsLinkedFully _ func (l *Links) IsLinkedFully() bool { return l != nil && l.links != nil && len(l.links) > 0 && len(l.DatasetIDs()) == len(l.links) } -// Len _ func (l *Links) Len() int { if l == nil || l.links == nil { return 0 @@ -62,7 +54,6 @@ func (l *Links) Len() int { return len(l.links) } -// First _ func (l *Links) First() *Link { if l == nil || l.links == nil || len(l.links) == 0 { return nil @@ -70,7 +61,6 @@ func (l *Links) First() *Link { return l.links[0] } -// Last _ func (l *Links) Last() *Link { if l == nil || l.links == nil || len(l.links) == 0 { return nil @@ -78,12 +68,10 @@ func (l *Links) Last() *Link { return l.links[len(l.links)-1] } -// LastValue _ func (l *Links) LastValue(ds *dataset.Dataset) *dataset.Value { return l.Last().Value(ds) } -// Validate _ func (l *Links) Validate(dsm dataset.SchemaMap, dm dataset.Map) bool { if l == nil || l.links == nil { return false @@ -111,11 +99,10 @@ func (l *Links) Validate(dsm dataset.SchemaMap, dm dataset.Map) bool { return true } -// Replace _ func (l *Links) Replace( - dsm map[id.DatasetSchemaID]id.DatasetSchemaID, - dm map[id.DatasetID]id.DatasetID, - fm map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID, + dsm map[DatasetSchemaID]DatasetSchemaID, + dm map[DatasetID]DatasetID, + fm map[DatasetFieldID]DatasetFieldID, ) { if l == nil || l.links == nil { return @@ -168,7 +155,6 @@ func (l *Links) Replace( l.links = links } -// Links _ func (l *Links) Links() []*Link { if l == nil || l.links == nil || len(l.links) == 0 { return nil @@ -181,12 +167,11 @@ func (l *Links) Links() []*Link { return links2 } -// DatasetIDs _ -func (l *Links) DatasetIDs() []id.DatasetID { +func (l *Links) DatasetIDs() []DatasetID { if l == nil { return nil } - datasets := make([]id.DatasetID, 0, len(l.links)) + datasets := make([]DatasetID, 0, len(l.links)) for _, i := range l.links { if i.dataset != nil { datasets = append(datasets, *i.dataset) @@ -197,12 +182,11 @@ func (l *Links) DatasetIDs() []id.DatasetID { return datasets } -// DatasetSchemaIDs _ -func (l *Links) DatasetSchemaIDs() []id.DatasetSchemaID { +func (l *Links) DatasetSchemaIDs() []DatasetSchemaID { if l == nil { return nil } - schemas := make([]id.DatasetSchemaID, 0, len(l.links)) + schemas := make([]DatasetSchemaID, 0, len(l.links)) for _, i := range l.links { if i.schema != nil { schemas = append(schemas, *i.schema) @@ -213,8 +197,7 @@ func (l *Links) DatasetSchemaIDs() []id.DatasetSchemaID { return schemas } -// IsDatasetLinked _ -func (l *Links) IsDatasetLinked(s id.DatasetSchemaID, dsid id.DatasetID) bool { +func (l *Links) IsDatasetLinked(s DatasetSchemaID, dsid DatasetID) bool { if l == nil { return false } @@ -231,12 +214,11 @@ func (l *Links) IsDatasetLinked(s id.DatasetSchemaID, dsid id.DatasetID) bool { return false } -// DatasetSchemaFieldIDs _ -func (l *Links) DatasetSchemaFieldIDs() []id.DatasetSchemaFieldID { +func (l *Links) DatasetSchemaFieldIDs() []DatasetFieldID { if l == nil { return nil } - fields := make([]id.DatasetSchemaFieldID, 0, len(l.links)) + fields := make([]DatasetFieldID, 0, len(l.links)) for _, i := range l.links { if i.field != nil { fields = append(fields, *i.field) @@ -247,8 +229,7 @@ func (l *Links) DatasetSchemaFieldIDs() []id.DatasetSchemaFieldID { return fields } -// HasDataset _ -func (l *Links) HasDataset(did id.DatasetID) bool { +func (l *Links) HasDataset(did DatasetID) bool { if l == nil { return false } @@ -260,8 +241,7 @@ func (l *Links) HasDataset(did id.DatasetID) bool { return false } -// HasDatasetSchema _ -func (l *Links) HasDatasetSchema(dsid id.DatasetSchemaID) bool { +func (l *Links) HasDatasetSchema(dsid DatasetSchemaID) bool { if l == nil { return false } @@ -273,7 +253,7 @@ func (l *Links) HasDatasetSchema(dsid id.DatasetSchemaID) bool { return false } -func (l *Links) HasDatasetOrSchema(dsid id.DatasetSchemaID, did id.DatasetID) bool { +func (l *Links) HasDatasetOrSchema(dsid DatasetSchemaID, did DatasetID) bool { if l == nil { return false } @@ -285,8 +265,7 @@ func (l *Links) HasDatasetOrSchema(dsid id.DatasetSchemaID, did id.DatasetID) bo return false } -// NewLink _ -func NewLink(d id.DatasetID, ds id.DatasetSchemaID, f id.DatasetSchemaFieldID) *Link { +func NewLink(d DatasetID, ds DatasetSchemaID, f DatasetFieldID) *Link { dataset := d schema := ds field := f @@ -297,8 +276,7 @@ func NewLink(d id.DatasetID, ds id.DatasetSchemaID, f id.DatasetSchemaFieldID) * } } -// NewLinkFieldOnly _ -func NewLinkFieldOnly(ds id.DatasetSchemaID, f id.DatasetSchemaFieldID) *Link { +func NewLinkFieldOnly(ds DatasetSchemaID, f DatasetFieldID) *Link { schema := ds field := f return &Link{ @@ -307,8 +285,7 @@ func NewLinkFieldOnly(ds id.DatasetSchemaID, f id.DatasetSchemaFieldID) *Link { } } -// Dataset _ -func (l *Link) Dataset() *id.DatasetID { +func (l *Link) Dataset() *DatasetID { if l == nil || l.dataset == nil { return nil } @@ -316,8 +293,7 @@ func (l *Link) Dataset() *id.DatasetID { return &dataset } -// DatasetSchema _ -func (l *Link) DatasetSchema() *id.DatasetSchemaID { +func (l *Link) DatasetSchema() *DatasetSchemaID { if l == nil || l.schema == nil { return nil } @@ -325,8 +301,7 @@ func (l *Link) DatasetSchema() *id.DatasetSchemaID { return &datasetSchema } -// DatasetSchemaField _ -func (l *Link) DatasetSchemaField() *id.DatasetSchemaFieldID { +func (l *Link) DatasetSchemaField() *DatasetFieldID { if l == nil || l.field == nil { return nil } @@ -334,7 +309,6 @@ func (l *Link) DatasetSchemaField() *id.DatasetSchemaFieldID { return &field } -// Value _ func (l *Link) Value(ds *dataset.Dataset) *dataset.Value { if l == nil || ds == nil || l.dataset == nil || l.field == nil || ds.ID() != *l.dataset { return nil @@ -346,7 +320,6 @@ func (l *Link) Value(ds *dataset.Dataset) *dataset.Value { return f.Value() } -// Validate _ func (l *Link) Validate(dss *dataset.Schema, ds *dataset.Dataset) bool { if l == nil || l.field == nil || l.schema == nil || dss == nil { return false @@ -373,12 +346,10 @@ func (l *Link) Validate(dss *dataset.Schema, ds *dataset.Dataset) bool { return true } -// IsEmpty _ func (l *Links) IsEmpty() bool { return l == nil || l.links == nil || len(l.links) == 0 } -// Clone _ func (l *Link) Clone() *Link { if l == nil { return nil @@ -390,8 +361,7 @@ func (l *Link) Clone() *Link { } } -// ApplyDataset _ -func (l *Link) ApplyDataset(ds *id.DatasetID) *Link { +func (l *Link) ApplyDataset(ds *DatasetID) *Link { if l == nil { return nil } @@ -407,8 +377,7 @@ func (l *Link) ApplyDataset(ds *id.DatasetID) *Link { } } -// ApplyDataset _ -func (l *Links) ApplyDataset(ds *id.DatasetID) *Links { +func (l *Links) ApplyDataset(ds *DatasetID) *Links { if l == nil || l.links == nil || len(l.links) == 0 { return nil } diff --git a/pkg/property/link_test.go b/pkg/property/link_test.go index 706b8565..5f2c2c94 100644 --- a/pkg/property/link_test.go +++ b/pkg/property/link_test.go @@ -5,17 +5,16 @@ import ( "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestNewLinks(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - dsid2 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - did2 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() - dfid2 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + dsid2 := NewDatasetSchemaID() + did1 := NewDatasetID() + did2 := NewDatasetID() + dfid1 := NewDatasetFieldID() + dfid2 := NewDatasetFieldID() var lin *Links assert.Nil(t, lin) @@ -27,17 +26,17 @@ func TestNewLinks(t *testing.T) { assert.Equal(t, 0, lin.Len()) lin = NewLinks([]*Link{}) - assert.Equal(t, []id.DatasetID{}, lin.DatasetIDs()) - assert.Equal(t, []id.DatasetSchemaID{}, lin.DatasetSchemaIDs()) - assert.Equal(t, []id.DatasetSchemaFieldID{}, lin.DatasetSchemaFieldIDs()) + assert.Equal(t, []DatasetID{}, lin.DatasetIDs()) + assert.Equal(t, []DatasetSchemaID{}, lin.DatasetSchemaIDs()) + assert.Equal(t, []DatasetFieldID{}, lin.DatasetSchemaFieldIDs()) ll := []*Link{ NewLink(did1, dsid1, dfid1), NewLink(did2, dsid2, dfid2), } - dl := []id.DatasetID{did1, did2} - dsl := []id.DatasetSchemaID{dsid1, dsid2} - dsfl := []id.DatasetSchemaFieldID{dfid1, dfid2} + dl := []DatasetID{did1, did2} + dsl := []DatasetSchemaID{dsid1, dsid2} + dsfl := []DatasetFieldID{dfid1, dfid2} lin = NewLinks(ll) assert.NotNil(t, lin) assert.Equal(t, ll, lin.Links()) @@ -50,19 +49,19 @@ func TestNewLinks(t *testing.T) { } func TestLinks_IsDatasetLinked(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - dsid2 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - did2 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + dsid2 := NewDatasetSchemaID() + did1 := NewDatasetID() + did2 := NewDatasetID() + dfid1 := NewDatasetFieldID() ll := []*Link{ NewLink(did1, dsid1, dfid1), } testCases := []struct { Name string - DSS id.DatasetSchemaID - DS id.DatasetID + DSS DatasetSchemaID + DS DatasetID Links *Links Expected bool }{ @@ -100,9 +99,9 @@ func TestLinks_IsDatasetLinked(t *testing.T) { } func TestLinks_Validate(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string @@ -155,18 +154,18 @@ func TestLinks_Validate(t *testing.T) { } func TestLinks_Replace(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - dsid2 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - did2 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() - dfid2 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + dsid2 := NewDatasetSchemaID() + did1 := NewDatasetID() + did2 := NewDatasetID() + dfid1 := NewDatasetFieldID() + dfid2 := NewDatasetFieldID() testCases := []struct { Name string - DSM map[id.DatasetSchemaID]id.DatasetSchemaID - DM map[id.DatasetID]id.DatasetID - FM map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID + DSM map[DatasetSchemaID]DatasetSchemaID + DM map[DatasetID]DatasetID + FM map[DatasetFieldID]DatasetFieldID Expected, Links *Links }{ { @@ -174,13 +173,13 @@ func TestLinks_Replace(t *testing.T) { }, { Name: "success", - DSM: map[id.DatasetSchemaID]id.DatasetSchemaID{ + DSM: map[DatasetSchemaID]DatasetSchemaID{ dsid1: dsid2, }, - DM: map[id.DatasetID]id.DatasetID{ + DM: map[DatasetID]DatasetID{ did1: did2, }, - FM: map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID{ + FM: map[DatasetFieldID]DatasetFieldID{ dfid1: dfid2, }, Links: NewLinks([]*Link{NewLink(did1, dsid1, dfid1)}), @@ -188,35 +187,35 @@ func TestLinks_Replace(t *testing.T) { }, { Name: "dataset = nil", - DSM: map[id.DatasetSchemaID]id.DatasetSchemaID{ + DSM: map[DatasetSchemaID]DatasetSchemaID{ dsid1: dsid2, }, - DM: map[id.DatasetID]id.DatasetID{}, - FM: map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID{ + DM: map[DatasetID]DatasetID{}, + FM: map[DatasetFieldID]DatasetFieldID{ dfid1: dfid2, }, Links: NewLinks([]*Link{NewLink(did1, dsid1, dfid1)}), }, { Name: "datasetschema = nil", - DSM: map[id.DatasetSchemaID]id.DatasetSchemaID{}, - DM: map[id.DatasetID]id.DatasetID{ + DSM: map[DatasetSchemaID]DatasetSchemaID{}, + DM: map[DatasetID]DatasetID{ did1: did2, }, - FM: map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID{ + FM: map[DatasetFieldID]DatasetFieldID{ dfid1: dfid2, }, Links: NewLinks([]*Link{NewLink(did1, dsid1, dfid1)}), }, { Name: "dataset schema field = nil", - DSM: map[id.DatasetSchemaID]id.DatasetSchemaID{ + DSM: map[DatasetSchemaID]DatasetSchemaID{ dsid1: dsid2, }, - DM: map[id.DatasetID]id.DatasetID{ + DM: map[DatasetID]DatasetID{ did1: did2, }, - FM: map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID{}, + FM: map[DatasetFieldID]DatasetFieldID{}, Links: NewLinks([]*Link{NewLink(did1, dsid1, dfid1)}), }, } @@ -231,13 +230,13 @@ func TestLinks_Replace(t *testing.T) { } func TestLinks_ApplyDataset(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string - Input *id.DatasetID + Input *DatasetID Expected, Links *Links }{ { @@ -271,14 +270,14 @@ func TestLinks_ApplyDataset(t *testing.T) { } func TestLink_Dataset(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string Link *Link - Expected *id.DatasetID + Expected *DatasetID }{ { Name: "nil link", @@ -304,14 +303,14 @@ func TestLink_Dataset(t *testing.T) { } func TestLink_DatasetSchema(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string Link *Link - Expected *id.DatasetSchemaID + Expected *DatasetSchemaID }{ { Name: "nil link", @@ -333,14 +332,14 @@ func TestLink_DatasetSchema(t *testing.T) { } func TestLink_DatasetSchemaField(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string Link *Link - Expected *id.DatasetSchemaFieldID + Expected *DatasetFieldID }{ { Name: "nil link", @@ -361,9 +360,9 @@ func TestLink_DatasetSchemaField(t *testing.T) { } func TestLink_Value(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() dsf := []*dataset.Field{ dataset.NewField(dfid1, dataset.ValueTypeString.ValueFrom("aaa"), ""), } @@ -398,9 +397,9 @@ func TestLink_Value(t *testing.T) { } } func TestLink_Validate(t *testing.T) { - dsid1 := id.NewDatasetSchemaID() - did1 := id.NewDatasetID() - dfid1 := id.NewDatasetSchemaFieldID() + dsid1 := NewDatasetSchemaID() + did1 := NewDatasetID() + dfid1 := NewDatasetFieldID() testCases := []struct { Name string @@ -476,6 +475,6 @@ func TestLink_Validate(t *testing.T) { func TestLink_Clone(t *testing.T) { var l *Link assert.Nil(t, l.Clone()) - l = NewLink(id.NewDatasetID(), id.NewDatasetSchemaID(), id.NewDatasetSchemaFieldID()) + l = NewLink(NewDatasetID(), NewDatasetSchemaID(), NewDatasetFieldID()) assert.Equal(t, l, l.Clone()) } diff --git a/pkg/property/list.go b/pkg/property/list.go index 9fe0af64..7441ed75 100644 --- a/pkg/property/list.go +++ b/pkg/property/list.go @@ -1,16 +1,10 @@ package property -import ( - "sort" - - "github.com/reearth/reearth-backend/pkg/id" -) - type List []*Property -func (l List) Schemas() []id.PropertySchemaID { - schemas := make([]id.PropertySchemaID, 0, len(l)) - m := map[id.PropertySchemaID]struct{}{} +func (l List) Schemas() []SchemaID { + schemas := make([]SchemaID, 0, len(l)) + m := map[SchemaID]struct{}{} for _, p := range l { s := p.Schema() if _, ok := m[s]; ok { @@ -27,7 +21,7 @@ func (l List) Map() Map { return m.Add(l...) } -type Map map[id.PropertyID]*Property +type Map map[ID]*Property func MapFrom(properties ...*Property) Map { return Map{}.Add(properties...) @@ -80,14 +74,12 @@ func (m Map) Merge(m2 Map) Map { return m3.Add(m2.List()...) } -func (m Map) Keys() []id.PropertyID { - keys := make([]id.PropertyID, 0, len(m)) +func (m Map) Keys() []ID { + keys := make([]ID, 0, len(m)) for k := range m { keys = append(keys, k) } - sort.SliceStable(keys, func(i, j int) bool { - return id.ID(keys[i]).Compare(id.ID(keys[j])) < 0 - }) + sortIDs(keys) return keys } diff --git a/pkg/property/list_test.go b/pkg/property/list_test.go index 8b27eadb..6ce34a58 100644 --- a/pkg/property/list_test.go +++ b/pkg/property/list_test.go @@ -3,15 +3,14 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) var ( sf = NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg = NewSchemaGroup().ID("aa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - p = New().NewID().Scene(id.NewSceneID()).Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Items([]Item{InitItemFrom(sg)}).MustBuild() - p2 = New().NewID().Scene(id.NewSceneID()).Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Items([]Item{InitItemFrom(sg)}).MustBuild() + sg = NewSchemaGroup().ID("aa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + p = New().NewID().Scene(NewSceneID()).Schema(MustSchemaID("xx~1.0.0/aa")).Items([]Item{InitItemFrom(sg)}).MustBuild() + p2 = New().NewID().Scene(NewSceneID()).Schema(MustSchemaID("xx~1.0.0/aa")).Items([]Item{InitItemFrom(sg)}).MustBuild() ) func TestMap_Add(t *testing.T) { diff --git a/pkg/property/loader.go b/pkg/property/loader.go index f2bf3280..336161f0 100644 --- a/pkg/property/loader.go +++ b/pkg/property/loader.go @@ -2,16 +2,14 @@ package property import ( "context" - - "github.com/reearth/reearth-backend/pkg/id" ) -type Loader func(context.Context, ...id.PropertyID) (List, error) +type Loader func(context.Context, ...ID) (List, error) -type SchemaLoader func(context.Context, ...id.PropertySchemaID) (SchemaList, error) +type SchemaLoader func(context.Context, ...SchemaID) (SchemaList, error) func LoaderFrom(data []*Property) Loader { - return func(ctx context.Context, ids ...id.PropertyID) (List, error) { + return func(ctx context.Context, ids ...ID) (List, error) { res := make([]*Property, 0, len(ids)) for _, i := range ids { found := false @@ -30,8 +28,8 @@ func LoaderFrom(data []*Property) Loader { } } -func LoaderFromMap(data map[id.PropertyID]*Property) Loader { - return func(ctx context.Context, ids ...id.PropertyID) (List, error) { +func LoaderFromMap(data map[ID]*Property) Loader { + return func(ctx context.Context, ids ...ID) (List, error) { res := make([]*Property, 0, len(ids)) for _, i := range ids { if d, ok := data[i]; ok { diff --git a/pkg/property/loader_test.go b/pkg/property/loader_test.go index 8e6630de..13770436 100644 --- a/pkg/property/loader_test.go +++ b/pkg/property/loader_test.go @@ -4,15 +4,14 @@ import ( "context" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestLoaderFrom(t *testing.T) { - scene := id.NewSceneID() - ps := id.MustPropertySchemaID("xxx~1.1.1/aa") - pid1 := id.NewPropertyID() - pid2 := id.NewPropertyID() + scene := NewSceneID() + ps := MustSchemaID("xxx~1.1.1/aa") + pid1 := NewID() + pid2 := NewID() p1 := New().ID(pid1).Scene(scene).Schema(ps).MustBuild() p2 := New().ID(pid2).Scene(scene).Schema(ps).MustBuild() pl := LoaderFrom([]*Property{ @@ -27,15 +26,15 @@ func TestLoaderFrom(t *testing.T) { } func TestLoaderFromMap(t *testing.T) { - scene := id.NewSceneID() - ps := id.MustPropertySchemaID("xxx~1.1.1/aa") - pid1 := id.NewPropertyID() - pid2 := id.NewPropertyID() - pid3 := id.NewPropertyID() + scene := NewSceneID() + ps := MustSchemaID("xxx~1.1.1/aa") + pid1 := NewID() + pid2 := NewID() + pid3 := NewID() p1 := New().ID(pid1).Scene(scene).Schema(ps).MustBuild() p2 := New().ID(pid2).Scene(scene).Schema(ps).MustBuild() p3 := New().ID(pid3).Scene(scene).Schema(ps).MustBuild() - pl := LoaderFromMap(map[id.PropertyID]*Property{ + pl := LoaderFromMap(map[ID]*Property{ pid1: p1, pid2: p2, pid3: p3, diff --git a/pkg/property/merged.go b/pkg/property/merged.go index 6110b476..25401e44 100644 --- a/pkg/property/merged.go +++ b/pkg/property/merged.go @@ -4,31 +4,30 @@ import ( "context" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) // Merged represents a merged property from two properties type Merged struct { - Original *id.PropertyID - Parent *id.PropertyID - Schema id.PropertySchemaID - LinkedDataset *id.DatasetID + Original *ID + Parent *ID + Schema SchemaID + LinkedDataset *DatasetID Groups []*MergedGroup } // MergedGroup represents a group of Merged type MergedGroup struct { - Original *id.PropertyItemID - Parent *id.PropertyItemID - SchemaGroup id.PropertySchemaGroupID - LinkedDataset *id.DatasetID + Original *ItemID + Parent *ItemID + SchemaGroup SchemaGroupID + LinkedDataset *DatasetID Groups []*MergedGroup Fields []*MergedField } // MergedField represents a field of Merged type MergedField struct { - ID id.PropertySchemaFieldID + ID FieldID Type ValueType Value *Value Links *Links @@ -36,11 +35,11 @@ type MergedField struct { } // Datasets returns associated dataset IDs -func (m *Merged) Datasets() []id.DatasetID { +func (m *Merged) Datasets() []DatasetID { if m == nil { return nil } - ids := []id.DatasetID{} + ids := []DatasetID{} for _, g := range m.Groups { ids = append(ids, g.Datasets()...) } @@ -48,11 +47,11 @@ func (m *Merged) Datasets() []id.DatasetID { } // Datasets returns associated dataset IDs -func (m *MergedGroup) Datasets() []id.DatasetID { +func (m *MergedGroup) Datasets() []DatasetID { if m == nil { return nil } - ids := []id.DatasetID{} + ids := []DatasetID{} for _, f := range m.Fields { if f == nil { continue @@ -62,15 +61,14 @@ func (m *MergedGroup) Datasets() []id.DatasetID { return ids } -// MergedMetadata _ type MergedMetadata struct { - Original *id.PropertyID - Parent *id.PropertyID - LinkedDataset *id.DatasetID + Original *ID + Parent *ID + LinkedDataset *DatasetID } // MergedMetadataFrom generates MergedMetadata from single property -func MergedMetadataFrom(p id.PropertyID) MergedMetadata { +func MergedMetadataFrom(p ID) MergedMetadata { p2 := p return MergedMetadata{ Original: &p2, @@ -78,8 +76,8 @@ func MergedMetadataFrom(p id.PropertyID) MergedMetadata { } // Properties returns associated property IDs -func (m MergedMetadata) Properties() []id.PropertyID { - ids := make([]id.PropertyID, 0, 2) +func (m MergedMetadata) Properties() []ID { + ids := make([]ID, 0, 2) if m.Original != nil { ids = append(ids, *m.Original) } @@ -108,12 +106,12 @@ func (f *MergedField) DatasetValue(ctx context.Context, d dataset.GraphLoader) ( } // Merge merges two properties -func Merge(o *Property, p *Property, linked *id.DatasetID) *Merged { +func Merge(o *Property, p *Property, linked *DatasetID) *Merged { if o == nil && p == nil || o != nil && p != nil && !o.Schema().Equal(p.Schema()) { return nil } - var schema id.PropertySchemaID + var schema SchemaID if p != nil { schema = p.Schema() } else if o != nil { @@ -129,12 +127,12 @@ func Merge(o *Property, p *Property, linked *id.DatasetID) *Merged { } } -func mergeItems(i1, i2 []Item, linked *id.DatasetID) []*MergedGroup { +func mergeItems(i1, i2 []Item, linked *DatasetID) []*MergedGroup { if i1 == nil && i2 == nil || len(i1) == 0 && len(i2) == 0 { return nil } - consumed := map[id.PropertyItemID]struct{}{} + consumed := map[ItemID]struct{}{} groups := []*MergedGroup{} for _, item := range i1 { @@ -174,7 +172,7 @@ func group(o, p Item) (*Group, *Group) { return ToGroup(o), ToGroup(p) } -func mergeItem(o, p Item, linked *id.DatasetID) *MergedGroup { +func mergeItem(o, p Item, linked *DatasetID) *MergedGroup { if o == nil && p == nil || o != nil && p != nil && o.SchemaGroup() != p.SchemaGroup() { return nil } @@ -215,8 +213,8 @@ func mergeItem(o, p Item, linked *id.DatasetID) *MergedGroup { } } - var oid, pid *id.PropertyItemID - var sg id.PropertySchemaGroupID + var oid, pid *ItemID + var sg SchemaGroupID if o != nil { oid = o.IDRef() sg = o.SchemaGroup() @@ -236,7 +234,7 @@ func mergeItem(o, p Item, linked *id.DatasetID) *MergedGroup { } } -func mergeField(original, parent *Field, linked *id.DatasetID) *MergedField { +func mergeField(original, parent *Field, linked *DatasetID) *MergedField { if original == nil && parent == nil || original != nil && parent != nil && (original.Field() != parent.Field() || original.Type() != parent.Type()) { return nil } @@ -248,7 +246,7 @@ func mergeField(original, parent *Field, linked *id.DatasetID) *MergedField { t = parent.Type() } - var fid id.PropertySchemaFieldID + var fid FieldID if original != nil { fid = original.Field() } else if parent != nil { @@ -286,9 +284,9 @@ func mergeField(original, parent *Field, linked *id.DatasetID) *MergedField { } } -func allFields(args ...[]id.PropertySchemaFieldID) []id.PropertySchemaFieldID { - consumedKeys := map[id.PropertySchemaFieldID]struct{}{} - result := []id.PropertySchemaFieldID{} +func allFields(args ...[]FieldID) []FieldID { + consumedKeys := map[FieldID]struct{}{} + result := []FieldID{} for _, fields := range args { for _, f := range fields { if _, ok := consumedKeys[f]; ok { diff --git a/pkg/property/merged_test.go b/pkg/property/merged_test.go index e21e9606..dbc18a9e 100644 --- a/pkg/property/merged_test.go +++ b/pkg/property/merged_test.go @@ -3,45 +3,43 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" - "github.com/stretchr/testify/assert" ) func TestMerge(t *testing.T) { - ds := id.NewDatasetSchemaID() - df := id.NewDatasetSchemaFieldID() - d := id.NewDatasetID() - d2 := id.NewDatasetID() - opid := id.NewPropertyID() - ppid := id.NewPropertyID() - psid := id.MustPropertySchemaID("hoge~0.1.0/fff") - psid2 := id.MustPropertySchemaID("hoge~0.1.0/aaa") - psgid1 := id.PropertySchemaGroupID("group1") - psgid2 := id.PropertySchemaGroupID("group2") - psgid3 := id.PropertySchemaGroupID("group3") - psgid4 := id.PropertySchemaGroupID("group4") - i1id := id.NewPropertyItemID() - i2id := id.NewPropertyItemID() - i3id := id.NewPropertyItemID() - i4id := id.NewPropertyItemID() - i5id := id.NewPropertyItemID() - i6id := id.NewPropertyItemID() - i7id := id.NewPropertyItemID() - i8id := id.NewPropertyItemID() + ds := NewDatasetSchemaID() + df := NewDatasetFieldID() + d := NewDatasetID() + d2 := NewDatasetID() + opid := NewID() + ppid := NewID() + psid := MustSchemaID("hoge~0.1.0/fff") + psid2 := MustSchemaID("hoge~0.1.0/aaa") + psgid1 := SchemaGroupID("group1") + psgid2 := SchemaGroupID("group2") + psgid3 := SchemaGroupID("group3") + psgid4 := SchemaGroupID("group4") + i1id := NewItemID() + i2id := NewItemID() + i3id := NewItemID() + i4id := NewItemID() + i5id := NewItemID() + i6id := NewItemID() + i7id := NewItemID() + i8id := NewItemID() fields1 := []*Field{ - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("a")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("a"))).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("b")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("b"))).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("e")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).LinksUnsafe(NewLinks([]*Link{NewLink(d2, ds, df)})).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("f")).ValueUnsafe(NewOptionalValue(ValueTypeNumber, nil)).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("a")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("a"))).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("b")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("b"))).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("e")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).LinksUnsafe(NewLinks([]*Link{NewLink(d2, ds, df)})).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("f")).ValueUnsafe(NewOptionalValue(ValueTypeNumber, nil)).Build(), } fields2 := []*Field{ - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("a")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("1"))).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("c")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("2"))).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("d")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).LinksUnsafe(NewLinks([]*Link{NewLinkFieldOnly(ds, df)})).Build(), - NewFieldUnsafe().FieldUnsafe(id.PropertySchemaFieldID("f")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("a")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("1"))).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("c")).ValueUnsafe(OptionalValueFrom(ValueTypeString.ValueFrom("2"))).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("d")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).LinksUnsafe(NewLinks([]*Link{NewLinkFieldOnly(ds, df)})).Build(), + NewFieldUnsafe().FieldUnsafe(FieldID("f")).ValueUnsafe(NewOptionalValue(ValueTypeString, nil)).Build(), } groups1 := []*Group{ @@ -64,7 +62,7 @@ func TestMerge(t *testing.T) { NewGroup().ID(i6id).Schema(psid, psgid4).Fields(fields2).MustBuild(), } - sid := id.NewSceneID() + sid := NewSceneID() op := New().ID(opid).Scene(sid).Schema(psid).Items(items1).MustBuild() pp := New().NewID().Scene(sid).Schema(psid2).MustBuild() pp2 := New().ID(ppid).Scene(sid).Schema(psid).Items(items2).MustBuild() @@ -89,22 +87,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeNumber, }, }, @@ -118,28 +116,28 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, Overridden: true, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("c"), + ID: FieldID("c"), Value: ValueTypeString.ValueFrom("2"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("d"), + ID: FieldID("d"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, }, @@ -152,22 +150,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeNumber, }, }, @@ -179,22 +177,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("1"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("c"), + ID: FieldID("c"), Value: ValueTypeString.ValueFrom("2"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("d"), + ID: FieldID("d"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeString, }, }, @@ -222,22 +220,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeNumber, }, }, @@ -251,22 +249,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeNumber, }, }, @@ -278,22 +276,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("e"), + ID: FieldID("e"), Links: NewLinks([]*Link{NewLink(d2, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeNumber, }, }, @@ -321,22 +319,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("1"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("c"), + ID: FieldID("c"), Value: ValueTypeString.ValueFrom("2"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("d"), + ID: FieldID("d"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeString, }, }, @@ -350,22 +348,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("1"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("c"), + ID: FieldID("c"), Value: ValueTypeString.ValueFrom("2"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("d"), + ID: FieldID("d"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeString, }, }, @@ -377,22 +375,22 @@ func TestMerge(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("1"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("c"), + ID: FieldID("c"), Value: ValueTypeString.ValueFrom("2"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("d"), + ID: FieldID("d"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("f"), + ID: FieldID("f"), Type: ValueTypeString, }, }, diff --git a/pkg/property/pointer.go b/pkg/property/pointer.go index 658f0a82..8164adb9 100644 --- a/pkg/property/pointer.go +++ b/pkg/property/pointer.go @@ -1,16 +1,14 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - // Pointer is a pointer to a field and an item in properties and schemas type Pointer struct { - schemaItem *id.PropertySchemaGroupID - item *id.PropertyItemID - field *id.PropertySchemaFieldID + schemaItem *SchemaGroupID + item *ItemID + field *FieldID } // NewPointer creates a new Pointer. -func NewPointer(sg *id.PropertySchemaGroupID, i *id.PropertyItemID, f *id.PropertySchemaFieldID) *Pointer { +func NewPointer(sg *SchemaGroupID, i *ItemID, f *FieldID) *Pointer { if sg == nil && i == nil && f == nil { return nil } @@ -22,7 +20,7 @@ func NewPointer(sg *id.PropertySchemaGroupID, i *id.PropertyItemID, f *id.Proper } // PointField creates a new Pointer pointing the field in properties. -func PointField(sg *id.PropertySchemaGroupID, i *id.PropertyItemID, f id.PropertySchemaFieldID) *Pointer { +func PointField(sg *SchemaGroupID, i *ItemID, f FieldID) *Pointer { return &Pointer{ schemaItem: sg.CopyRef(), item: i.CopyRef(), @@ -31,28 +29,28 @@ func PointField(sg *id.PropertySchemaGroupID, i *id.PropertyItemID, f id.Propert } // PointField creates a new Pointer pointing the field in property schemas. -func PointFieldOnly(fid id.PropertySchemaFieldID) *Pointer { +func PointFieldOnly(fid FieldID) *Pointer { return &Pointer{ field: &fid, } } // PointItemBySchema creates a new Pointer pointing the schema item in property schemas. -func PointItemBySchema(sg id.PropertySchemaGroupID) *Pointer { +func PointItemBySchema(sg SchemaGroupID) *Pointer { return &Pointer{ schemaItem: &sg, } } // PointItem creates a new Pointer pointing to the item in properties. -func PointItem(i id.PropertyItemID) *Pointer { +func PointItem(i ItemID) *Pointer { return &Pointer{ item: &i, } } // PointFieldBySchemaGroup creates a new Pointer pointing to the field of the schema field in properties. -func PointFieldBySchemaGroup(sg id.PropertySchemaGroupID, f id.PropertySchemaFieldID) *Pointer { +func PointFieldBySchemaGroup(sg SchemaGroupID, f FieldID) *Pointer { return &Pointer{ schemaItem: &sg, field: &f, @@ -60,7 +58,7 @@ func PointFieldBySchemaGroup(sg id.PropertySchemaGroupID, f id.PropertySchemaFie } // PointFieldByItem creates a new Pointer pointing to the field of the item in properties. -func PointFieldByItem(i id.PropertyItemID, f id.PropertySchemaFieldID) *Pointer { +func PointFieldByItem(i ItemID, f FieldID) *Pointer { return &Pointer{ item: &i, field: &f, @@ -78,7 +76,7 @@ func (p *Pointer) Clone() *Pointer { } } -func (p *Pointer) ItemBySchemaGroupAndItem() (i id.PropertySchemaGroupID, i2 id.PropertyItemID, ok bool) { +func (p *Pointer) ItemBySchemaGroupAndItem() (i SchemaGroupID, i2 ItemID, ok bool) { if p == nil || p.schemaItem == nil || p.item == nil { ok = false return @@ -89,7 +87,7 @@ func (p *Pointer) ItemBySchemaGroupAndItem() (i id.PropertySchemaGroupID, i2 id. return } -func (p *Pointer) ItemBySchemaGroup() (i id.PropertySchemaGroupID, ok bool) { +func (p *Pointer) ItemBySchemaGroup() (i SchemaGroupID, ok bool) { if p == nil || p.schemaItem == nil { ok = false return @@ -99,7 +97,7 @@ func (p *Pointer) ItemBySchemaGroup() (i id.PropertySchemaGroupID, ok bool) { return } -func (p *Pointer) SchemaGroupAndItem() (i id.PropertySchemaGroupID, i2 id.PropertyItemID, ok bool) { +func (p *Pointer) SchemaGroupAndItem() (i SchemaGroupID, i2 ItemID, ok bool) { ok = false if p == nil { return @@ -115,7 +113,7 @@ func (p *Pointer) SchemaGroupAndItem() (i id.PropertySchemaGroupID, i2 id.Proper return } -func (p *Pointer) Item() (i id.PropertyItemID, ok bool) { +func (p *Pointer) Item() (i ItemID, ok bool) { if p == nil || p.item == nil { ok = false return @@ -125,7 +123,7 @@ func (p *Pointer) Item() (i id.PropertyItemID, ok bool) { return } -func (p *Pointer) ItemRef() *id.PropertyItemID { +func (p *Pointer) ItemRef() *ItemID { if p == nil || p.item == nil { return nil } @@ -133,7 +131,7 @@ func (p *Pointer) ItemRef() *id.PropertyItemID { return &f } -func (p *Pointer) FieldByItem() (i id.PropertyItemID, f id.PropertySchemaFieldID, ok bool) { +func (p *Pointer) FieldByItem() (i ItemID, f FieldID, ok bool) { if p == nil || p.item == nil || p.schemaItem != nil || p.field == nil { ok = false return @@ -144,7 +142,7 @@ func (p *Pointer) FieldByItem() (i id.PropertyItemID, f id.PropertySchemaFieldID return } -func (p *Pointer) FieldBySchemaGroup() (sg id.PropertySchemaGroupID, f id.PropertySchemaFieldID, ok bool) { +func (p *Pointer) FieldBySchemaGroup() (sg SchemaGroupID, f FieldID, ok bool) { if p == nil || p.schemaItem == nil || p.item != nil || p.field == nil { ok = false return @@ -155,7 +153,7 @@ func (p *Pointer) FieldBySchemaGroup() (sg id.PropertySchemaGroupID, f id.Proper return } -func (p *Pointer) Field() (f id.PropertySchemaFieldID, ok bool) { +func (p *Pointer) Field() (f FieldID, ok bool) { if p == nil || p.field == nil { ok = false return @@ -165,7 +163,7 @@ func (p *Pointer) Field() (f id.PropertySchemaFieldID, ok bool) { return } -func (p *Pointer) FieldRef() *id.PropertySchemaFieldID { +func (p *Pointer) FieldRef() *FieldID { if p == nil || p.field == nil { return nil } @@ -173,7 +171,7 @@ func (p *Pointer) FieldRef() *id.PropertySchemaFieldID { return &f } -func (p *Pointer) GetAll() (sg *id.PropertySchemaGroupID, i *id.PropertyItemID, f *id.PropertySchemaFieldID) { +func (p *Pointer) GetAll() (sg *SchemaGroupID, i *ItemID, f *FieldID) { if p == nil { return } diff --git a/pkg/property/pointer_test.go b/pkg/property/pointer_test.go index c1225a4e..f0639c7c 100644 --- a/pkg/property/pointer_test.go +++ b/pkg/property/pointer_test.go @@ -3,14 +3,13 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestPointer(t *testing.T) { - iid := id.NewPropertyItemID() - sgid := id.PropertySchemaGroupID("foo") - fid := id.PropertySchemaFieldID("hoge") + iid := NewItemID() + sgid := SchemaGroupID("foo") + fid := FieldID("hoge") var p *Pointer var ok bool diff --git a/pkg/property/property.go b/pkg/property/property.go index 1fbbb2eb..ee6db07a 100644 --- a/pkg/property/property.go +++ b/pkg/property/property.go @@ -6,32 +6,31 @@ import ( "fmt" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) type Property struct { - id id.PropertyID - scene id.SceneID - schema id.PropertySchemaID + id ID + scene SceneID + schema SchemaID items []Item } -func (p *Property) ID() id.PropertyID { +func (p *Property) ID() ID { return p.id } -func (p *Property) IDRef() *id.PropertyID { +func (p *Property) IDRef() *ID { if p == nil { return nil } return p.id.Ref() } -func (p *Property) Scene() id.SceneID { +func (p *Property) Scene() SceneID { return p.scene } -func (p *Property) Schema() id.PropertySchemaID { +func (p *Property) Schema() SchemaID { return p.schema } @@ -62,7 +61,7 @@ func (p *Property) Items() []Item { return append([]Item{}, p.items...) } -func (p *Property) Item(id id.PropertyItemID) (Item, *GroupList) { +func (p *Property) Item(id ItemID) (Item, *GroupList) { if p == nil { return nil, nil } @@ -80,7 +79,7 @@ func (p *Property) Item(id id.PropertyItemID) (Item, *GroupList) { } // ItemBySchema returns a root item by a schema group ID. -func (p *Property) ItemBySchema(id id.PropertySchemaGroupID) Item { +func (p *Property) ItemBySchema(id SchemaGroupID) Item { if p == nil { return nil } @@ -92,7 +91,7 @@ func (p *Property) ItemBySchema(id id.PropertySchemaGroupID) Item { return nil } -func (p *Property) GroupBySchema(id id.PropertySchemaGroupID) *Group { +func (p *Property) GroupBySchema(id SchemaGroupID) *Group { i := p.ItemBySchema(id) if i == nil { return nil @@ -103,7 +102,7 @@ func (p *Property) GroupBySchema(id id.PropertySchemaGroupID) *Group { return nil } -func (p *Property) GroupListBySchema(id id.PropertySchemaGroupID) *GroupList { +func (p *Property) GroupListBySchema(id SchemaGroupID) *GroupList { i := p.ItemBySchema(id) if i == nil { return nil @@ -161,7 +160,7 @@ func (p *Property) HasLinkedField() bool { return false } -func (p *Property) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) []*Field { +func (p *Property) FieldsByLinkedDataset(s DatasetSchemaID, i DatasetID) []*Field { if p == nil { return nil } @@ -172,7 +171,7 @@ func (p *Property) FieldsByLinkedDataset(s id.DatasetSchemaID, i id.DatasetID) [ return res } -func (p *Property) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { +func (p *Property) IsDatasetLinked(s DatasetSchemaID, i DatasetID) bool { if p == nil { return false } @@ -184,11 +183,11 @@ func (p *Property) IsDatasetLinked(s id.DatasetSchemaID, i id.DatasetID) bool { return false } -func (p *Property) CollectDatasets() []id.DatasetID { +func (p *Property) CollectDatasets() []DatasetID { if p == nil { return nil } - res := []id.DatasetID{} + res := []DatasetID{} for _, f := range p.items { res = append(res, f.CollectDatasets()...) @@ -261,7 +260,7 @@ func (p *Property) UpdateValue(ps *Schema, ptr *Pointer, v *Value) (*Field, *Gro return field, gl, g, nil } -func (p *Property) UnlinkAllByDataset(s id.DatasetSchemaID, ds id.DatasetID) { +func (p *Property) UnlinkAllByDataset(s DatasetSchemaID, ds DatasetID) { fields := p.FieldsByLinkedDataset(s, ds) for _, f := range fields { f.Unlink() @@ -419,7 +418,7 @@ func (p *Property) UpdateLinkableValue(s *Schema, v *Value) { } } -func (p *Property) AutoLinkField(s *Schema, v ValueType, d id.DatasetSchemaID, df *id.DatasetSchemaFieldID, ds *id.DatasetID) { +func (p *Property) AutoLinkField(s *Schema, v ValueType, d DatasetSchemaID, df *DatasetFieldID, ds *DatasetID) { if s == nil || p == nil || df == nil { return } diff --git a/pkg/property/property_test.go b/pkg/property/property_test.go index 153a1cdc..5f38c5bb 100644 --- a/pkg/property/property_test.go +++ b/pkg/property/property_test.go @@ -6,26 +6,25 @@ import ( "github.com/reearth/reearth-backend/pkg/dataset" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestPropertyMigrateSchema(t *testing.T) { - sceneID := id.NewSceneID() - oldSchema, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - newSchema, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test2") - schemaField1ID := id.PropertySchemaFieldID("a") - schemaField2ID := id.PropertySchemaFieldID("b") - schemaField3ID := id.PropertySchemaFieldID("c") - schemaField4ID := id.PropertySchemaFieldID("d") - schemaField5ID := id.PropertySchemaFieldID("e") - schemaField6ID := id.PropertySchemaFieldID("f") - schemaField7ID := id.PropertySchemaFieldID("g") - schemaField8ID := id.PropertySchemaFieldID("h") - schemaGroupID := id.PropertySchemaGroupID("i") - datasetID := id.NewDatasetID() - datasetSchemaID := id.NewDatasetSchemaID() - datasetFieldID := id.NewDatasetSchemaFieldID() + sceneID := NewSceneID() + oldSchema, _ := SchemaIDFrom("hoge~1.0.0/test") + newSchema, _ := SchemaIDFrom("hoge~1.0.0/test2") + schemaField1ID := FieldID("a") + schemaField2ID := FieldID("b") + schemaField3ID := FieldID("c") + schemaField4ID := FieldID("d") + schemaField5ID := FieldID("e") + schemaField6ID := FieldID("f") + schemaField7ID := FieldID("g") + schemaField8ID := FieldID("h") + schemaGroupID := SchemaGroupID("i") + datasetID := NewDatasetID() + datasetSchemaID := NewDatasetSchemaID() + datasetFieldID := NewDatasetFieldID() schemaField1, _ := NewSchemaField().ID(schemaField1ID).Type(ValueTypeString).Build() schemaField2, _ := NewSchemaField().ID(schemaField2ID).Type(ValueTypeNumber).Min(0).Max(100).Build() @@ -115,12 +114,12 @@ func TestPropertyMigrateSchema(t *testing.T) { } func TestGetOrCreateItem(t *testing.T) { - sceneID := id.NewSceneID() - sid, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - sf1id := id.PropertySchemaFieldID("a") - sf2id := id.PropertySchemaFieldID("b") - sg1id := id.PropertySchemaGroupID("c") - sg2id := id.PropertySchemaGroupID("d") + sceneID := NewSceneID() + sid, _ := SchemaIDFrom("hoge~1.0.0/test") + sf1id := FieldID("a") + sf2id := FieldID("b") + sg1id := SchemaGroupID("c") + sg2id := SchemaGroupID("d") sf1 := NewSchemaField().ID(sf1id).Type(ValueTypeString).MustBuild() sg1 := NewSchemaGroup().ID(sg1id).Schema(sid).Fields([]*SchemaField{sf1}).MustBuild() @@ -165,12 +164,12 @@ func TestGetOrCreateItem(t *testing.T) { } func TestGetOrCreateField(t *testing.T) { - sceneID := id.NewSceneID() - sid, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - sf1id := id.PropertySchemaFieldID("a") - sf2id := id.PropertySchemaFieldID("b") - sg1id := id.PropertySchemaGroupID("c") - sg2id := id.PropertySchemaGroupID("d") + sceneID := NewSceneID() + sid, _ := SchemaIDFrom("hoge~1.0.0/test") + sf1id := FieldID("a") + sf2id := FieldID("b") + sg1id := SchemaGroupID("c") + sg2id := SchemaGroupID("d") sf1 := NewSchemaField().ID(sf1id).Type(ValueTypeString).MustBuild() sg1 := NewSchemaGroup().ID(sg1id).Schema(sid).Fields([]*SchemaField{sf1}).MustBuild() @@ -217,10 +216,10 @@ func TestGetOrCreateField(t *testing.T) { } func TestAddListItem(t *testing.T) { - sceneID := id.NewSceneID() - sid, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - sfid := id.PropertySchemaFieldID("a") - sgid := id.PropertySchemaGroupID("b") + sceneID := NewSceneID() + sid, _ := SchemaIDFrom("hoge~1.0.0/test") + sfid := FieldID("a") + sgid := SchemaGroupID("b") sf := NewSchemaField().ID(sfid).Type(ValueTypeString).MustBuild() sg := NewSchemaGroup().ID(sgid).Schema(sid).Fields([]*SchemaField{sf}).IsList(true).MustBuild() ps := NewSchema().ID(sid).Groups([]*SchemaGroup{sg}).MustBuild() @@ -239,9 +238,9 @@ func TestAddListItem(t *testing.T) { } func TestMoveListItem(t *testing.T) { - sceneID := id.NewSceneID() - sid, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - sgid := id.PropertySchemaGroupID("b") + sceneID := NewSceneID() + sid, _ := SchemaIDFrom("hoge~1.0.0/test") + sgid := SchemaGroupID("b") g1 := NewGroup().NewID().Schema(sid, sgid).MustBuild() g2 := NewGroup().NewID().Schema(sid, sgid).MustBuild() gl := NewGroupList().NewID().Schema(sid, sgid).Groups([]*Group{g1, g2}).MustBuild() @@ -254,9 +253,9 @@ func TestMoveListItem(t *testing.T) { } func TestRemoveListItem(t *testing.T) { - sceneID := id.NewSceneID() - sid, _ := id.PropertySchemaIDFrom("hoge~1.0.0/test") - sgid := id.PropertySchemaGroupID("b") + sceneID := NewSceneID() + sid, _ := SchemaIDFrom("hoge~1.0.0/test") + sgid := SchemaGroupID("b") g1 := NewGroup().NewID().Schema(sid, sgid).MustBuild() g2 := NewGroup().NewID().Schema(sid, sgid).MustBuild() gl := NewGroupList().NewID().Schema(sid, sgid).Groups([]*Group{g1, g2}).MustBuild() diff --git a/pkg/property/schema.go b/pkg/property/schema.go index b14eaa04..f6cd4f2b 100644 --- a/pkg/property/schema.go +++ b/pkg/property/schema.go @@ -1,10 +1,7 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - -// Schema _ type Schema struct { - id id.PropertySchemaID + id SchemaID version int groups []*SchemaGroup linkable LinkableFields @@ -15,11 +12,11 @@ type LinkableFields struct { URL *Pointer } -func (p *Schema) ID() id.PropertySchemaID { +func (p *Schema) ID() SchemaID { return p.id } -func (p *Schema) IDRef() *id.PropertySchemaID { +func (p *Schema) IDRef() *SchemaID { if p == nil { return nil } @@ -41,7 +38,7 @@ func (p *Schema) Fields() []*SchemaField { return fields } -func (p *Schema) Field(id id.PropertySchemaFieldID) *SchemaField { +func (p *Schema) Field(id FieldID) *SchemaField { if p == nil { return nil } @@ -71,7 +68,7 @@ func (p *Schema) Groups() []*SchemaGroup { return append([]*SchemaGroup{}, p.groups...) } -func (p *Schema) Group(id id.PropertySchemaGroupID) *SchemaGroup { +func (p *Schema) Group(id SchemaGroupID) *SchemaGroup { if p == nil { return nil } @@ -83,7 +80,7 @@ func (p *Schema) Group(id id.PropertySchemaGroupID) *SchemaGroup { return nil } -func (p *Schema) GroupByField(id id.PropertySchemaFieldID) *SchemaGroup { +func (p *Schema) GroupByField(id FieldID) *SchemaGroup { if p == nil { return nil } @@ -114,9 +111,9 @@ func (p *Schema) GroupByPointer(ptr *Pointer) *SchemaGroup { return nil } -func (s *Schema) DetectDuplicatedFields() []id.PropertySchemaFieldID { - duplicated := []id.PropertySchemaFieldID{} - ids := map[id.PropertySchemaFieldID]struct{}{} +func (s *Schema) DetectDuplicatedFields() []FieldID { + duplicated := []FieldID{} + ids := map[FieldID]struct{}{} for _, f := range s.Fields() { i := f.ID() if _, ok := ids[i]; ok { diff --git a/pkg/property/schema_builder.go b/pkg/property/schema_builder.go index d62a30fb..82c01de7 100644 --- a/pkg/property/schema_builder.go +++ b/pkg/property/schema_builder.go @@ -3,8 +3,6 @@ package property import ( "errors" "fmt" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( @@ -26,7 +24,7 @@ func NewSchema() *SchemaBuilder { func (b *SchemaBuilder) Build() (*Schema, error) { if b.p.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if d := b.p.DetectDuplicatedFields(); len(d) > 0 { return nil, fmt.Errorf("%s: %s %s", ErrDuplicatedField, b.p.id, d) @@ -45,7 +43,7 @@ func (b *SchemaBuilder) MustBuild() *Schema { return p } -func (b *SchemaBuilder) ID(id id.PropertySchemaID) *SchemaBuilder { +func (b *SchemaBuilder) ID(id SchemaID) *SchemaBuilder { b.p.id = id return b } @@ -57,7 +55,7 @@ func (b *SchemaBuilder) Version(version int) *SchemaBuilder { func (b *SchemaBuilder) Groups(groups []*SchemaGroup) *SchemaBuilder { newGroups := []*SchemaGroup{} - ids := map[id.PropertySchemaGroupID]struct{}{} + ids := map[SchemaGroupID]struct{}{} for _, f := range groups { if f == nil { continue diff --git a/pkg/property/schema_builder_test.go b/pkg/property/schema_builder_test.go index 9d7dfbbe..0e317b70 100644 --- a/pkg/property/schema_builder_test.go +++ b/pkg/property/schema_builder_test.go @@ -5,22 +5,21 @@ import ( "fmt" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestSchemaBuilder_Build(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg := NewSchemaGroup().ID("aaa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - sg2 := NewSchemaGroup().ID("daa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg := NewSchemaGroup().ID("aaa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg2 := NewSchemaGroup().ID("daa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() testCases := []struct { Name string - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields Expected struct { - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields @@ -29,31 +28,31 @@ func TestSchemaBuilder_Build(t *testing.T) { }{ { Name: "fail: invalid id", - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "fail: invalid linkable field", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), - Linkable: LinkableFields{LatLng: NewPointer(nil, nil, id.PropertySchemaFieldID("xx").Ref())}, + Id: MustSchemaID("xx~1.0.0/aa"), + Linkable: LinkableFields{LatLng: NewPointer(nil, nil, FieldID("xx").Ref())}, Err: ErrInvalidPropertyLinkableField, }, { Name: "fail: duplicated field", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), + Id: MustSchemaID("xx~1.0.0/aa"), Groups: []*SchemaGroup{sg, sg2}, - Err: fmt.Errorf("%s: %s %s", ErrDuplicatedField, id.MustPropertySchemaID("xx~1.0.0/aa"), []id.PropertySchemaFieldID{"aa"}), + Err: fmt.Errorf("%s: %s %s", ErrDuplicatedField, MustSchemaID("xx~1.0.0/aa"), []FieldID{"aa"}), }, { Name: "success", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), + Id: MustSchemaID("xx~1.0.0/aa"), Groups: []*SchemaGroup{sg}, Version: 1, Expected: struct { - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields - }{Id: id.MustPropertySchemaID("xx~1.0.0/aa"), Version: 1, Groups: []*SchemaGroup{sg}}, + }{Id: MustSchemaID("xx~1.0.0/aa"), Version: 1, Groups: []*SchemaGroup{sg}}, }, } @@ -81,17 +80,17 @@ func TestSchemaBuilder_Build(t *testing.T) { func TestSchemaBuilder_MustBuild(t *testing.T) { sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() - sg := NewSchemaGroup().ID("aaa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() - sg2 := NewSchemaGroup().ID("daa").Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg := NewSchemaGroup().ID("aaa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg2 := NewSchemaGroup().ID("daa").Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() testCases := []struct { Name string Fails bool - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields Expected struct { - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields @@ -103,27 +102,27 @@ func TestSchemaBuilder_MustBuild(t *testing.T) { }, { Name: "fail: invalid linkable field", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), - Linkable: LinkableFields{LatLng: NewPointer(nil, nil, id.PropertySchemaFieldID("xx").Ref())}, + Id: MustSchemaID("xx~1.0.0/aa"), + Linkable: LinkableFields{LatLng: NewPointer(nil, nil, FieldID("xx").Ref())}, Fails: true, }, { Name: "fail: duplicated field", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), + Id: MustSchemaID("xx~1.0.0/aa"), Groups: []*SchemaGroup{sg, sg2}, Fails: true, }, { Name: "success", - Id: id.MustPropertySchemaID("xx~1.0.0/aa"), + Id: MustSchemaID("xx~1.0.0/aa"), Groups: []*SchemaGroup{sg}, Version: 1, Expected: struct { - Id id.PropertySchemaID + Id SchemaID Version int Groups []*SchemaGroup Linkable LinkableFields - }{Id: id.MustPropertySchemaID("xx~1.0.0/aa"), Version: 1, Groups: []*SchemaGroup{sg}}, + }{Id: MustSchemaID("xx~1.0.0/aa"), Version: 1, Groups: []*SchemaGroup{sg}}, }, } diff --git a/pkg/property/schema_field.go b/pkg/property/schema_field.go index 402be2b0..825233f3 100644 --- a/pkg/property/schema_field.go +++ b/pkg/property/schema_field.go @@ -2,11 +2,10 @@ package property import ( "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) type SchemaField struct { - id id.PropertySchemaFieldID + id FieldID propertyType ValueType title i18n.String description i18n.String @@ -26,7 +25,7 @@ type SchemaFieldChoice struct { Icon string } -func (p *SchemaField) ID() id.PropertySchemaFieldID { +func (p *SchemaField) ID() FieldID { return p.id } diff --git a/pkg/property/schema_field_builder.go b/pkg/property/schema_field_builder.go index 268b1508..cb1497c6 100644 --- a/pkg/property/schema_field_builder.go +++ b/pkg/property/schema_field_builder.go @@ -4,7 +4,6 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) type SchemaFieldBuilder struct { @@ -17,7 +16,7 @@ func NewSchemaField() *SchemaFieldBuilder { func (b *SchemaFieldBuilder) Build() (*SchemaField, error) { if b.p.id.String() == "" || b.p.id.String() == "id" { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.p.ui != SchemaFieldUI("") && SchemaFieldUIFrom(string(b.p.ui)) == SchemaFieldUI("") { return nil, errors.New("invalid property schema field ui") @@ -39,7 +38,7 @@ func (b *SchemaFieldBuilder) MustBuild() *SchemaField { return p } -func (b *SchemaFieldBuilder) ID(id id.PropertySchemaFieldID) *SchemaFieldBuilder { +func (b *SchemaFieldBuilder) ID(id FieldID) *SchemaFieldBuilder { b.p.id = id return b } diff --git a/pkg/property/schema_field_builder_test.go b/pkg/property/schema_field_builder_test.go index ef150746..164a29f3 100644 --- a/pkg/property/schema_field_builder_test.go +++ b/pkg/property/schema_field_builder_test.go @@ -5,14 +5,13 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestSchemaFieldBuilder_Build(t *testing.T) { testCases := []struct { Name string - Id id.PropertySchemaFieldID + Id FieldID PropertyType ValueType Fname i18n.String Description i18n.String @@ -27,7 +26,7 @@ func TestSchemaFieldBuilder_Build(t *testing.T) { Choices []SchemaFieldChoice Cond *Condition Expected struct { - Id id.PropertySchemaFieldID + Id FieldID PropertyType ValueType Fname i18n.String Description i18n.String @@ -44,11 +43,11 @@ func TestSchemaFieldBuilder_Build(t *testing.T) { }{ { Name: "nil field", - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "fail min > max", - Id: id.PropertySchemaFieldID("aa"), + Id: FieldID("aa"), Min: 10, Max: 1, Err: errors.New("invalid min and max"), diff --git a/pkg/property/schema_field_ui.go b/pkg/property/schema_field_ui.go index c03f282a..3b8b40f0 100644 --- a/pkg/property/schema_field_ui.go +++ b/pkg/property/schema_field_ui.go @@ -52,7 +52,6 @@ func (p SchemaFieldUI) String() string { return string(p) } -// StringRef _ func (p *SchemaFieldUI) StringRef() *string { if p == nil { return nil diff --git a/pkg/property/schema_group.go b/pkg/property/schema_group.go index 73c0955f..c1515ecb 100644 --- a/pkg/property/schema_group.go +++ b/pkg/property/schema_group.go @@ -2,43 +2,42 @@ package property import ( "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) // SchemaGroup represents a group of property that has some fields type SchemaGroup struct { - id id.PropertySchemaGroupID - sid id.PropertySchemaID + id SchemaGroupID + sid SchemaID fields []*SchemaField list bool isAvailableIf *Condition title i18n.String - representativeField *id.PropertySchemaFieldID + representativeField *FieldID } // ID returns id -func (s *SchemaGroup) ID() id.PropertySchemaGroupID { +func (s *SchemaGroup) ID() SchemaGroupID { if s == nil { - return id.PropertySchemaGroupID("") + return SchemaGroupID("") } return s.id } -func (s *SchemaGroup) IDRef() *id.PropertySchemaGroupID { +func (s *SchemaGroup) IDRef() *SchemaGroupID { if s == nil { return nil } return s.id.Ref() } -func (s *SchemaGroup) Schema() id.PropertySchemaID { +func (s *SchemaGroup) Schema() SchemaID { if s == nil { - return id.PropertySchemaID{} + return SchemaID{} } return s.sid } -func (s *SchemaGroup) SchemaRef() *id.PropertySchemaID { +func (s *SchemaGroup) SchemaRef() *SchemaID { if s == nil { return nil } @@ -54,7 +53,7 @@ func (s *SchemaGroup) Fields() []*SchemaField { } // Field returns a field whose id is specified -func (s *SchemaGroup) Field(fid id.PropertySchemaFieldID) *SchemaField { +func (s *SchemaGroup) Field(fid FieldID) *SchemaField { if s == nil { return nil } @@ -78,7 +77,7 @@ func (s *SchemaGroup) FieldByPointer(ptr *Pointer) *SchemaField { return s.Field(fid) } -func (s *SchemaGroup) HasField(i id.PropertySchemaFieldID) bool { +func (s *SchemaGroup) HasField(i FieldID) bool { return s.Field(i) != nil } @@ -107,7 +106,7 @@ func (s *SchemaGroup) Title() i18n.String { } // RepresentativeFieldID returns the representative field ID of the group -func (s *SchemaGroup) RepresentativeFieldID() *id.PropertySchemaFieldID { +func (s *SchemaGroup) RepresentativeFieldID() *FieldID { if s == nil { return nil } diff --git a/pkg/property/schema_group_builder.go b/pkg/property/schema_group_builder.go index 1b61fe11..7acecdba 100644 --- a/pkg/property/schema_group_builder.go +++ b/pkg/property/schema_group_builder.go @@ -2,7 +2,6 @@ package property import ( "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" ) type SchemaGroupBuilder struct { @@ -17,7 +16,7 @@ func NewSchemaGroup() *SchemaGroupBuilder { func (b *SchemaGroupBuilder) Build() (*SchemaGroup, error) { if b.p.sid.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } return b.p, nil } @@ -30,19 +29,19 @@ func (b *SchemaGroupBuilder) MustBuild() *SchemaGroup { return p } -func (b *SchemaGroupBuilder) ID(id id.PropertySchemaGroupID) *SchemaGroupBuilder { +func (b *SchemaGroupBuilder) ID(id SchemaGroupID) *SchemaGroupBuilder { b.p.id = id return b } -func (b *SchemaGroupBuilder) Schema(sid id.PropertySchemaID) *SchemaGroupBuilder { +func (b *SchemaGroupBuilder) Schema(sid SchemaID) *SchemaGroupBuilder { b.p.sid = sid return b } func (b *SchemaGroupBuilder) Fields(fields []*SchemaField) *SchemaGroupBuilder { newFields := []*SchemaField{} - ids := map[id.PropertySchemaFieldID]struct{}{} + ids := map[FieldID]struct{}{} for _, f := range fields { if f == nil { continue @@ -72,7 +71,7 @@ func (b *SchemaGroupBuilder) Title(title i18n.String) *SchemaGroupBuilder { return b } -func (b *SchemaGroupBuilder) RepresentativeField(representativeField *id.PropertySchemaFieldID) *SchemaGroupBuilder { +func (b *SchemaGroupBuilder) RepresentativeField(representativeField *FieldID) *SchemaGroupBuilder { b.p.representativeField = representativeField.CopyRef() return b } diff --git a/pkg/property/schema_group_builder_test.go b/pkg/property/schema_group_builder_test.go index 6b88a95b..cafc7dd5 100644 --- a/pkg/property/schema_group_builder_test.go +++ b/pkg/property/schema_group_builder_test.go @@ -4,18 +4,17 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestSchemaGroupBuilder_Build(t *testing.T) { - sid := id.MustPropertySchemaID("xx~1.0.0/aa") - gid := id.PropertySchemaGroupID("xx") + sid := MustSchemaID("xx~1.0.0/aa") + gid := SchemaGroupID("xx") sf := NewSchemaField().ID("ff").Type(ValueTypeString).MustBuild() type expected struct { - ID id.PropertySchemaGroupID - Sid id.PropertySchemaID + ID SchemaGroupID + Sid SchemaID Fields []*SchemaField List bool IsAvailableIf *Condition @@ -24,8 +23,8 @@ func TestSchemaGroupBuilder_Build(t *testing.T) { testCases := []struct { Name string - ID id.PropertySchemaGroupID - Sid id.PropertySchemaID + ID SchemaGroupID + Sid SchemaID Fields []*SchemaField List bool IsAvailableIf *Condition @@ -35,7 +34,7 @@ func TestSchemaGroupBuilder_Build(t *testing.T) { }{ { Name: "fail: invalid id", - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, { Name: "success", diff --git a/pkg/property/schema_group_test.go b/pkg/property/schema_group_test.go index 09b63522..0c1a2eea 100644 --- a/pkg/property/schema_group_test.go +++ b/pkg/property/schema_group_test.go @@ -4,23 +4,22 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/i18n" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestSchemaGroup(t *testing.T) { - scid := id.PropertySchemaGroupID("aa") - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + scid := SchemaGroupID("aa") + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() testCases := []struct { Name string G *SchemaGroup Expected struct { - GIDRef *id.PropertySchemaGroupID - SIDRef *id.PropertySchemaID - GID id.PropertySchemaGroupID - SID id.PropertySchemaID + GIDRef *SchemaGroupID + SIDRef *SchemaID + GID SchemaGroupID + SID SchemaID Fields []*SchemaField Title i18n.String IsAvailableIf *Condition @@ -34,10 +33,10 @@ func TestSchemaGroup(t *testing.T) { Name: "success", G: NewSchemaGroup().ID(scid).Schema(sid).Fields([]*SchemaField{sf}).MustBuild(), Expected: struct { - GIDRef *id.PropertySchemaGroupID - SIDRef *id.PropertySchemaID - GID id.PropertySchemaGroupID - SID id.PropertySchemaID + GIDRef *SchemaGroupID + SIDRef *SchemaID + GID SchemaGroupID + SID SchemaID Fields []*SchemaField Title i18n.String IsAvailableIf *Condition @@ -71,15 +70,15 @@ func TestSchemaGroup(t *testing.T) { } func TestSchemaGroup_Field(t *testing.T) { - scid := id.PropertySchemaGroupID("aa") - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + scid := SchemaGroupID("aa") + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() testCases := []struct { Name string G *SchemaGroup PTR *Pointer - Input id.PropertySchemaFieldID + Input FieldID Expected *SchemaField }{ { @@ -95,8 +94,8 @@ func TestSchemaGroup_Field(t *testing.T) { { Name: "not found", G: NewSchemaGroup().ID(scid).Schema(sid).Fields([]*SchemaField{sf}).MustBuild(), - PTR: NewPointer(nil, nil, id.PropertySchemaFieldID("zz").Ref()), - Input: id.PropertySchemaFieldID("zz"), + PTR: NewPointer(nil, nil, FieldID("zz").Ref()), + Input: FieldID("zz"), }, } @@ -112,7 +111,7 @@ func TestSchemaGroup_Field(t *testing.T) { } func TestSchemaGroup_SetTitle(t *testing.T) { - sg := NewSchemaGroup().ID(id.PropertySchemaGroupID("aa")).Schema(id.MustPropertySchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() + sg := NewSchemaGroup().ID(SchemaGroupID("aa")).Schema(MustSchemaID("xx~1.0.0/aa")).Fields([]*SchemaField{sf}).MustBuild() sg.SetTitle(i18n.StringFrom("ttt")) assert.Equal(t, i18n.StringFrom("ttt"), sg.Title()) } diff --git a/pkg/property/schema_list.go b/pkg/property/schema_list.go index 8666f60c..7c1bd062 100644 --- a/pkg/property/schema_list.go +++ b/pkg/property/schema_list.go @@ -1,14 +1,12 @@ package property -import "github.com/reearth/reearth-backend/pkg/id" - type SchemaList []*Schema func (l SchemaList) Map() SchemaMap { return SchemaMapFrom(l) } -type SchemaMap map[id.PropertySchemaID]*Schema +type SchemaMap map[SchemaID]*Schema func SchemaMapFrom(l []*Schema) SchemaMap { m := make(SchemaMap, len(l)) diff --git a/pkg/property/schema_test.go b/pkg/property/schema_test.go index 6c712043..95b4d206 100644 --- a/pkg/property/schema_test.go +++ b/pkg/property/schema_test.go @@ -3,7 +3,6 @@ package property import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -16,7 +15,7 @@ func TestSchema_Nil(t *testing.T) { } func TestSchema_Field(t *testing.T) { - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() sg := NewSchemaGroup().ID("aaa").Schema(sid).Fields([]*SchemaField{sf}).MustBuild() @@ -24,7 +23,7 @@ func TestSchema_Field(t *testing.T) { Name string S *Schema PTR *Pointer - Input id.PropertySchemaFieldID + Input FieldID Expected *SchemaField }{ { @@ -40,8 +39,8 @@ func TestSchema_Field(t *testing.T) { { Name: "not found", S: NewSchema().ID(sid).Groups([]*SchemaGroup{sg}).MustBuild(), - PTR: NewPointer(nil, nil, id.PropertySchemaFieldID("zz").Ref()), - Input: id.PropertySchemaFieldID("zz"), + PTR: NewPointer(nil, nil, FieldID("zz").Ref()), + Input: FieldID("zz"), }, } @@ -56,7 +55,7 @@ func TestSchema_Field(t *testing.T) { } func TestSchema_Group(t *testing.T) { - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() sg := NewSchemaGroup().ID("aaa").Schema(sid).Fields([]*SchemaField{sf}).MustBuild() @@ -64,8 +63,8 @@ func TestSchema_Group(t *testing.T) { Name string S *Schema PTR *Pointer - Input id.PropertySchemaGroupID - InputField id.PropertySchemaFieldID + Input SchemaGroupID + InputField FieldID Expected *SchemaGroup }{ { @@ -82,8 +81,8 @@ func TestSchema_Group(t *testing.T) { { Name: "not found", S: NewSchema().ID(sid).Groups([]*SchemaGroup{sg}).MustBuild(), - PTR: NewPointer(nil, nil, id.PropertySchemaFieldID("zz").Ref()), - Input: id.PropertySchemaGroupID("zz"), + PTR: NewPointer(nil, nil, FieldID("zz").Ref()), + Input: SchemaGroupID("zz"), }, } @@ -99,7 +98,7 @@ func TestSchema_Group(t *testing.T) { } func TestSchema_DetectDuplicatedFields(t *testing.T) { - sid := id.MustPropertySchemaID("xx~1.0.0/aa") + sid := MustSchemaID("xx~1.0.0/aa") sf := NewSchemaField().ID("aa").Type(ValueTypeString).MustBuild() sg := NewSchemaGroup().ID("aaa").Schema(sid).Fields([]*SchemaField{sf}).MustBuild() @@ -115,13 +114,13 @@ func TestSchema_DetectDuplicatedFields(t *testing.T) { { Name: "invalid: URL", S: NewSchema().ID(sid).Groups([]*SchemaGroup{sg}).MustBuild(), - LF: LinkableFields{URL: NewPointer(nil, nil, id.PropertySchemaFieldID("xx").Ref())}, + LF: LinkableFields{URL: NewPointer(nil, nil, FieldID("xx").Ref())}, Expected: false, }, { Name: "invalid: Lng", S: NewSchema().ID(sid).Groups([]*SchemaGroup{sg}).MustBuild(), - LF: LinkableFields{LatLng: NewPointer(nil, nil, id.PropertySchemaFieldID("xx").Ref())}, + LF: LinkableFields{LatLng: NewPointer(nil, nil, FieldID("xx").Ref())}, Expected: false, }, { diff --git a/pkg/property/sealed.go b/pkg/property/sealed.go index 2279ad0c..43c3bc52 100644 --- a/pkg/property/sealed.go +++ b/pkg/property/sealed.go @@ -4,28 +4,27 @@ import ( "context" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" ) type Sealed struct { - Original *id.PropertyID - Parent *id.PropertyID - Schema id.PropertySchemaID - LinkedDataset *id.DatasetID + Original *ID + Parent *ID + Schema SchemaID + LinkedDataset *DatasetID Items []*SealedItem } type SealedItem struct { - Original *id.PropertyItemID - Parent *id.PropertyItemID - SchemaGroup id.PropertySchemaGroupID - LinkedDataset *id.DatasetID + Original *ItemID + Parent *ItemID + SchemaGroup SchemaGroupID + LinkedDataset *DatasetID Fields []*SealedField Groups []*SealedItem } type SealedField struct { - ID id.PropertySchemaFieldID + ID FieldID Val *ValueAndDatasetValue } @@ -164,7 +163,7 @@ func sealedFieldsInterface(fields []*SealedField) map[string]interface{} { return item } -func (s *Sealed) Item(i id.PropertyItemID) *SealedItem { +func (s *Sealed) Item(i ItemID) *SealedItem { if s == nil { return nil } @@ -192,7 +191,7 @@ func (s *Sealed) ItemBy(ptr *Pointer) *SealedItem { return nil } -func (s *Sealed) ItemBySchemaGroup(i id.PropertySchemaGroupID) *SealedItem { +func (s *Sealed) ItemBySchemaGroup(i SchemaGroupID) *SealedItem { if s == nil { return nil } @@ -204,7 +203,7 @@ func (s *Sealed) ItemBySchemaGroup(i id.PropertySchemaGroupID) *SealedItem { return nil } -func (s *Sealed) Field(id id.PropertySchemaFieldID) *SealedField { +func (s *Sealed) Field(id FieldID) *SealedField { if s == nil { return nil } @@ -232,14 +231,14 @@ func (s *Sealed) FieldBy(ptr *Pointer) *SealedField { return nil } -func (s *SealedItem) Match(id id.PropertyItemID) bool { +func (s *SealedItem) Match(id ItemID) bool { if s == nil { return false } return s.Original != nil && *s.Original == id || s.Parent != nil && *s.Parent == id } -func (s *SealedItem) Group(id id.PropertyItemID) *SealedItem { +func (s *SealedItem) Group(id ItemID) *SealedItem { if s == nil { return nil } @@ -251,7 +250,7 @@ func (s *SealedItem) Group(id id.PropertyItemID) *SealedItem { return nil } -func (s *SealedItem) Field(id id.PropertySchemaFieldID) *SealedField { +func (s *SealedItem) Field(id FieldID) *SealedField { if s == nil { return nil } diff --git a/pkg/property/sealed_test.go b/pkg/property/sealed_test.go index 209856c8..b71907d8 100644 --- a/pkg/property/sealed_test.go +++ b/pkg/property/sealed_test.go @@ -5,25 +5,24 @@ import ( "testing" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) var ( - sid = id.NewSceneID() - ds = id.NewDatasetSchemaID() - df = id.NewDatasetSchemaFieldID() - d = id.NewDatasetID() - opid = id.NewPropertyID() - ppid = id.NewPropertyID() - psid = id.MustPropertySchemaID("hoge~0.1.0/fff") - psiid1 = id.PropertySchemaGroupID("x") - psiid2 = id.PropertySchemaGroupID("y") - i1id = id.NewPropertyItemID() - i2id = id.NewPropertyItemID() - i3id = id.NewPropertyItemID() - i4id = id.NewPropertyItemID() - i5id = id.NewPropertyItemID() + sid = NewSceneID() + ds = NewDatasetSchemaID() + df = NewDatasetFieldID() + d = NewDatasetID() + opid = NewID() + ppid = NewID() + psid = MustSchemaID("hoge~0.1.0/fff") + psiid1 = SchemaGroupID("x") + psiid2 = SchemaGroupID("y") + i1id = NewItemID() + i2id = NewItemID() + i3id = NewItemID() + i4id = NewItemID() + i5id = NewItemID() ) func TestSeal(t *testing.T) { @@ -57,12 +56,12 @@ func TestSeal(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, @@ -78,12 +77,12 @@ func TestSeal(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("aaa"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("aaa"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, @@ -92,7 +91,7 @@ func TestSeal(t *testing.T) { }, }, }, - DSGL: dataset.GraphLoaderFromMap(map[id.DatasetID]*dataset.Dataset{ + DSGL: dataset.GraphLoaderFromMap(map[DatasetID]*dataset.Dataset{ d: dataset.New().Scene(sid).ID(d).Schema(ds).Fields([]*dataset.Field{ dataset.NewField(df, dataset.ValueTypeString.ValueFrom("bbb"), ""), }).MustBuild(), @@ -177,8 +176,8 @@ func TestSeal(t *testing.T) { } func TestSealProperty(t *testing.T) { - pid := id.NewPropertyID() - ps := id.MustPropertySchemaID("xxx~1.1.1/aa") + pid := NewID() + ps := MustSchemaID("xxx~1.1.1/aa") testCases := []struct { Name string Input *Property @@ -189,7 +188,7 @@ func TestSealProperty(t *testing.T) { }, { Name: "seal property", - Input: New().ID(pid).Scene(id.NewSceneID()).Schema(ps).MustBuild(), + Input: New().ID(pid).Scene(NewSceneID()).Schema(ps).MustBuild(), Expected: &Sealed{ Original: pid.Ref(), Parent: nil, @@ -236,12 +235,12 @@ func TestSealedItemFrom(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("a"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("b"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, @@ -250,7 +249,7 @@ func TestSealedItemFrom(t *testing.T) { }, }, }, - DSGL: dataset.GraphLoaderFromMap(map[id.DatasetID]*dataset.Dataset{ + DSGL: dataset.GraphLoaderFromMap(map[DatasetID]*dataset.Dataset{ d: dataset.New().Scene(sid).ID(d).Schema(ds).Fields([]*dataset.Field{ dataset.NewField(df, dataset.ValueTypeString.ValueFrom("bbb"), ""), }).MustBuild(), @@ -303,12 +302,12 @@ func TestSealedItemFrom(t *testing.T) { LinkedDataset: &d, Fields: []*MergedField{ { - ID: id.PropertySchemaFieldID("a"), + ID: FieldID("a"), Value: ValueTypeString.ValueFrom("aaa"), Type: ValueTypeString, }, { - ID: id.PropertySchemaFieldID("b"), + ID: FieldID("b"), Value: ValueTypeString.ValueFrom("aaa"), Links: NewLinks([]*Link{NewLink(d, ds, df)}), Type: ValueTypeString, @@ -317,7 +316,7 @@ func TestSealedItemFrom(t *testing.T) { }, }, }, - DSGL: dataset.GraphLoaderFromMap(map[id.DatasetID]*dataset.Dataset{ + DSGL: dataset.GraphLoaderFromMap(map[DatasetID]*dataset.Dataset{ d: dataset.New().Scene(sid).ID(d).Schema(ds).Fields([]*dataset.Field{ dataset.NewField(df, dataset.ValueTypeString.ValueFrom("bbb"), ""), }).MustBuild(), @@ -475,7 +474,7 @@ func TestSealedItem_Match(t *testing.T) { testCases := []struct { Name string SI *SealedItem - Input id.PropertyItemID + Input ItemID Expected bool }{ { @@ -605,7 +604,7 @@ func TestSealed_ItemBy(t *testing.T) { }, }, }, - Input: NewPointer(psiid1.Ref(), i1id.Ref(), id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(psiid1.Ref(), i1id.Ref(), FieldID("a").Ref()), Expected: &SealedItem{ SchemaGroup: psiid1, Original: &i1id, @@ -703,7 +702,7 @@ func TestSealed_ItemBy(t *testing.T) { }, }, }, - Input: NewPointer(nil, i1id.Ref(), id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(nil, i1id.Ref(), FieldID("a").Ref()), Expected: &SealedItem{ SchemaGroup: psiid1, Original: &i1id, @@ -801,7 +800,7 @@ func TestSealed_ItemBy(t *testing.T) { }, }, }, - Input: NewPointer(nil, nil, id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(nil, nil, FieldID("a").Ref()), Expected: nil, }, } @@ -892,7 +891,7 @@ func TestSealed_FieldBy(t *testing.T) { }, }, }, - Input: NewPointer(psiid1.Ref(), i1id.Ref(), id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(psiid1.Ref(), i1id.Ref(), FieldID("a").Ref()), Expected: &SealedField{ ID: "a", Val: NewValueAndDatasetValue( @@ -967,7 +966,7 @@ func TestSealed_FieldBy(t *testing.T) { }, }, }, - Input: NewPointer(nil, i3id.Ref(), id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(nil, i3id.Ref(), FieldID("a").Ref()), Expected: &SealedField{ ID: "a", Val: NewValueAndDatasetValue( @@ -1042,7 +1041,7 @@ func TestSealed_FieldBy(t *testing.T) { }, }, }, - Input: NewPointer(nil, nil, id.PropertySchemaFieldID("a").Ref()), + Input: NewPointer(nil, nil, FieldID("a").Ref()), Expected: &SealedField{ ID: "a", Val: NewValueAndDatasetValue( diff --git a/pkg/scene/builder.go b/pkg/scene/builder.go index 085ac3aa..8124303e 100644 --- a/pkg/scene/builder.go +++ b/pkg/scene/builder.go @@ -2,8 +2,6 @@ package scene import ( "time" - - "github.com/reearth/reearth-backend/pkg/id" ) type Builder struct { @@ -15,14 +13,14 @@ func New() *Builder { } func (b *Builder) Build() (*Scene, error) { - if b.scene.id.ID().IsNil() { - return nil, id.ErrInvalidID + if b.scene.id.IsNil() { + return nil, ErrInvalidID } if b.scene.team.ID().IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.scene.rootLayer.ID().IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.scene.widgetSystem == nil { b.scene.widgetSystem = NewWidgetSystem(nil) @@ -47,22 +45,22 @@ func (b *Builder) MustBuild() *Scene { return r } -func (b *Builder) ID(id id.SceneID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.scene.id = id return b } func (b *Builder) NewID() *Builder { - b.scene.id = id.NewSceneID() + b.scene.id = NewID() return b } -func (b *Builder) Project(prj id.ProjectID) *Builder { +func (b *Builder) Project(prj ProjectID) *Builder { b.scene.project = prj return b } -func (b *Builder) Team(team id.TeamID) *Builder { +func (b *Builder) Team(team TeamID) *Builder { b.scene.team = team return b } @@ -83,7 +81,7 @@ func (b *Builder) WidgetAlignSystem(widgetAlignSystem *WidgetAlignSystem) *Build return b } -func (b *Builder) RootLayer(rootLayer id.LayerID) *Builder { +func (b *Builder) RootLayer(rootLayer LayerID) *Builder { b.scene.rootLayer = rootLayer return b } @@ -94,7 +92,7 @@ func (b *Builder) PluginSystem(pluginSystem *PluginSystem) *Builder { return b } -func (b *Builder) Property(p id.PropertyID) *Builder { +func (b *Builder) Property(p PropertyID) *Builder { b.scene.property = p return b } diff --git a/pkg/scene/builder/builder_test.go b/pkg/scene/builder/builder_test.go index dc240799..d081abb5 100644 --- a/pkg/scene/builder/builder_test.go +++ b/pkg/scene/builder/builder_test.go @@ -6,7 +6,6 @@ import ( "time" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/scene" @@ -15,31 +14,31 @@ import ( func TestSceneBuilder(t *testing.T) { // ids - sceneID := id.NewSceneID() - scenePropertyID := id.NewPropertyID() - propertySchemaID := id.MustPropertySchemaID("hoge~0.1.0/foobar") - pluginID := id.MustPluginID("hoge~0.1.0") - pluginExtension1ID := id.PluginExtensionID("ext") - pluginExtension2ID := id.PluginExtensionID("ext2") - propertySchemaField1ID := id.PropertySchemaFieldID("a") - propertySchemaField2ID := id.PropertySchemaFieldID("b") - propertySchemaField3ID := id.PropertySchemaFieldID("c") - propertySchemaGroup1ID := id.PropertySchemaGroupID("A") - propertySchemaGroup2ID := id.PropertySchemaGroupID("B") - propertyItemID1 := id.NewPropertyItemID() - propertyItemID2 := id.NewPropertyItemID() + sceneID := scene.NewID() + scenePropertyID := property.NewID() + propertySchemaID := property.MustSchemaID("hoge~0.1.0/foobar") + pluginID := layer.MustPluginID("hoge~0.1.0") + pluginExtension1ID := layer.PluginExtensionID("ext") + pluginExtension2ID := layer.PluginExtensionID("ext2") + propertySchemaField1ID := property.FieldID("a") + propertySchemaField2ID := property.FieldID("b") + propertySchemaField3ID := property.FieldID("c") + propertySchemaGroup1ID := property.SchemaGroupID("A") + propertySchemaGroup2ID := property.SchemaGroupID("B") + propertyItemID1 := property.NewItemID() + propertyItemID2 := property.NewItemID() // datasets - dss1id := id.NewDatasetSchemaID() - dss2id := id.NewDatasetSchemaID() - dss3id := id.NewDatasetSchemaID() - ds1id := id.NewDatasetID() - ds2id := id.NewDatasetID() - ds3id := id.NewDatasetID() - ds1f1 := id.NewDatasetSchemaFieldID() - ds1f2 := id.NewDatasetSchemaFieldID() - ds2f1 := id.NewDatasetSchemaFieldID() - ds3f1 := id.NewDatasetSchemaFieldID() + dss1id := dataset.NewSchemaID() + dss2id := dataset.NewSchemaID() + dss3id := dataset.NewSchemaID() + ds1id := dataset.NewID() + ds2id := dataset.NewID() + ds3id := dataset.NewID() + ds1f1 := dataset.NewFieldID() + ds1f2 := dataset.NewFieldID() + ds2f1 := dataset.NewFieldID() + ds3f1 := dataset.NewFieldID() ds1 := dataset.New().ID(ds1id).Fields([]*dataset.Field{ dataset.NewField( ds1f1, @@ -149,7 +148,7 @@ func TestSceneBuilder(t *testing.T) { Extension(&pluginExtension1ID). Property(layer2p.IDRef()). Infobox(layer2ib). - Layers(layer.NewIDList([]id.LayerID{layer21.ID()})). + Layers(layer.NewIDList([]layer.ID{layer21.ID()})). MustBuild() // layer3: full-linked layer item with infobox @@ -245,7 +244,7 @@ func TestSceneBuilder(t *testing.T) { Property(layer4p.IDRef()). Infobox(layer4ib). LinkedDatasetSchema(&dss3id). - Layers(layer.NewIDList([]id.LayerID{layer41.ID()})). + Layers(layer.NewIDList([]layer.ID{layer41.ID()})). MustBuild() // layer5: linked layer group and children with overrided property @@ -309,7 +308,7 @@ func TestSceneBuilder(t *testing.T) { Extension(&pluginExtension1ID). Property(layer5p.IDRef()). LinkedDatasetSchema(&dss1id). - Layers(layer.NewIDList([]id.LayerID{layer51.ID()})). + Layers(layer.NewIDList([]layer.ID{layer51.ID()})). MustBuild() layer6p := property.New(). NewID(). @@ -343,7 +342,7 @@ func TestSceneBuilder(t *testing.T) { MustBuild() // root layer - rootLayer := layer.NewGroup().NewID().Scene(sceneID).Layers(layer.NewIDList([]id.LayerID{ + rootLayer := layer.NewGroup().NewID().Scene(sceneID).Layers(layer.NewIDList([]layer.ID{ layer1.ID(), layer2.ID(), layer3.ID(), @@ -367,8 +366,8 @@ func TestSceneBuilder(t *testing.T) { }). MustBuild() - sceneWidgetID1 := id.NewWidgetID() - sceneWidgetID2 := id.NewWidgetID() + sceneWidgetID1 := scene.NewWidgetID() + sceneWidgetID2 := scene.NewWidgetID() sceneWidget1 := scene.MustNewWidget( sceneWidgetID1, pluginID, @@ -390,8 +389,8 @@ func TestSceneBuilder(t *testing.T) { scene := scene.New(). ID(sceneID). - Project(id.NewProjectID()). - Team(id.NewTeamID()). + Project(scene.NewProjectID()). + Team(scene.NewTeamID()). Property(scenep.ID()). WidgetSystem(scene.NewWidgetSystem([]*scene.Widget{ sceneWidget1, sceneWidget2, diff --git a/pkg/scene/builder/encoder_test.go b/pkg/scene/builder/encoder_test.go index 9c1177b3..798b0413 100644 --- a/pkg/scene/builder/encoder_test.go +++ b/pkg/scene/builder/encoder_test.go @@ -3,10 +3,10 @@ package builder import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/merging" "github.com/reearth/reearth-backend/pkg/property" + "github.com/reearth/reearth-backend/pkg/scene" "github.com/stretchr/testify/assert" ) @@ -88,18 +88,18 @@ func TestEncoder_Encode(t *testing.T) { } func TestEncoder_Layers(t *testing.T) { - lid := id.NewLayerID() - sid := id.NewSceneID() - pid := id.NewPropertyID() - ex := id.PluginExtensionID("marker") - iid := id.NewPropertyItemID() + lid := layer.NewID() + sid := scene.NewID() + pid := property.NewID() + ex := layer.PluginExtensionID("marker") + iid := property.NewItemID() v1 := property.LatLng{ Lat: 4.4, Lng: 53.4, } f1 := property.SealedField{ - ID: id.PropertySchemaFieldID("location"), + ID: property.FieldID("location"), Val: property.NewValueAndDatasetValue( property.ValueTypeLatLng, nil, @@ -111,7 +111,7 @@ func TestEncoder_Layers(t *testing.T) { item1 := property.SealedItem{ Original: &iid, Parent: nil, - SchemaGroup: id.PropertySchemaGroupID("default"), + SchemaGroup: property.SchemaGroupID("default"), LinkedDataset: nil, Fields: fl1, Groups: nil, @@ -132,7 +132,7 @@ func TestEncoder_Layers(t *testing.T) { Scene: sid, Property: nil, Infobox: nil, - PluginID: &id.OfficialPluginID, + PluginID: &layer.OfficialPluginID, ExtensionID: &ex, }, Property: &sp, @@ -156,7 +156,7 @@ func TestEncoder_Layers(t *testing.T) { SL: sealed, Expected: &layerJSON{ ID: lid.String(), - PluginID: id.OfficialPluginID.StringRef(), + PluginID: layer.OfficialPluginID.StringRef(), ExtensionID: ex.StringRef(), Name: "test", Property: map[string]interface{}{"default": map[string]interface{}{"location": property.LatLng{Lat: 4.4, Lng: 53.4}}}, diff --git a/pkg/scene/builder/scene.go b/pkg/scene/builder/scene.go index 973598bb..d517afb4 100644 --- a/pkg/scene/builder/scene.go +++ b/pkg/scene/builder/scene.go @@ -4,7 +4,6 @@ import ( "context" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/scene" ) @@ -85,7 +84,7 @@ func (b *Builder) property(ctx context.Context, p *property.Property) propertyJS return property.SealProperty(ctx, p).Interface() } -func findProperty(pp []*property.Property, i id.PropertyID) *property.Property { +func findProperty(pp []*property.Property, i property.ID) *property.Property { for _, p := range pp { if p.ID() == i { return p @@ -94,7 +93,7 @@ func findProperty(pp []*property.Property, i id.PropertyID) *property.Property { return nil } -func toString(wids []id.WidgetID) []string { +func toString(wids []scene.WidgetID) []string { if wids == nil { return nil } diff --git a/pkg/scene/builder/scene_test.go b/pkg/scene/builder/scene_test.go index 438206b8..f33f0b1b 100644 --- a/pkg/scene/builder/scene_test.go +++ b/pkg/scene/builder/scene_test.go @@ -3,16 +3,15 @@ package builder import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/property" "github.com/reearth/reearth-backend/pkg/scene" "github.com/stretchr/testify/assert" ) func TestScene_FindProperty(t *testing.T) { - p1 := id.NewPropertyID() - sid := id.NewSceneID() - scid := id.MustPropertySchemaID("xx~1.0.0/aa") + p1 := property.NewID() + sid := scene.NewID() + scid := property.MustSchemaID("xx~1.0.0/aa") pl := []*property.Property{ property.New().NewID().Scene(sid).Schema(scid).MustBuild(), property.New().ID(p1).Scene(sid).Schema(scid).MustBuild(), @@ -20,7 +19,7 @@ func TestScene_FindProperty(t *testing.T) { testCases := []struct { Name string PL []*property.Property - Input id.PropertyID + Input property.ID Expected *property.Property }{ { @@ -32,7 +31,7 @@ func TestScene_FindProperty(t *testing.T) { { Name: " NotFound", PL: pl, - Input: id.NewPropertyID(), + Input: property.NewID(), Expected: nil, }, } @@ -47,22 +46,22 @@ func TestScene_FindProperty(t *testing.T) { } func TestScene_ToString(t *testing.T) { - wid := id.NewWidgetID() + wid := scene.NewWidgetID() widS := wid.String() - wid2 := id.NewWidgetID() + wid2 := scene.NewWidgetID() wid2S := wid2.String() - wid3 := id.NewWidgetID() + wid3 := scene.NewWidgetID() wid3S := wid3.String() - wids := []id.WidgetID{wid, wid2, wid3} + wids := []scene.WidgetID{wid, wid2, wid3} widsString := []string{widS, wid2S, wid3S} testCases := []struct { Name string - Input []id.WidgetID + Input []scene.WidgetID Expected []string }{ { - Name: "Convert a slice of id.WidgetID to a slice of strings", + Name: "Convert a slice of scene.WidgetID to a slice of strings", Input: wids, Expected: widsString, }, @@ -83,7 +82,7 @@ func TestScene_ToString(t *testing.T) { } func TestBuildWidgetAlignSystem(t *testing.T) { - wid := id.NewWidgetID() + wid := scene.NewWidgetID() was := scene.NewWidgetAlignSystem() was.Area(scene.WidgetLocation{ Zone: scene.WidgetZoneInner, diff --git a/pkg/scene/builder_test.go b/pkg/scene/builder_test.go index 8dadac45..81a92427 100644 --- a/pkg/scene/builder_test.go +++ b/pkg/scene/builder_test.go @@ -5,103 +5,100 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestBuilder_IDs(t *testing.T) { - tid := id.NewTeamID() - lid := id.NewLayerID() + tid := NewTeamID() + lid := NewLayerID() b := New().NewID().RootLayer(lid).Team(tid).MustBuild() assert.NotNil(t, b.ID()) assert.Equal(t, tid, b.Team()) assert.Equal(t, lid, b.RootLayer()) - sid := id.NewSceneID() + sid := NewID() b2 := New().ID(sid).RootLayer(lid).Team(tid).MustBuild() assert.Equal(t, sid, b2.ID()) } func TestBuilder_UpdatedAt(t *testing.T) { ti := time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC) - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).UpdatedAt(ti).MustBuild() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).UpdatedAt(ti).MustBuild() assert.Equal(t, ti, b.UpdatedAt()) } func TestBuilder_Property(t *testing.T) { - pid := id.NewPropertyID() - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).Property(pid).MustBuild() + pid := NewPropertyID() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).Property(pid).MustBuild() assert.Equal(t, pid, b.Property()) } func TestBuilder_PluginSystem(t *testing.T) { ps := NewPluginSystem([]*Plugin{ - NewPlugin(id.OfficialPluginID, id.NewPropertyID().Ref()), + NewPlugin(OfficialPluginID, NewPropertyID().Ref()), }) - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).PluginSystem(ps).MustBuild() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).PluginSystem(ps).MustBuild() assert.Equal(t, ps, b.PluginSystem()) } func TestBuilder_Project(t *testing.T) { - pid := id.NewProjectID() - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).Project(pid).MustBuild() + pid := NewProjectID() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).Project(pid).MustBuild() assert.Equal(t, pid, b.Project()) } func TestBuilder_WidgetSystem(t *testing.T) { - nid := id.New() ws := NewWidgetSystem([]*Widget{ - MustNewWidget(id.WidgetID(nid), id.OfficialPluginID, "xxx", id.NewPropertyID(), true, false), + MustNewWidget(NewWidgetID(), OfficialPluginID, "xxx", NewPropertyID(), true, false), }) - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).WidgetSystem(ws).MustBuild() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).WidgetSystem(ws).MustBuild() assert.Equal(t, ws, b.WidgetSystem()) } func TestBuilder_WidgetAlignSystem(t *testing.T) { was := NewWidgetAlignSystem() - b := New().NewID().RootLayer(id.NewLayerID()).Team(id.NewTeamID()).WidgetAlignSystem(was).MustBuild() + b := New().NewID().RootLayer(NewLayerID()).Team(NewTeamID()).WidgetAlignSystem(was).MustBuild() assert.Equal(t, was, b.WidgetAlignSystem()) } func TestBuilder_Build(t *testing.T) { - tid := id.NewTeamID() - sid := id.NewSceneID() - pid := id.NewProjectID() - ppid := id.NewPropertyID() - lid := id.NewLayerID() - nid := id.New() + tid := NewTeamID() + sid := NewID() + pid := NewProjectID() + ppid := NewPropertyID() + lid := NewLayerID() ws := NewWidgetSystem([]*Widget{ - MustNewWidget(id.WidgetID(nid), id.OfficialPluginID, "xxx", ppid, true, false), + MustNewWidget(NewWidgetID(), OfficialPluginID, "xxx", ppid, true, false), }) was := NewWidgetAlignSystem() ps := NewPluginSystem([]*Plugin{ - NewPlugin(id.OfficialPluginID, ppid.Ref()), + NewPlugin(OfficialPluginID, ppid.Ref()), }) testCases := []struct { Name string - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID Expected struct { - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID } err error }{ { Name: "fail nil scene id", - Id: id.SceneID{}, + Id: ID{}, Project: pid, Team: tid, RootLayer: lid, @@ -110,33 +107,33 @@ func TestBuilder_Build(t *testing.T) { PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "fail nil team id", Id: sid, Project: pid, - Team: id.TeamID{}, + Team: TeamID{}, RootLayer: lid, WidgetSystem: ws, WidgetAlignSystem: was, PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "fail nil root layer id", Id: sid, Project: pid, Team: tid, - RootLayer: id.LayerID{}, + RootLayer: LayerID{}, WidgetSystem: ws, WidgetAlignSystem: was, PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "success build new scene", @@ -150,15 +147,15 @@ func TestBuilder_Build(t *testing.T) { UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, Expected: struct { - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID }{ Id: sid, Project: pid, @@ -205,46 +202,45 @@ func TestBuilder_Build(t *testing.T) { } func TestBuilder_MustBuild(t *testing.T) { - tid := id.NewTeamID() - sid := id.NewSceneID() - pid := id.NewProjectID() - ppid := id.NewPropertyID() - lid := id.NewLayerID() - nid := id.New() + tid := NewTeamID() + sid := NewID() + pid := NewProjectID() + ppid := NewPropertyID() + lid := NewLayerID() ws := NewWidgetSystem([]*Widget{ - MustNewWidget(id.WidgetID(nid), id.OfficialPluginID, "xxx", ppid, true, false), + MustNewWidget(NewWidgetID(), OfficialPluginID, "xxx", ppid, true, false), }) was := NewWidgetAlignSystem() ps := NewPluginSystem([]*Plugin{ - NewPlugin(id.OfficialPluginID, ppid.Ref()), + NewPlugin(OfficialPluginID, ppid.Ref()), }) testCases := []struct { Name string - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID Expected struct { - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID } err error }{ { Name: "fail nil scene id", - Id: id.SceneID{}, + Id: ID{}, Project: pid, Team: tid, RootLayer: lid, @@ -253,33 +249,33 @@ func TestBuilder_MustBuild(t *testing.T) { PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "fail nil team id", Id: sid, Project: pid, - Team: id.TeamID{}, + Team: TeamID{}, RootLayer: lid, WidgetSystem: ws, WidgetAlignSystem: was, PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "fail nil root layer id", Id: sid, Project: pid, Team: tid, - RootLayer: id.LayerID{}, + RootLayer: LayerID{}, WidgetSystem: ws, WidgetAlignSystem: was, PluginSystem: ps, UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, - err: id.ErrInvalidID, + err: ErrInvalidID, }, { Name: "success build new scene", @@ -293,15 +289,15 @@ func TestBuilder_MustBuild(t *testing.T) { UpdatedAt: time.Date(2000, 1, 1, 1, 1, 0, 0, time.UTC), Property: ppid, Expected: struct { - Id id.SceneID - Project id.ProjectID - Team id.TeamID - RootLayer id.LayerID + Id ID + Project ProjectID + Team TeamID + RootLayer LayerID WidgetSystem *WidgetSystem WidgetAlignSystem *WidgetAlignSystem PluginSystem *PluginSystem UpdatedAt time.Time - Property id.PropertyID + Property PropertyID }{ Id: sid, Project: pid, diff --git a/pkg/scene/cluster.go b/pkg/scene/cluster.go index f32cfb43..16888498 100644 --- a/pkg/scene/cluster.go +++ b/pkg/scene/cluster.go @@ -1,16 +1,14 @@ package scene -import "github.com/reearth/reearth-backend/pkg/id" - type Cluster struct { - id id.ClusterID + id ClusterID name string - property id.PropertyID + property PropertyID } -func NewCluster(cid id.ClusterID, name string, pid id.PropertyID) (*Cluster, error) { +func NewCluster(cid ClusterID, name string, pid PropertyID) (*Cluster, error) { if cid.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } return &Cluster{ id: cid, @@ -19,9 +17,9 @@ func NewCluster(cid id.ClusterID, name string, pid id.PropertyID) (*Cluster, err }, nil } -func (c *Cluster) ID() id.ClusterID { +func (c *Cluster) ID() ClusterID { if c == nil { - return id.ClusterID{} + return ClusterID{} } return c.id } @@ -33,9 +31,9 @@ func (c *Cluster) Name() string { return c.name } -func (c *Cluster) Property() id.PropertyID { +func (c *Cluster) Property() PropertyID { if c == nil { - return id.PropertyID{} + return PropertyID{} } return c.property } @@ -47,7 +45,7 @@ func (c *Cluster) Rename(name string) { c.name = name } -func (c *Cluster) UpdateProperty(pid id.PropertyID) { +func (c *Cluster) UpdateProperty(pid PropertyID) { if c == nil { return } diff --git a/pkg/scene/cluster_list.go b/pkg/scene/cluster_list.go index 36a86f01..2addbc3a 100644 --- a/pkg/scene/cluster_list.go +++ b/pkg/scene/cluster_list.go @@ -1,7 +1,5 @@ package scene -import "github.com/reearth/reearth-backend/pkg/id" - type ClusterList struct { clusters []*Cluster } @@ -21,7 +19,7 @@ func (tl *ClusterList) Clusters() []*Cluster { return append([]*Cluster{}, tl.clusters...) } -func (tl *ClusterList) Has(tid id.ClusterID) bool { +func (tl *ClusterList) Has(tid ClusterID) bool { if tl == nil { return false } @@ -40,7 +38,7 @@ func (tl *ClusterList) Add(clusters ...*Cluster) { tl.clusters = append(tl.clusters, clusters...) } -func (tl *ClusterList) Get(cid id.ClusterID) *Cluster { +func (tl *ClusterList) Get(cid ClusterID) *Cluster { if tl == nil { return nil } @@ -52,7 +50,7 @@ func (tl *ClusterList) Get(cid id.ClusterID) *Cluster { return nil } -func (tl *ClusterList) Remove(clusters ...id.ClusterID) { +func (tl *ClusterList) Remove(clusters ...ClusterID) { if tl == nil { return } @@ -66,11 +64,11 @@ func (tl *ClusterList) Remove(clusters ...id.ClusterID) { } } -func (tl *ClusterList) Properties() []id.PropertyID { +func (tl *ClusterList) Properties() []PropertyID { if tl == nil { return nil } - res := make([]id.PropertyID, 0, len(tl.clusters)) + res := make([]PropertyID, 0, len(tl.clusters)) for _, c := range tl.clusters { res = append(res, c.property) } diff --git a/pkg/scene/cluster_list_test.go b/pkg/scene/cluster_list_test.go index be15a429..1fafc894 100644 --- a/pkg/scene/cluster_list_test.go +++ b/pkg/scene/cluster_list_test.go @@ -3,13 +3,12 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestList_Add(t *testing.T) { - c1, _ := NewCluster(id.NewClusterID(), "c1", id.NewPropertyID()) - c2, _ := NewCluster(id.NewClusterID(), "c2", id.NewPropertyID()) + c1, _ := NewCluster(NewClusterID(), "c1", NewPropertyID()) + c2, _ := NewCluster(NewClusterID(), "c2", NewPropertyID()) type args struct { clusters []*Cluster } @@ -43,8 +42,8 @@ func TestList_Add(t *testing.T) { } func TestList_Clusters(t *testing.T) { - c1, _ := NewCluster(id.NewClusterID(), "ccc", id.NewPropertyID()) - c2, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) + c1, _ := NewCluster(NewClusterID(), "ccc", NewPropertyID()) + c2, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) tests := []struct { name string list *ClusterList @@ -71,10 +70,10 @@ func TestList_Clusters(t *testing.T) { } func TestList_Has(t *testing.T) { - c1, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) + c1, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) type args struct { - tid id.ClusterID + tid ClusterID } tests := []struct { name string @@ -94,7 +93,7 @@ func TestList_Has(t *testing.T) { name: "not existing: should return false", list: NewClusterListFrom([]*Cluster{c1}), args: args{ - tid: id.NewClusterID(), + tid: NewClusterID(), }, want: false, }, @@ -114,12 +113,12 @@ func TestList_Has(t *testing.T) { } func TestList_Remove(t *testing.T) { - c1, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) - c2, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) - c3, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) + c1, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) + c2, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) + c3, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) type args struct { - cluster id.ClusterID + cluster ClusterID } tests := []struct { name string @@ -162,14 +161,14 @@ func TestList_Remove(t *testing.T) { } func TestClusterList_Get(t *testing.T) { - cid1 := id.NewClusterID() - cid2 := id.NewClusterID() - cid3 := id.NewClusterID() - c1, _ := NewCluster(cid1, "xxx", id.NewPropertyID()) - c2, _ := NewCluster(cid2, "zzz", id.NewPropertyID()) - c3, _ := NewCluster(cid3, "yyy", id.NewPropertyID()) + cid1 := NewClusterID() + cid2 := NewClusterID() + cid3 := NewClusterID() + c1, _ := NewCluster(cid1, "xxx", NewPropertyID()) + c2, _ := NewCluster(cid2, "zzz", NewPropertyID()) + c3, _ := NewCluster(cid3, "yyy", NewPropertyID()) type args struct { - cid id.ClusterID + cid ClusterID } tests := []struct { name string diff --git a/pkg/scene/cluster_test.go b/pkg/scene/cluster_test.go index 1df00080..01c4d825 100644 --- a/pkg/scene/cluster_test.go +++ b/pkg/scene/cluster_test.go @@ -3,19 +3,18 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestCluster_ID(t *testing.T) { - cid := id.NewClusterID() + cid := NewClusterID() clusterA := &Cluster{ id: cid, } tests := []struct { name string cluster *Cluster - want id.ClusterID + want ClusterID }{ { name: "should return cluster id", @@ -25,7 +24,7 @@ func TestCluster_ID(t *testing.T) { { name: "should return empty if cluster is nil", cluster: nil, - want: id.ClusterID{}, + want: ClusterID{}, }, } for _, tc := range tests { @@ -67,14 +66,14 @@ func TestCluster_Name(t *testing.T) { } } func TestCluster_Property(t *testing.T) { - propertyId := id.NewPropertyID() + propertyId := NewPropertyID() clusterA := &Cluster{ property: propertyId, } tests := []struct { name string cluster *Cluster - want id.PropertyID + want PropertyID }{ { name: "should return cluster property", @@ -84,7 +83,7 @@ func TestCluster_Property(t *testing.T) { { name: "should return empty cluster property", cluster: nil, - want: id.PropertyID{}, + want: PropertyID{}, }, } for _, tc := range tests { @@ -98,12 +97,12 @@ func TestCluster_Property(t *testing.T) { } func TestNew(t *testing.T) { - propertyId := id.NewPropertyID() - clusterId := id.NewClusterID() + propertyId := NewPropertyID() + clusterId := NewClusterID() type args struct { - cid id.ClusterID + cid ClusterID name string - pid id.PropertyID + pid PropertyID } tests := []struct { name string @@ -128,7 +127,7 @@ func TestNew(t *testing.T) { { name: "should return invalid id error", args: args{ - cid: id.ClusterID{}, + cid: ClusterID{}, name: "xxx", pid: propertyId, }, @@ -148,8 +147,8 @@ func TestNew(t *testing.T) { } func TestCluster_Rename(t *testing.T) { - propertyId := id.NewPropertyID() - clusterId := id.NewClusterID() + propertyId := NewPropertyID() + clusterId := NewClusterID() type args struct { name string @@ -195,12 +194,12 @@ func TestCluster_Rename(t *testing.T) { } func TestCluster_UpdateProperty(t *testing.T) { - propertyId := id.NewPropertyID() - propertyId2 := id.NewPropertyID() - clusterId := id.NewClusterID() + propertyId := NewPropertyID() + propertyId2 := NewPropertyID() + clusterId := NewClusterID() type args struct { - property id.PropertyID + property PropertyID } tests := []struct { name string diff --git a/pkg/scene/id.go b/pkg/scene/id.go new file mode 100644 index 00000000..0947fac4 --- /dev/null +++ b/pkg/scene/id.go @@ -0,0 +1,68 @@ +package scene + +import ( + "time" + + "github.com/reearth/reearth-backend/pkg/id" +) + +type ID = id.SceneID +type WidgetID = id.WidgetID +type ClusterID = id.ClusterID +type LayerID = id.LayerID +type PropertyID = id.PropertyID +type PluginID = id.PluginID +type PluginExtensionID = id.PluginExtensionID +type ProjectID = id.ProjectID +type TeamID = id.TeamID + +var NewID = id.NewSceneID +var NewWidgetID = id.NewWidgetID +var NewClusterID = id.NewClusterID +var NewLayerID = id.NewLayerID +var NewPropertyID = id.NewPropertyID +var NewPluginID = id.NewPluginID +var NewProjectID = id.NewProjectID +var NewTeamID = id.NewTeamID + +var MustID = id.MustSceneID +var MustWidgetID = id.MustWidgetID +var MustClusterID = id.MustClusterID +var MustLayerID = id.MustLayerID +var MustPropertyID = id.MustPropertyID +var MustPluginID = id.MustPluginID +var MustProjectID = id.MustProjectID +var MustTeamID = id.MustTeamID + +var IDFrom = id.SceneIDFrom +var WidgetIDFrom = id.WidgetIDFrom +var ClusterIDFrom = id.ClusterIDFrom +var LayerIDFrom = id.LayerIDFrom +var PropertyIDFrom = id.PropertyIDFrom +var PluginIDFrom = id.PluginIDFrom +var ProjectIDFrom = id.ProjectIDFrom +var TeamIDFrom = id.TeamIDFrom + +var IDFromRef = id.SceneIDFromRef +var WidgetIDFromRef = id.WidgetIDFromRef +var ClusterIDFromRef = id.ClusterIDFromRef +var LayerIDFromRef = id.LayerIDFromRef +var PropertyIDFromRef = id.PropertyIDFromRef +var PluginIDFromRef = id.PluginIDFromRef +var ProjectIDFromRef = id.ProjectIDFromRef +var TeamIDFromRef = id.TeamIDFromRef + +var IDFromRefID = id.SceneIDFromRefID +var WidgetIDFromRefID = id.WidgetIDFromRefID +var ClusterIDFromRefID = id.ClusterIDFromRefID +var LayerIDFromRefID = id.LayerIDFromRefID +var PropertyIDFromRefID = id.PropertyIDFromRefID +var ProjectIDFromRefID = id.ProjectIDFromRefID +var TeamIDFromRefID = id.TeamIDFromRefID + +var OfficialPluginID = id.OfficialPluginID +var ErrInvalidID = id.ErrInvalidID + +func createdAt(i ID) time.Time { + return id.ID(i).Timestamp() +} diff --git a/pkg/scene/plugin.go b/pkg/scene/plugin.go index c15ef56e..3228304b 100644 --- a/pkg/scene/plugin.go +++ b/pkg/scene/plugin.go @@ -1,15 +1,11 @@ package scene -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type Plugin struct { - plugin id.PluginID - property *id.PropertyID + plugin PluginID + property *PropertyID } -func NewPlugin(plugin id.PluginID, property *id.PropertyID) *Plugin { +func NewPlugin(plugin PluginID, property *PropertyID) *Plugin { if property != nil { property2 := *property property = &property2 @@ -20,11 +16,11 @@ func NewPlugin(plugin id.PluginID, property *id.PropertyID) *Plugin { } } -func (s Plugin) Plugin() id.PluginID { +func (s Plugin) Plugin() PluginID { return s.plugin } -func (s Plugin) Property() *id.PropertyID { +func (s Plugin) Property() *PropertyID { property := s.property if property != nil { property2 := *property diff --git a/pkg/scene/plugin_system.go b/pkg/scene/plugin_system.go index 169f77eb..66088177 100644 --- a/pkg/scene/plugin_system.go +++ b/pkg/scene/plugin_system.go @@ -1,9 +1,5 @@ package scene -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type PluginSystem struct { plugins []*Plugin } @@ -36,7 +32,7 @@ func (p *PluginSystem) Plugins() []*Plugin { return append([]*Plugin{}, p.plugins...) } -func (p *PluginSystem) Property(id id.PluginID) *id.PropertyID { +func (p *PluginSystem) Property(id PluginID) *PropertyID { for _, p := range p.plugins { if p.plugin.Equal(id) { return p.property.CopyRef() @@ -45,7 +41,7 @@ func (p *PluginSystem) Property(id id.PluginID) *id.PropertyID { return nil } -func (p *PluginSystem) Has(id id.PluginID) bool { +func (p *PluginSystem) Has(id PluginID) bool { for _, p2 := range p.plugins { if p2.plugin.Equal(id) { return true @@ -54,7 +50,7 @@ func (p *PluginSystem) Has(id id.PluginID) bool { return false } -func (p *PluginSystem) HasPlugin(id id.PluginID) bool { +func (p *PluginSystem) HasPlugin(id PluginID) bool { name := id.Name() for _, p2 := range p.plugins { if p2.plugin.Name() == name { @@ -65,15 +61,15 @@ func (p *PluginSystem) HasPlugin(id id.PluginID) bool { } func (p *PluginSystem) Add(sp *Plugin) { - if sp == nil || p.Has(sp.plugin) || sp.plugin.Equal(id.OfficialPluginID) { + if sp == nil || p.Has(sp.plugin) || sp.plugin.Equal(OfficialPluginID) { return } sp2 := *sp p.plugins = append(p.plugins, &sp2) } -func (p *PluginSystem) Remove(pid id.PluginID) { - if pid.Equal(id.OfficialPluginID) { +func (p *PluginSystem) Remove(pid PluginID) { + if pid.Equal(OfficialPluginID) { return } for i, p2 := range p.plugins { @@ -84,9 +80,9 @@ func (p *PluginSystem) Remove(pid id.PluginID) { } } -func (p *PluginSystem) Upgrade(pid, newID id.PluginID) { +func (p *PluginSystem) Upgrade(pid, newID PluginID) { for i, p2 := range p.plugins { - if p2.plugin.Equal(id.OfficialPluginID) { + if p2.plugin.Equal(OfficialPluginID) { continue } if p2.plugin.Equal(pid) { @@ -96,11 +92,11 @@ func (p *PluginSystem) Upgrade(pid, newID id.PluginID) { } } -func (p *PluginSystem) Properties() []id.PropertyID { +func (p *PluginSystem) Properties() []PropertyID { if p == nil { return nil } - res := make([]id.PropertyID, 0, len(p.plugins)) + res := make([]PropertyID, 0, len(p.plugins)) for _, pp := range p.plugins { if pp.property != nil { res = append(res, *pp.property) @@ -109,7 +105,7 @@ func (p *PluginSystem) Properties() []id.PropertyID { return res } -func (p *PluginSystem) Plugin(pluginID id.PluginID) *Plugin { +func (p *PluginSystem) Plugin(pluginID PluginID) *Plugin { for _, pp := range p.plugins { if pp.plugin == pluginID { return pp diff --git a/pkg/scene/plugin_system_test.go b/pkg/scene/plugin_system_test.go index e8acd920..514b7abf 100644 --- a/pkg/scene/plugin_system_test.go +++ b/pkg/scene/plugin_system_test.go @@ -3,13 +3,12 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestNewPluginSystem(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string Input []*Plugin @@ -65,13 +64,13 @@ func TestNewPluginSystem(t *testing.T) { } func TestPluginSystem_Property(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - Input id.PluginID + Input PluginID PS *PluginSystem - Expected *id.PropertyID + Expected *PropertyID }{ { Name: "property is found", @@ -88,7 +87,7 @@ func TestPluginSystem_Property(t *testing.T) { { Name: "property is not found", Input: pid, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.MustPluginID("zzz~1.1.1"), pr)}), + PS: NewPluginSystem([]*Plugin{NewPlugin(MustPluginID("zzz~1.1.1"), pr)}), Expected: nil, }, } @@ -103,11 +102,11 @@ func TestPluginSystem_Property(t *testing.T) { } func TestPluginSystem_Plugin(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - Input id.PluginID + Input PluginID PS *PluginSystem Expected *Plugin }{ @@ -120,7 +119,7 @@ func TestPluginSystem_Plugin(t *testing.T) { { Name: "plugin is not found", Input: pid, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.MustPluginID("zzz~1.1.1"), pr)}), + PS: NewPluginSystem([]*Plugin{NewPlugin(MustPluginID("zzz~1.1.1"), pr)}), Expected: nil, }, } @@ -135,12 +134,12 @@ func TestPluginSystem_Plugin(t *testing.T) { } func TestPluginSystem_Properties(t *testing.T) { - pr := id.NewPropertyID().Ref() - pr2 := id.NewPropertyID().Ref() + pr := NewPropertyID().Ref() + pr2 := NewPropertyID().Ref() testCases := []struct { Name string PS *PluginSystem - Expected []id.PropertyID + Expected []PropertyID }{ { Name: "pluginSystem is nil", @@ -150,10 +149,10 @@ func TestPluginSystem_Properties(t *testing.T) { { Name: "get properties", PS: NewPluginSystem([]*Plugin{ - NewPlugin(id.MustPluginID("zzz~1.1.1"), pr), - NewPlugin(id.MustPluginID("xxx~1.1.1"), pr2), + NewPlugin(MustPluginID("zzz~1.1.1"), pr), + NewPlugin(MustPluginID("xxx~1.1.1"), pr2), }), - Expected: []id.PropertyID{*pr, *pr2}, + Expected: []PropertyID{*pr, *pr2}, }, } for _, tc := range testCases { @@ -167,11 +166,11 @@ func TestPluginSystem_Properties(t *testing.T) { } func TestPluginSystem_Has(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - Input id.PluginID + Input PluginID PS *PluginSystem Expected bool }{ @@ -184,7 +183,7 @@ func TestPluginSystem_Has(t *testing.T) { { Name: "property is not found", Input: pid, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.MustPluginID("zzz~1.1.1"), pr)}), + PS: NewPluginSystem([]*Plugin{NewPlugin(MustPluginID("zzz~1.1.1"), pr)}), Expected: false, }, } @@ -199,11 +198,11 @@ func TestPluginSystem_Has(t *testing.T) { } func TestPluginSystem_HasPlugin(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - Input id.PluginID + Input PluginID PS *PluginSystem Expected bool }{ @@ -216,7 +215,7 @@ func TestPluginSystem_HasPlugin(t *testing.T) { { Name: "property is not found", Input: pid, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.MustPluginID("zzz~1.1.1"), pr)}), + PS: NewPluginSystem([]*Plugin{NewPlugin(MustPluginID("zzz~1.1.1"), pr)}), Expected: false, }, } @@ -231,8 +230,8 @@ func TestPluginSystem_HasPlugin(t *testing.T) { } func TestPluginSystem_Add(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string Input *Plugin @@ -252,7 +251,7 @@ func TestPluginSystem_Add(t *testing.T) { }, { Name: "add official plugin", - Input: NewPlugin(id.OfficialPluginID, pr), + Input: NewPlugin(OfficialPluginID, pr), PS: NewPluginSystem([]*Plugin{NewPlugin(pid, pr)}), Expected: NewPluginSystem([]*Plugin{NewPlugin(pid, pr)}), }, @@ -274,18 +273,18 @@ func TestPluginSystem_Add(t *testing.T) { } func TestPluginSystem_Remove(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - Input id.PluginID + Input PluginID PS, Expected *PluginSystem }{ { Name: "remove official plugin", - Input: id.OfficialPluginID, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.OfficialPluginID, pr)}), - Expected: NewPluginSystem([]*Plugin{NewPlugin(id.OfficialPluginID, pr)}), + Input: OfficialPluginID, + PS: NewPluginSystem([]*Plugin{NewPlugin(OfficialPluginID, pr)}), + Expected: NewPluginSystem([]*Plugin{NewPlugin(OfficialPluginID, pr)}), }, { Name: "remove a plugin", @@ -305,19 +304,19 @@ func TestPluginSystem_Remove(t *testing.T) { } func TestPluginSystem_Upgrade(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - nid := id.MustPluginID("zzz~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + nid := MustPluginID("zzz~1.1.1") + pr := NewPropertyID().Ref() testCases := []struct { Name string - PID, NewID id.PluginID + PID, NewID PluginID PS, Expected *PluginSystem }{ { Name: "upgrade official plugin", - PID: id.OfficialPluginID, - PS: NewPluginSystem([]*Plugin{NewPlugin(id.OfficialPluginID, pr)}), - Expected: NewPluginSystem([]*Plugin{NewPlugin(id.OfficialPluginID, pr)}), + PID: OfficialPluginID, + PS: NewPluginSystem([]*Plugin{NewPlugin(OfficialPluginID, pr)}), + Expected: NewPluginSystem([]*Plugin{NewPlugin(OfficialPluginID, pr)}), }, { Name: "upgrade a plugin", diff --git a/pkg/scene/plugin_test.go b/pkg/scene/plugin_test.go index fa35ca27..bce10b3c 100644 --- a/pkg/scene/plugin_test.go +++ b/pkg/scene/plugin_test.go @@ -3,13 +3,12 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestPlugin(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID().Ref() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID().Ref() res := NewPlugin(pid, pr) p := Plugin{ plugin: pid, diff --git a/pkg/scene/scene.go b/pkg/scene/scene.go index 70898068..4f371c30 100644 --- a/pkg/scene/scene.go +++ b/pkg/scene/scene.go @@ -3,28 +3,26 @@ package scene import ( "errors" "time" - - "github.com/reearth/reearth-backend/pkg/id" ) var ErrSceneIsLocked error = errors.New("scene is locked") type Scene struct { - id id.SceneID - project id.ProjectID - team id.TeamID - rootLayer id.LayerID + id ID + project ProjectID + team TeamID + rootLayer LayerID widgetSystem *WidgetSystem widgetAlignSystem *WidgetAlignSystem pluginSystem *PluginSystem updatedAt time.Time - property id.PropertyID + property PropertyID clusters *ClusterList } -func (s *Scene) ID() id.SceneID { +func (s *Scene) ID() ID { if s == nil { - return id.SceneID{} + return ID{} } return s.id } @@ -33,33 +31,33 @@ func (s *Scene) CreatedAt() time.Time { if s == nil { return time.Time{} } - return id.ID(s.id).Timestamp() + return createdAt(s.id) } -func (s *Scene) Project() id.ProjectID { +func (s *Scene) Project() ProjectID { if s == nil { - return id.ProjectID{} + return ProjectID{} } return s.project } -func (s *Scene) Team() id.TeamID { +func (s *Scene) Team() TeamID { if s == nil { - return id.TeamID{} + return TeamID{} } return s.team } -func (s *Scene) Property() id.PropertyID { +func (s *Scene) Property() PropertyID { if s == nil { - return id.PropertyID{} + return PropertyID{} } return s.property } -func (s *Scene) RootLayer() id.LayerID { +func (s *Scene) RootLayer() LayerID { if s == nil { - return id.LayerID{} + return LayerID{} } return s.rootLayer } @@ -99,7 +97,7 @@ func (s *Scene) SetUpdatedAt(updatedAt time.Time) { s.updatedAt = updatedAt } -func (s *Scene) IsTeamIncluded(teams []id.TeamID) bool { +func (s *Scene) IsTeamIncluded(teams []TeamID) bool { if s == nil || teams == nil { return false } @@ -111,11 +109,11 @@ func (s *Scene) IsTeamIncluded(teams []id.TeamID) bool { return false } -func (s *Scene) Properties() []id.PropertyID { +func (s *Scene) Properties() []PropertyID { if s == nil { return nil } - ids := []id.PropertyID{s.property} + ids := []PropertyID{s.property} ids = append(ids, s.pluginSystem.Properties()...) ids = append(ids, s.widgetSystem.Properties()...) ids = append(ids, s.clusters.Properties()...) diff --git a/pkg/scene/scene_test.go b/pkg/scene/scene_test.go index f72a0ea2..04f2abd2 100644 --- a/pkg/scene/scene_test.go +++ b/pkg/scene/scene_test.go @@ -4,40 +4,39 @@ import ( "testing" "time" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestScene_IsTeamIncluded(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() testCases := []struct { Name string - Teams []id.TeamID + Teams []TeamID S *Scene Expected bool }{ { Name: "nil scene", - Teams: []id.TeamID{id.NewTeamID()}, + Teams: []TeamID{NewTeamID()}, S: nil, Expected: false, }, { Name: "nil teams", Teams: nil, - S: New().NewID().Team(id.NewTeamID()).RootLayer(id.NewLayerID()).MustBuild(), + S: New().NewID().Team(NewTeamID()).RootLayer(NewLayerID()).MustBuild(), Expected: false, }, { Name: "teams exist", - Teams: []id.TeamID{tid}, - S: New().NewID().Team(tid).RootLayer(id.NewLayerID()).MustBuild(), + Teams: []TeamID{tid}, + S: New().NewID().Team(tid).RootLayer(NewLayerID()).MustBuild(), Expected: true, }, { Name: "teams not exist", - Teams: []id.TeamID{tid}, - S: New().NewID().Team(id.NewTeamID()).RootLayer(id.NewLayerID()).MustBuild(), + Teams: []TeamID{tid}, + S: New().NewID().Team(NewTeamID()).RootLayer(NewLayerID()).MustBuild(), Expected: false, }, } @@ -52,7 +51,7 @@ func TestScene_IsTeamIncluded(t *testing.T) { } func TestScene_SetUpdatedAt(t *testing.T) { - s := New().NewID().Team(id.NewTeamID()).RootLayer(id.NewLayerID()).UpdatedAt(time.Date(1999, 1, 1, 00, 00, 1, 1, time.UTC)).MustBuild() + s := New().NewID().Team(NewTeamID()).RootLayer(NewLayerID()).UpdatedAt(time.Date(1999, 1, 1, 00, 00, 1, 1, time.UTC)).MustBuild() s.SetUpdatedAt(time.Date(2021, 1, 1, 00, 00, 1, 1, time.UTC)) assert.Equal(t, time.Date(2021, 1, 1, 00, 00, 1, 1, time.UTC), s.UpdatedAt()) s = nil @@ -61,24 +60,24 @@ func TestScene_SetUpdatedAt(t *testing.T) { } func TestScene_Properties(t *testing.T) { - pid1 := id.NewPropertyID() - pid2 := id.NewPropertyID() + pid1 := NewPropertyID() + pid2 := NewPropertyID() s := New(). NewID(). - Team(id.NewTeamID()). - RootLayer(id.NewLayerID()). + Team(NewTeamID()). + RootLayer(NewLayerID()). Property(pid1). WidgetSystem( NewWidgetSystem( []*Widget{ - MustNewWidget(id.NewWidgetID(), id.MustPluginID("xxx~1.1.1"), "eee", pid2, true, false), + MustNewWidget(NewWidgetID(), MustPluginID("xxx~1.1.1"), "eee", pid2, true, false), }, ), ). WidgetAlignSystem(NewWidgetAlignSystem()). MustBuild() - assert.Equal(t, []id.PropertyID{pid1, pid2}, s.Properties()) + assert.Equal(t, []PropertyID{pid1, pid2}, s.Properties()) } func TestSceneNil(t *testing.T) { @@ -96,7 +95,7 @@ func TestSceneNil(t *testing.T) { } func TestScene_Clusters(t *testing.T) { - c1, _ := NewCluster(id.NewClusterID(), "xxx", id.NewPropertyID()) + c1, _ := NewCluster(NewClusterID(), "xxx", NewPropertyID()) tests := []struct { name string diff --git a/pkg/scene/sceneops/dataset_migrator.go b/pkg/scene/sceneops/dataset_migrator.go index c84303b9..c4902292 100644 --- a/pkg/scene/sceneops/dataset_migrator.go +++ b/pkg/scene/sceneops/dataset_migrator.go @@ -5,7 +5,6 @@ import ( "github.com/reearth/reearth-backend/internal/usecase/repo" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/layer/layerops" "github.com/reearth/reearth-backend/pkg/plugin" @@ -24,9 +23,9 @@ type DatasetMigrator struct { type MigrateDatasetResult struct { Layers layer.Map Properties property.Map - RemovedLayers *id.LayerIDSet - RemovedDatasetSchemas []id.DatasetSchemaID - RemovedDatasets []id.DatasetID + RemovedLayers *layer.IDSet + RemovedDatasetSchemas []dataset.SchemaID + RemovedDatasets []dataset.ID } func (r MigrateDatasetResult) Merge(r2 MigrateDatasetResult) MigrateDatasetResult { @@ -38,30 +37,30 @@ func (r MigrateDatasetResult) Merge(r2 MigrateDatasetResult) MigrateDatasetResul } // NOTE: DatasetSchemaの削除には対応していない(自動的に削除されない) -func (srv DatasetMigrator) Migrate(ctx context.Context, sid id.SceneID, newdsl []*dataset.Schema, newdl dataset.List) (MigrateDatasetResult, error) { - scenes := []id.SceneID{sid} +func (srv DatasetMigrator) Migrate(ctx context.Context, sid dataset.SceneID, newdsl []*dataset.Schema, newdl dataset.List) (MigrateDatasetResult, error) { + scenes := []dataset.SceneID{sid} result := MigrateDatasetResult{} // 削除対象 - noLogerUsedDS := []id.DatasetSchemaID{} - noLogerUsedD := []id.DatasetID{} + noLogerUsedDS := []dataset.SchemaID{} + noLogerUsedD := []dataset.ID{} // 古いDatasetSchema - oldDatasetSchemaMap := map[id.DatasetSchemaID]*dataset.Schema{} + oldDatasetSchemaMap := map[dataset.SchemaID]*dataset.Schema{} // 新しいDatasetSchema - newDatasetSchemaMap := map[id.DatasetSchemaID]*dataset.Schema{} + newDatasetSchemaMap := map[dataset.SchemaID]*dataset.Schema{} // 新しいDatasetSchemaから古いDatasetSchemaIDへの対応 - datasetSchemaMapNewOld := map[id.DatasetSchemaID]id.DatasetSchemaID{} + datasetSchemaMapNewOld := map[dataset.SchemaID]dataset.SchemaID{} // 古いDatasetSchemaから新しいDatasetSchemaIDへの対応 - datasetSchemaMapOldNew := map[id.DatasetSchemaID]id.DatasetSchemaID{} + datasetSchemaMapOldNew := map[dataset.SchemaID]dataset.SchemaID{} // 古いDatasetFieldIDから新しいDatasetSchemaFieldIDへの対応 - datasetSchemaFieldIDMap := map[id.DatasetSchemaFieldID]id.DatasetSchemaFieldID{} + datasetSchemaFieldIDMap := map[dataset.FieldID]dataset.FieldID{} // 古いDatasetから新しいDatasetへの対応 - newDatasetMap := map[id.DatasetID]*dataset.Dataset{} - datasetMapOldNew := map[id.DatasetID]*dataset.Dataset{} - datasetIDMapOldNew := map[id.DatasetID]id.DatasetID{} + newDatasetMap := map[dataset.ID]*dataset.Dataset{} + datasetMapOldNew := map[dataset.ID]*dataset.Dataset{} + datasetIDMapOldNew := map[dataset.ID]dataset.ID{} // 新しいDatasetSchemaからDatasetDiffへの対応 - datasetDiffMap := map[id.DatasetSchemaID]dataset.Diff{} + datasetDiffMap := map[dataset.SchemaID]dataset.Diff{} // マップの作成 for _, newds := range newdsl { @@ -162,8 +161,8 @@ func (srv DatasetMigrator) Migrate(ctx context.Context, sid id.SceneID, newdsl [ return result, nil } -func (srv DatasetMigrator) migrateLayer(ctx context.Context, sid id.SceneID, oldds *dataset.Schema, newds *dataset.Schema, diff dataset.Diff) (MigrateDatasetResult, error) { - scenes := []id.SceneID{sid} +func (srv DatasetMigrator) migrateLayer(ctx context.Context, sid dataset.SceneID, oldds *dataset.Schema, newds *dataset.Schema, diff dataset.Diff) (MigrateDatasetResult, error) { + scenes := []dataset.SceneID{sid} // 前のデータセットスキーマに紐づいたレイヤーグループを取得 layerGroups, err := srv.LayerRepo.FindGroupBySceneAndLinkedDatasetSchema(ctx, sid, oldds.ID()) @@ -173,7 +172,7 @@ func (srv DatasetMigrator) migrateLayer(ctx context.Context, sid id.SceneID, old addedAndUpdatedLayers := layer.List{} addedProperties := property.List{} - removedLayers := []id.LayerID{} + removedLayers := []layer.ID{} for _, lg := range layerGroups { layers, err := srv.LayerRepo.FindByIDs(ctx, lg.Layers().Layers(), scenes) @@ -216,7 +215,7 @@ func (srv DatasetMigrator) migrateLayer(ctx context.Context, sid id.SceneID, old // プラグインを取得 var plug *plugin.Plugin if pid := lg.Plugin(); pid != nil { - plug2, err := srv.Plugin(ctx, []id.PluginID{*pid}, []id.SceneID{sid}) + plug2, err := srv.Plugin(ctx, []plugin.ID{*pid}, []dataset.SceneID{sid}) if err != nil || len(plug2) < 1 { return MigrateDatasetResult{}, err } @@ -266,7 +265,7 @@ func (srv DatasetMigrator) migrateLayer(ctx context.Context, sid id.SceneID, old layerGroups.ToLayerList()..., ) - set := id.NewLayerIDSet() + set := layer.NewIDSet() set.Add(removedLayers...) return MigrateDatasetResult{ diff --git a/pkg/scene/sceneops/dataset_migrator_test.go b/pkg/scene/sceneops/dataset_migrator_test.go index a601dd2c..f7ae7fda 100644 --- a/pkg/scene/sceneops/dataset_migrator_test.go +++ b/pkg/scene/sceneops/dataset_migrator_test.go @@ -1,19 +1,19 @@ package sceneops //import ( -// "github.com/reearth/reearth-backend/pkg/dataset" -// "github.com/reearth/reearth-backend/pkg/id" // "testing" +// +// "github.com/reearth/reearth-backend/pkg/dataset" //) // //func TestDatasetMigrator_Migrate(t *testing.T) { -// sid := id.NewSceneID() -// dsid:=id.NewDatasetID() -// dssid:=id.NewDatasetSchemaID() -// dssfid:=id.NewDatasetSchemaFieldID() +// sid := dataset.NewSceneID() +// dsid := dataset.NewID() +// dssid := dataset.NewSchemaID() +// dssfid := dataset.MewFieldID() // testCases := []struct { // Name string -// SID id.SceneID +// SID dataset.SceneID // NewDSL []*dataset.Schema // NewDL dataset.List // Expected MigrateDatasetResult diff --git a/pkg/scene/sceneops/plugin_installer.go b/pkg/scene/sceneops/plugin_installer.go index dfc7609b..936c8d94 100644 --- a/pkg/scene/sceneops/plugin_installer.go +++ b/pkg/scene/sceneops/plugin_installer.go @@ -3,7 +3,7 @@ package sceneops import ( "errors" - "github.com/reearth/reearth-backend/pkg/id" + "github.com/reearth/reearth-backend/pkg/scene" ) type PluginInstaller struct { @@ -12,7 +12,7 @@ type PluginInstaller struct { // PropertySchemaRepo repo.PropertySchema } -func (s PluginInstaller) InstallPluginFromRepository(pluginID id.PluginID) error { +func (s PluginInstaller) InstallPluginFromRepository(pluginID scene.PluginID) error { return errors.New("not implemented") // manifest, err := s.PluginRepositoryRepo.Manifest(pluginID) diff --git a/pkg/scene/sceneops/plugin_migrator.go b/pkg/scene/sceneops/plugin_migrator.go index 2971b996..20d4c126 100644 --- a/pkg/scene/sceneops/plugin_migrator.go +++ b/pkg/scene/sceneops/plugin_migrator.go @@ -5,7 +5,6 @@ import ( "errors" "github.com/reearth/reearth-backend/pkg/dataset" - "github.com/reearth/reearth-backend/pkg/id" "github.com/reearth/reearth-backend/pkg/layer" "github.com/reearth/reearth-backend/pkg/plugin" "github.com/reearth/reearth-backend/pkg/property" @@ -25,8 +24,8 @@ type MigratePluginsResult struct { Scene *scene.Scene Layers layer.List Properties []*property.Property - RemovedLayers []id.LayerID - RemovedProperties []id.PropertyID + RemovedLayers []layer.ID + RemovedProperties []property.ID } var ( @@ -34,7 +33,7 @@ var ( ErrInvalidPlugins error = errors.New("invalid plugins") ) -func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, oldPluginID, newPluginID id.PluginID) (MigratePluginsResult, error) { +func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, oldPluginID, newPluginID plugin.ID) (MigratePluginsResult, error) { if s == nil { return MigratePluginsResult{}, rerror.ErrInternalBy(errors.New("scene is nil")) } @@ -47,7 +46,7 @@ func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, ol return MigratePluginsResult{}, ErrPluginNotInstalled } - plugins, err := s.Plugin(ctx, []id.PluginID{oldPluginID, newPluginID}, []id.SceneID{sc.ID()}) + plugins, err := s.Plugin(ctx, []plugin.ID{oldPluginID, newPluginID}, []scene.ID{sc.ID()}) if err != nil || len(plugins) < 2 { return MigratePluginsResult{}, ErrInvalidPlugins } @@ -62,13 +61,13 @@ func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, ol } modifiedLayers := layer.List{} - removedLayers := []id.LayerID{} - propertyIDs := []id.PropertyID{} - removedPropertyIDs := []id.PropertyID{} - schemaMap := map[id.PropertySchemaID]*property.Schema{} + removedLayers := []layer.ID{} + propertyIDs := []property.ID{} + removedPropertyIDs := []property.ID{} + schemaMap := map[property.SchemaID]*property.Schema{} // プロパティスキーマの取得と、古いスキーマと新しいスキーマのマップ作成 - schemaIDs := []id.PropertySchemaID{} + schemaIDs := []property.SchemaID{} if oldPlugin.Schema() != nil { if pps := newPlugin.Schema(); pps != nil { schemaIDs = append(schemaIDs, *pps) @@ -153,7 +152,7 @@ func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, ol // 不正なInfoboxFieldの削除 if ib := ll.Infobox(); ib != nil { - removeFields := []id.InfoboxFieldID{} + removeFields := []layer.InfoboxFieldID{} for _, f := range ib.Fields() { if newPlugin.Extension(f.Extension()) == nil { removeFields = append(removeFields, f.ID()) @@ -234,8 +233,8 @@ func (s *PluginMigrator) MigratePlugins(ctx context.Context, sc *scene.Scene, ol }, nil } -func collectDatasetIDs(properties []*property.Property) []id.DatasetID { - res := []id.DatasetID{} +func collectDatasetIDs(properties []*property.Property) []property.DatasetID { + res := []property.DatasetID{} for _, p := range properties { res = append(res, p.CollectDatasets()...) } diff --git a/pkg/scene/widget.go b/pkg/scene/widget.go index e420d1aa..e52a61b5 100644 --- a/pkg/scene/widget.go +++ b/pkg/scene/widget.go @@ -1,21 +1,17 @@ package scene -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type Widget struct { - id id.WidgetID - plugin id.PluginID - extension id.PluginExtensionID - property id.PropertyID + id WidgetID + plugin PluginID + extension PluginExtensionID + property PropertyID enabled bool extended bool } -func NewWidget(wid id.WidgetID, plugin id.PluginID, extension id.PluginExtensionID, property id.PropertyID, enabled, extended bool) (*Widget, error) { +func NewWidget(wid WidgetID, plugin PluginID, extension PluginExtensionID, property PropertyID, enabled, extended bool) (*Widget, error) { if !plugin.Validate() || string(extension) == "" || property.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } return &Widget{ @@ -28,7 +24,7 @@ func NewWidget(wid id.WidgetID, plugin id.PluginID, extension id.PluginExtension }, nil } -func MustNewWidget(wid id.WidgetID, plugin id.PluginID, extension id.PluginExtensionID, property id.PropertyID, enabled bool, extended bool) *Widget { +func MustNewWidget(wid WidgetID, plugin PluginID, extension PluginExtensionID, property PropertyID, enabled bool, extended bool) *Widget { w, err := NewWidget(wid, plugin, extension, property, enabled, extended) if err != nil { panic(err) @@ -36,19 +32,19 @@ func MustNewWidget(wid id.WidgetID, plugin id.PluginID, extension id.PluginExten return w } -func (w *Widget) ID() id.WidgetID { +func (w *Widget) ID() WidgetID { return w.id } -func (w *Widget) Plugin() id.PluginID { +func (w *Widget) Plugin() PluginID { return w.plugin } -func (w *Widget) Extension() id.PluginExtensionID { +func (w *Widget) Extension() PluginExtensionID { return w.extension } -func (w *Widget) Property() id.PropertyID { +func (w *Widget) Property() PropertyID { return w.property } diff --git a/pkg/scene/widget_align_system.go b/pkg/scene/widget_align_system.go index 239ce8ba..c87ef78d 100644 --- a/pkg/scene/widget_align_system.go +++ b/pkg/scene/widget_align_system.go @@ -1,9 +1,5 @@ package scene -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type WidgetLocation struct { Zone WidgetZoneType Section WidgetSectionType @@ -57,7 +53,7 @@ func (was *WidgetAlignSystem) Zone(zone WidgetZoneType) *WidgetZone { } // Remove a widget from the align system. -func (was *WidgetAlignSystem) Remove(wid id.WidgetID) { +func (was *WidgetAlignSystem) Remove(wid WidgetID) { if was == nil { return } @@ -70,7 +66,7 @@ func (was *WidgetAlignSystem) Area(loc WidgetLocation) *WidgetArea { return was.Zone(loc.Zone).Section(loc.Section).Area(loc.Area) } -func (was *WidgetAlignSystem) Find(wid id.WidgetID) (int, WidgetLocation) { +func (was *WidgetAlignSystem) Find(wid WidgetID) (int, WidgetLocation) { if was == nil { return -1, WidgetLocation{} } @@ -93,7 +89,7 @@ func (was *WidgetAlignSystem) Find(wid id.WidgetID) (int, WidgetLocation) { return -1, WidgetLocation{} } -func (was *WidgetAlignSystem) Move(wid id.WidgetID, location WidgetLocation, index int) { +func (was *WidgetAlignSystem) Move(wid WidgetID, location WidgetLocation, index int) { if was == nil { return } diff --git a/pkg/scene/widget_align_system_test.go b/pkg/scene/widget_align_system_test.go index 81395732..b0b5ffe0 100644 --- a/pkg/scene/widget_align_system_test.go +++ b/pkg/scene/widget_align_system_test.go @@ -3,7 +3,6 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -29,15 +28,15 @@ func TestWidgetAlignSystem_Area(t *testing.T) { } func TestWidgetAlignSystem_Find(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() - wid4 := id.NewWidgetID() - wid5 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() + wid4 := NewWidgetID() + wid5 := NewWidgetID() testCases := []struct { Name string - Input id.WidgetID + Input WidgetID Expected1 int Expected2 WidgetLocation Nil bool @@ -56,7 +55,7 @@ func TestWidgetAlignSystem_Find(t *testing.T) { }, { Name: "invalid id", - Input: id.NewWidgetID(), + Input: NewWidgetID(), Expected1: -1, Expected2: WidgetLocation{}, }, @@ -82,8 +81,8 @@ func TestWidgetAlignSystem_Find(t *testing.T) { } was := NewWidgetAlignSystem() - was.Zone(WidgetZoneInner).Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]id.WidgetID{wid1, wid2, wid3}) - was.Zone(WidgetZoneOuter).Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]id.WidgetID{wid4, wid5}) + was.Zone(WidgetZoneInner).Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]WidgetID{wid1, wid2, wid3}) + was.Zone(WidgetZoneOuter).Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]WidgetID{wid4, wid5}) index, location := was.Find(tc.Input) assert.Equal(tt, tc.Expected1, index) @@ -93,38 +92,38 @@ func TestWidgetAlignSystem_Find(t *testing.T) { } func TestWidgetAlignSystem_Remove(t *testing.T) { - wid := id.NewWidgetID() + wid := NewWidgetID() testCases := []struct { Name string Zone WidgetZoneType - Input id.WidgetID - Expected []id.WidgetID + Input WidgetID + Expected []WidgetID Nil bool }{ { Name: "inner: remove a widget from widget section", Zone: WidgetZoneInner, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "inner: couldn't find widgetId", Zone: WidgetZoneInner, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "outer: remove a widget from widget section", Zone: WidgetZoneOuter, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "outer: couldn't find widgetId", Zone: WidgetZoneOuter, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "nil", @@ -153,20 +152,20 @@ func TestWidgetAlignSystem_Remove(t *testing.T) { } func TestWidgetAlignSystem_Move(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() - wid4 := id.NewWidgetID() - wid5 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() + wid4 := NewWidgetID() + wid5 := NewWidgetID() testCases := []struct { Name string - Input1 id.WidgetID + Input1 WidgetID Input2 WidgetLocation Input3 int Source WidgetLocation - ExpectedSource []id.WidgetID - ExpectedDest []id.WidgetID + ExpectedSource []WidgetID + ExpectedDest []WidgetID Nil bool }{ { @@ -183,8 +182,8 @@ func TestWidgetAlignSystem_Move(t *testing.T) { Section: WidgetSectionLeft, Area: WidgetAreaTop, }, - ExpectedSource: []id.WidgetID{wid2, wid1, wid3}, - ExpectedDest: []id.WidgetID{wid2, wid1, wid3}, + ExpectedSource: []WidgetID{wid2, wid1, wid3}, + ExpectedDest: []WidgetID{wid2, wid1, wid3}, }, { Name: "move a widget in the same area with negative index", @@ -200,8 +199,8 @@ func TestWidgetAlignSystem_Move(t *testing.T) { Section: WidgetSectionLeft, Area: WidgetAreaTop, }, - ExpectedSource: []id.WidgetID{wid2, wid3, wid1}, - ExpectedDest: []id.WidgetID{wid2, wid3, wid1}, + ExpectedSource: []WidgetID{wid2, wid3, wid1}, + ExpectedDest: []WidgetID{wid2, wid3, wid1}, }, { Name: "move a widget to a different area with positive index", @@ -217,8 +216,8 @@ func TestWidgetAlignSystem_Move(t *testing.T) { Section: WidgetSectionRight, Area: WidgetAreaTop, }, - ExpectedSource: []id.WidgetID{wid2, wid3}, - ExpectedDest: []id.WidgetID{wid4, wid1, wid5}, + ExpectedSource: []WidgetID{wid2, wid3}, + ExpectedDest: []WidgetID{wid4, wid1, wid5}, }, { Name: "move a widget to a different area with negative index", @@ -234,8 +233,8 @@ func TestWidgetAlignSystem_Move(t *testing.T) { Section: WidgetSectionCenter, Area: WidgetAreaMiddle, }, - ExpectedSource: []id.WidgetID{wid2, wid3}, - ExpectedDest: []id.WidgetID{wid4, wid5, wid1}, + ExpectedSource: []WidgetID{wid2, wid3}, + ExpectedDest: []WidgetID{wid4, wid5, wid1}, }, { Name: "nil", @@ -254,9 +253,9 @@ func TestWidgetAlignSystem_Move(t *testing.T) { } ws := NewWidgetAlignSystem() - ws.Area(tc.Source).AddAll([]id.WidgetID{wid1, wid2, wid3}) + ws.Area(tc.Source).AddAll([]WidgetID{wid1, wid2, wid3}) if tc.Source != tc.Input2 { - ws.Area(tc.Input2).AddAll([]id.WidgetID{wid4, wid5}) + ws.Area(tc.Input2).AddAll([]WidgetID{wid4, wid5}) } ws.Move(tc.Input1, tc.Input2, tc.Input3) diff --git a/pkg/scene/widget_area.go b/pkg/scene/widget_area.go index 7ded7c37..81d98f4a 100644 --- a/pkg/scene/widget_area.go +++ b/pkg/scene/widget_area.go @@ -1,10 +1,8 @@ package scene -import "github.com/reearth/reearth-backend/pkg/id" - // WidgetArea has the widgets and alignment information found in each part area of a section. type WidgetArea struct { - widgetIds []id.WidgetID + widgetIds []WidgetID align WidgetAlignType } @@ -16,7 +14,7 @@ const ( WidgetAlignEnd WidgetAlignType = "end" ) -func NewWidgetArea(widgetIds []id.WidgetID, align WidgetAlignType) *WidgetArea { +func NewWidgetArea(widgetIds []WidgetID, align WidgetAlignType) *WidgetArea { wa := &WidgetArea{} wa.AddAll(widgetIds) wa.SetAlignment(align) @@ -24,12 +22,12 @@ func NewWidgetArea(widgetIds []id.WidgetID, align WidgetAlignType) *WidgetArea { } // WidgetIds will return a slice of widget ids from a specific area. -func (a *WidgetArea) WidgetIDs() []id.WidgetID { +func (a *WidgetArea) WidgetIDs() []WidgetID { if a == nil { return nil } - return append([]id.WidgetID{}, a.widgetIds...) + return append([]WidgetID{}, a.widgetIds...) } // Alignment will return the alignment of a specific area. @@ -41,7 +39,7 @@ func (a *WidgetArea) Alignment() WidgetAlignType { return a.align } -func (a *WidgetArea) Find(wid id.WidgetID) int { +func (a *WidgetArea) Find(wid WidgetID) int { if a == nil { return -1 } @@ -54,7 +52,7 @@ func (a *WidgetArea) Find(wid id.WidgetID) int { return -1 } -func (a *WidgetArea) Add(wid id.WidgetID, index int) { +func (a *WidgetArea) Add(wid WidgetID, index int) { if a == nil || wid.Contains(a.widgetIds) { return } @@ -62,12 +60,12 @@ func (a *WidgetArea) Add(wid id.WidgetID, index int) { a.widgetIds = insertWidgetID(a.widgetIds, wid, index) } -func (a *WidgetArea) AddAll(wids []id.WidgetID) { +func (a *WidgetArea) AddAll(wids []WidgetID) { if a == nil { return } - widgetIds := make([]id.WidgetID, 0, len(wids)) + widgetIds := make([]WidgetID, 0, len(wids)) for _, w := range wids { if w.Contains(a.widgetIds) || w.Contains(widgetIds) { continue @@ -90,7 +88,7 @@ func (a *WidgetArea) SetAlignment(at WidgetAlignType) { } } -func (a *WidgetArea) Remove(wid id.WidgetID) { +func (a *WidgetArea) Remove(wid WidgetID) { if a == nil { return } @@ -113,14 +111,14 @@ func (a *WidgetArea) Move(from, to int) { } // insertWidgetID is used in moveInt to add the widgetID to a new position(index). -func insertWidgetID(array []id.WidgetID, value id.WidgetID, index int) []id.WidgetID { +func insertWidgetID(array []WidgetID, value WidgetID, index int) []WidgetID { if index < 0 { return append(array, value) } - return append(array[:index], append([]id.WidgetID{value}, array[index:]...)...) + return append(array[:index], append([]WidgetID{value}, array[index:]...)...) } // removeWidgetID is used in moveInt to remove the widgetID from original position(index). -func removeWidgetID(array []id.WidgetID, index int) []id.WidgetID { +func removeWidgetID(array []WidgetID, index int) []WidgetID { return append(array[:index], array[index+1:]...) } diff --git a/pkg/scene/widget_area_test.go b/pkg/scene/widget_area_test.go index 2c16d20a..a69bb219 100644 --- a/pkg/scene/widget_area_test.go +++ b/pkg/scene/widget_area_test.go @@ -3,37 +3,36 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestWidgetArea(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() testCases := []struct { Name string - Input1 []id.WidgetID + Input1 []WidgetID Input2 WidgetAlignType Expected *WidgetArea }{ { Name: "New widget area with proper widget ids and widget align type", - Input1: []id.WidgetID{wid1, wid2}, + Input1: []WidgetID{wid1, wid2}, Input2: WidgetAlignEnd, - Expected: &WidgetArea{widgetIds: []id.WidgetID{wid1, wid2}, align: WidgetAlignEnd}, + Expected: &WidgetArea{widgetIds: []WidgetID{wid1, wid2}, align: WidgetAlignEnd}, }, { Name: "New widget area with duplicated widget ids", - Input1: []id.WidgetID{wid1, wid1}, + Input1: []WidgetID{wid1, wid1}, Input2: WidgetAlignEnd, - Expected: &WidgetArea{widgetIds: []id.WidgetID{wid1}, align: WidgetAlignEnd}, + Expected: &WidgetArea{widgetIds: []WidgetID{wid1}, align: WidgetAlignEnd}, }, { Name: "New widget area with wrong widget align type", - Input1: []id.WidgetID{wid1, wid2}, + Input1: []WidgetID{wid1, wid2}, Input2: "wrong", - Expected: &WidgetArea{widgetIds: []id.WidgetID{wid1, wid2}, align: WidgetAlignStart}, + Expected: &WidgetArea{widgetIds: []WidgetID{wid1, wid2}, align: WidgetAlignStart}, }, } @@ -48,8 +47,8 @@ func TestWidgetArea(t *testing.T) { } func TestWidgetArea_WidgetIDs(t *testing.T) { - wid := id.NewWidgetID() - wa := NewWidgetArea([]id.WidgetID{wid}, WidgetAlignStart) + wid := NewWidgetID() + wa := NewWidgetArea([]WidgetID{wid}, WidgetAlignStart) assert.Equal(t, wa.widgetIds, wa.WidgetIDs()) assert.Nil(t, (*WidgetArea)(nil).WidgetIDs()) } @@ -61,12 +60,12 @@ func TestWidgetArea_Alignment(t *testing.T) { } func TestWidgetArea_Find(t *testing.T) { - wid := id.NewWidgetID() - wid2 := id.NewWidgetID() + wid := NewWidgetID() + wid2 := NewWidgetID() testCases := []struct { Name string - Input id.WidgetID + Input WidgetID Expected int Nil bool }{ @@ -94,7 +93,7 @@ func TestWidgetArea_Find(t *testing.T) { var wa *WidgetArea if !tc.Nil { - wa = NewWidgetArea([]id.WidgetID{wid}, WidgetAlignStart) + wa = NewWidgetArea([]WidgetID{wid}, WidgetAlignStart) } assert.Equal(tt, tc.Expected, wa.Find(tc.Input)) }) @@ -102,34 +101,34 @@ func TestWidgetArea_Find(t *testing.T) { } func TestWidgetArea_Add(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() testCases := []struct { Name string Nil bool - Input id.WidgetID + Input WidgetID Input2 int - Expected []id.WidgetID + Expected []WidgetID }{ { Name: "add a widget id", Input: wid3, Input2: -1, - Expected: []id.WidgetID{wid1, wid2, wid3}, + Expected: []WidgetID{wid1, wid2, wid3}, }, { Name: "add a widget id but already exists", Input: wid1, Input2: -1, - Expected: []id.WidgetID{wid1, wid2}, + Expected: []WidgetID{wid1, wid2}, }, { Name: "insert a widget id", Input: wid3, Input2: 1, - Expected: []id.WidgetID{wid1, wid3, wid2}, + Expected: []WidgetID{wid1, wid3, wid2}, }, { Name: "nil widget area", @@ -147,7 +146,7 @@ func TestWidgetArea_Add(t *testing.T) { return } - wa := NewWidgetArea([]id.WidgetID{wid1, wid2}, WidgetAlignStart) + wa := NewWidgetArea([]WidgetID{wid1, wid2}, WidgetAlignStart) wa.Add(tc.Input, tc.Input2) assert.Equal(tt, tc.Expected, wa.WidgetIDs()) }) @@ -155,24 +154,24 @@ func TestWidgetArea_Add(t *testing.T) { } func TestWidgetArea_AddAll(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() testCases := []struct { Name string Nil bool - Input []id.WidgetID - Expected []id.WidgetID + Input []WidgetID + Expected []WidgetID }{ { Name: "add widget ids", - Input: []id.WidgetID{wid1, wid2}, - Expected: []id.WidgetID{wid1, wid2}, + Input: []WidgetID{wid1, wid2}, + Expected: []WidgetID{wid1, wid2}, }, { Name: "add widget ids but duplicated", - Input: []id.WidgetID{wid1, wid1, wid2}, - Expected: []id.WidgetID{wid1, wid2}, + Input: []WidgetID{wid1, wid1, wid2}, + Expected: []WidgetID{wid1, wid2}, }, { Name: "nil widget area", @@ -239,22 +238,22 @@ func TestWidgetArea_SetAlignment(t *testing.T) { } func TestWidgetArea_Remove(t *testing.T) { - wid := id.NewWidgetID() + wid := NewWidgetID() testCases := []struct { Name string - Input id.WidgetID - Expected []id.WidgetID + Input WidgetID + Expected []WidgetID Nil bool }{ { Name: "Remove a widget from widget area", Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "Remove a widget from widget area that doesn't exist", - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "Return nil if no widget area", @@ -270,7 +269,7 @@ func TestWidgetArea_Remove(t *testing.T) { var wa *WidgetArea if !tc.Nil { - wa = NewWidgetArea([]id.WidgetID{wid}, "") + wa = NewWidgetArea([]WidgetID{wid}, "") } wa.Remove(tc.Input) if !tc.Nil { @@ -281,27 +280,27 @@ func TestWidgetArea_Remove(t *testing.T) { } func TestWidgetArea_Move(t *testing.T) { - wid := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() + wid := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() testCases := []struct { Name string Input1, Input2 int - Expected []id.WidgetID + Expected []WidgetID Nil bool }{ { Name: "Move widget Id", Input1: 1, Input2: 2, - Expected: []id.WidgetID{wid, wid3, wid2}, + Expected: []WidgetID{wid, wid3, wid2}, }, { Name: "Move widget Id", Input1: 2, Input2: 0, - Expected: []id.WidgetID{wid3, wid, wid2}, + Expected: []WidgetID{wid3, wid, wid2}, }, { Name: "Nil", @@ -316,7 +315,7 @@ func TestWidgetArea_Move(t *testing.T) { var wa *WidgetArea if !tc.Nil { - wa = NewWidgetArea([]id.WidgetID{wid, wid2, wid3}, "") + wa = NewWidgetArea([]WidgetID{wid, wid2, wid3}, "") } wa.Move(tc.Input1, tc.Input2) if !tc.Nil { diff --git a/pkg/scene/widget_section.go b/pkg/scene/widget_section.go index 2fbcdf48..5a602e15 100644 --- a/pkg/scene/widget_section.go +++ b/pkg/scene/widget_section.go @@ -1,7 +1,5 @@ package scene -import "github.com/reearth/reearth-backend/pkg/id" - // WidgetSection is the structure of each section of the align system. type WidgetSection struct { top *WidgetArea @@ -46,7 +44,7 @@ func (s *WidgetSection) Area(t WidgetAreaType) *WidgetArea { return nil } -func (s *WidgetSection) Find(wid id.WidgetID) (int, WidgetAreaType) { +func (s *WidgetSection) Find(wid WidgetID) (int, WidgetAreaType) { if s == nil { return -1, "" } @@ -63,7 +61,7 @@ func (s *WidgetSection) Find(wid id.WidgetID) (int, WidgetAreaType) { return -1, "" } -func (s *WidgetSection) Remove(wid id.WidgetID) { +func (s *WidgetSection) Remove(wid WidgetID) { if s == nil { return } diff --git a/pkg/scene/widget_section_test.go b/pkg/scene/widget_section_test.go index 9346a63d..e0a35c5d 100644 --- a/pkg/scene/widget_section_test.go +++ b/pkg/scene/widget_section_test.go @@ -3,7 +3,6 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -22,17 +21,17 @@ func TestWidgetSection_Area(t *testing.T) { } func TestWidgetSection_Find(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() - wid4 := id.NewWidgetID() - wid5 := id.NewWidgetID() - wid6 := id.NewWidgetID() - wid7 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() + wid4 := NewWidgetID() + wid5 := NewWidgetID() + wid6 := NewWidgetID() + wid7 := NewWidgetID() testCases := []struct { Name string - Input id.WidgetID + Input WidgetID Expected1 int Expected2 WidgetAreaType Nil bool @@ -57,7 +56,7 @@ func TestWidgetSection_Find(t *testing.T) { }, { Name: "invalid id", - Input: id.NewWidgetID(), + Input: NewWidgetID(), Expected1: -1, Expected2: "", }, @@ -83,9 +82,9 @@ func TestWidgetSection_Find(t *testing.T) { } ws := NewWidgetSection() - ws.Area(WidgetAreaTop).AddAll([]id.WidgetID{wid1, wid2, wid3}) - ws.Area(WidgetAreaMiddle).AddAll([]id.WidgetID{wid4, wid5}) - ws.Area(WidgetAreaBottom).AddAll([]id.WidgetID{wid6, wid7}) + ws.Area(WidgetAreaTop).AddAll([]WidgetID{wid1, wid2, wid3}) + ws.Area(WidgetAreaMiddle).AddAll([]WidgetID{wid4, wid5}) + ws.Area(WidgetAreaBottom).AddAll([]WidgetID{wid6, wid7}) index, area := ws.Find(tc.Input) assert.Equal(tt, tc.Expected1, index) @@ -95,50 +94,50 @@ func TestWidgetSection_Find(t *testing.T) { } func TestWidgetSection_Remove(t *testing.T) { - wid := id.NewWidgetID() + wid := NewWidgetID() testCases := []struct { Name string Area WidgetAreaType - Input id.WidgetID - Expected []id.WidgetID + Input WidgetID + Expected []WidgetID Nil bool }{ { Name: "top: remove a widget from widget section", Area: WidgetAreaTop, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "top: couldn't find widgetId", Area: WidgetAreaTop, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "middle: remove a widget from widget section", Area: WidgetAreaMiddle, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "middle: couldn't find widgetId", Area: WidgetAreaMiddle, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "bottom: remove a widget from widget section", Area: WidgetAreaBottom, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "bottom: couldn't find widgetId", Area: WidgetAreaBottom, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "nil", diff --git a/pkg/scene/widget_system.go b/pkg/scene/widget_system.go index 87a9aa24..4ea6fa77 100644 --- a/pkg/scene/widget_system.go +++ b/pkg/scene/widget_system.go @@ -2,8 +2,6 @@ package scene import ( "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( @@ -45,7 +43,7 @@ func (w *WidgetSystem) Widgets() []*Widget { return append([]*Widget{}, w.widgets...) } -func (w *WidgetSystem) Widget(wid id.WidgetID) *Widget { +func (w *WidgetSystem) Widget(wid WidgetID) *Widget { if w == nil { return nil } @@ -57,7 +55,7 @@ func (w *WidgetSystem) Widget(wid id.WidgetID) *Widget { return nil } -func (w *WidgetSystem) Has(wid id.WidgetID) bool { +func (w *WidgetSystem) Has(wid WidgetID) bool { if w == nil { return false } @@ -77,7 +75,7 @@ func (w *WidgetSystem) Add(sw *Widget) { w.widgets = append(w.widgets, &sw2) } -func (w *WidgetSystem) Remove(wid id.WidgetID) { +func (w *WidgetSystem) Remove(wid WidgetID) { if w == nil { return } @@ -89,7 +87,7 @@ func (w *WidgetSystem) Remove(wid id.WidgetID) { } } -func (w *WidgetSystem) RemoveAllByPlugin(p id.PluginID) (res []id.PropertyID) { +func (w *WidgetSystem) RemoveAllByPlugin(p PluginID) (res []PropertyID) { if w == nil { return nil } @@ -103,7 +101,7 @@ func (w *WidgetSystem) RemoveAllByPlugin(p id.PluginID) (res []id.PropertyID) { return res } -func (w *WidgetSystem) RemoveAllByExtension(p id.PluginID, e id.PluginExtensionID) (res []id.PropertyID) { +func (w *WidgetSystem) RemoveAllByExtension(p PluginID, e PluginExtensionID) (res []PropertyID) { if w == nil { return nil } @@ -117,7 +115,7 @@ func (w *WidgetSystem) RemoveAllByExtension(p id.PluginID, e id.PluginExtensionI return res } -func (w *WidgetSystem) ReplacePlugin(oldp, newp id.PluginID) { +func (w *WidgetSystem) ReplacePlugin(oldp, newp PluginID) { if w == nil || w.widgets == nil { return } @@ -128,11 +126,11 @@ func (w *WidgetSystem) ReplacePlugin(oldp, newp id.PluginID) { } } -func (w *WidgetSystem) Properties() []id.PropertyID { +func (w *WidgetSystem) Properties() []PropertyID { if w == nil { return nil } - res := make([]id.PropertyID, 0, len(w.widgets)) + res := make([]PropertyID, 0, len(w.widgets)) for _, ww := range w.widgets { res = append(res, ww.property) } diff --git a/pkg/scene/widget_system_test.go b/pkg/scene/widget_system_test.go index d28772cb..cf385dec 100644 --- a/pkg/scene/widget_system_test.go +++ b/pkg/scene/widget_system_test.go @@ -3,14 +3,13 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestNewWidgetSystem(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string Input []*Widget @@ -57,9 +56,9 @@ func TestNewWidgetSystem(t *testing.T) { } func TestWidgetSystem_Add(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string Widgets []*Widget @@ -105,15 +104,15 @@ func TestWidgetSystem_Add(t *testing.T) { } func TestWidgetSystem_Remove(t *testing.T) { - wid := id.NewWidgetID() - wid2 := id.NewWidgetID() - pid := id.MustPluginID("xxx~1.1.1") - pid2 := id.MustPluginID("xxx~1.1.2") - pr := id.NewPropertyID() + wid := NewWidgetID() + wid2 := NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pid2 := MustPluginID("xxx~1.1.2") + pr := NewPropertyID() testCases := []struct { Name string - Input id.WidgetID + Input WidgetID Nil bool }{ { @@ -145,24 +144,24 @@ func TestWidgetSystem_Remove(t *testing.T) { } func TestWidgetSystem_RemoveAllByPlugin(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pid2 := id.MustPluginID("xxx~1.1.2") - w1 := MustNewWidget(id.NewWidgetID(), pid, "e1", id.NewPropertyID(), true, false) - w2 := MustNewWidget(id.NewWidgetID(), pid, "e2", id.NewPropertyID(), true, false) - w3 := MustNewWidget(id.NewWidgetID(), pid2, "e1", id.NewPropertyID(), true, false) + pid := MustPluginID("xxx~1.1.1") + pid2 := MustPluginID("xxx~1.1.2") + w1 := MustNewWidget(NewWidgetID(), pid, "e1", NewPropertyID(), true, false) + w2 := MustNewWidget(NewWidgetID(), pid, "e2", NewPropertyID(), true, false) + w3 := MustNewWidget(NewWidgetID(), pid2, "e1", NewPropertyID(), true, false) testCases := []struct { Name string - PID id.PluginID + PID PluginID WS, Expected *WidgetSystem - ExpectedResult []id.PropertyID + ExpectedResult []PropertyID }{ { Name: "remove widgets", PID: pid, WS: NewWidgetSystem([]*Widget{w1, w2, w3}), Expected: NewWidgetSystem([]*Widget{w3}), - ExpectedResult: []id.PropertyID{w1.Property(), w2.Property()}, + ExpectedResult: []PropertyID{w1.Property(), w2.Property()}, }, { Name: "remove from nil widgetSystem", @@ -182,32 +181,32 @@ func TestWidgetSystem_RemoveAllByPlugin(t *testing.T) { } func TestWidgetSystem_RemoveAllByExtension(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pid2 := id.MustPluginID("xxx~1.1.2") - w1 := MustNewWidget(id.NewWidgetID(), pid, "e1", id.NewPropertyID(), true, false) - w2 := MustNewWidget(id.NewWidgetID(), pid, "e2", id.NewPropertyID(), true, false) - w3 := MustNewWidget(id.NewWidgetID(), pid, "e1", id.NewPropertyID(), true, false) - w4 := MustNewWidget(id.NewWidgetID(), pid2, "e1", id.NewPropertyID(), true, false) + pid := MustPluginID("xxx~1.1.1") + pid2 := MustPluginID("xxx~1.1.2") + w1 := MustNewWidget(NewWidgetID(), pid, "e1", NewPropertyID(), true, false) + w2 := MustNewWidget(NewWidgetID(), pid, "e2", NewPropertyID(), true, false) + w3 := MustNewWidget(NewWidgetID(), pid, "e1", NewPropertyID(), true, false) + w4 := MustNewWidget(NewWidgetID(), pid2, "e1", NewPropertyID(), true, false) testCases := []struct { Name string - PID id.PluginID - EID id.PluginExtensionID + PID PluginID + EID PluginExtensionID WS, Expected *WidgetSystem - ExpectedResult []id.PropertyID + ExpectedResult []PropertyID }{ { Name: "remove widgets", PID: pid, - EID: id.PluginExtensionID("e1"), + EID: PluginExtensionID("e1"), WS: NewWidgetSystem([]*Widget{w1, w2, w3, w4}), Expected: NewWidgetSystem([]*Widget{w2, w4}), - ExpectedResult: []id.PropertyID{w1.Property(), w3.Property()}, + ExpectedResult: []PropertyID{w1.Property(), w3.Property()}, }, { Name: "remove widgets from nil widget system", PID: pid, - EID: id.PluginExtensionID("e1"), + EID: PluginExtensionID("e1"), WS: nil, Expected: nil, ExpectedResult: nil, @@ -224,13 +223,13 @@ func TestWidgetSystem_RemoveAllByExtension(t *testing.T) { } func TestWidgetSystem_ReplacePlugin(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pid2 := id.MustPluginID("zzz~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pid2 := MustPluginID("zzz~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string - PID, NewID id.PluginID + PID, NewID PluginID WS, Expected *WidgetSystem }{ { @@ -263,15 +262,15 @@ func TestWidgetSystem_ReplacePlugin(t *testing.T) { } func TestWidgetSystem_Properties(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - pr2 := id.NewPropertyID() - wid := id.NewWidgetID() - wid2 := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + pr2 := NewPropertyID() + wid := NewWidgetID() + wid2 := NewWidgetID() testCases := []struct { Name string WS *WidgetSystem - Expected []id.PropertyID + Expected []PropertyID }{ { Name: "get properties", @@ -279,7 +278,7 @@ func TestWidgetSystem_Properties(t *testing.T) { MustNewWidget(wid, pid, "eee", pr, true, false), MustNewWidget(wid2, pid, "eee", pr2, true, false), }), - Expected: []id.PropertyID{pr, pr2}, + Expected: []PropertyID{pr, pr2}, }, { Name: "get properties from nil widgetSystem", @@ -298,11 +297,11 @@ func TestWidgetSystem_Properties(t *testing.T) { } func TestWidgetSystem_Widgets(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - pr2 := id.NewPropertyID() - wid := id.NewWidgetID() - wid2 := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + pr2 := NewPropertyID() + wid := NewWidgetID() + wid2 := NewWidgetID() testCases := []struct { Name string WS *WidgetSystem @@ -336,12 +335,12 @@ func TestWidgetSystem_Widgets(t *testing.T) { } func TestWidgetSystem_Widget(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string - ID id.WidgetID + ID WidgetID WS *WidgetSystem Expected *Widget }{ @@ -375,12 +374,12 @@ func TestWidgetSystem_Widget(t *testing.T) { } func TestWidgetSystem_Has(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string - ID id.WidgetID + ID WidgetID WS *WidgetSystem Expected bool }{ diff --git a/pkg/scene/widget_test.go b/pkg/scene/widget_test.go index aa34d4c0..d376d191 100644 --- a/pkg/scene/widget_test.go +++ b/pkg/scene/widget_test.go @@ -3,20 +3,19 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestNewWidget(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string - ID id.WidgetID - Plugin id.PluginID - Extension id.PluginExtensionID - Property id.PropertyID + ID WidgetID + Plugin PluginID + Extension PluginExtensionID + Property PropertyID Enabled bool Extended bool Err error @@ -39,7 +38,7 @@ func TestNewWidget(t *testing.T) { Property: pr, Enabled: true, Extended: false, - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, } @@ -63,15 +62,15 @@ func TestNewWidget(t *testing.T) { } func TestMustNewWidget(t *testing.T) { - pid := id.MustPluginID("xxx~1.1.1") - pr := id.NewPropertyID() - wid := id.NewWidgetID() + pid := MustPluginID("xxx~1.1.1") + pr := NewPropertyID() + wid := NewWidgetID() testCases := []struct { Name string - ID id.WidgetID - Plugin id.PluginID - Extension id.PluginExtensionID - Property id.PropertyID + ID WidgetID + Plugin PluginID + Extension PluginExtensionID + Property PropertyID Enabled bool Extended bool Err error @@ -94,7 +93,7 @@ func TestMustNewWidget(t *testing.T) { Property: pr, Enabled: true, Extended: false, - Err: id.ErrInvalidID, + Err: ErrInvalidID, }, } @@ -121,13 +120,13 @@ func TestMustNewWidget(t *testing.T) { } func TestWidget_SetEnabled(t *testing.T) { - res := MustNewWidget(id.NewWidgetID(), id.MustPluginID("xxx~1.1.1"), "eee", id.NewPropertyID(), false, false) + res := MustNewWidget(NewWidgetID(), MustPluginID("xxx~1.1.1"), "eee", NewPropertyID(), false, false) res.SetEnabled(true) assert.True(t, res.Enabled()) } func TestWidget_SetExtended(t *testing.T) { - res := MustNewWidget(id.NewWidgetID(), id.MustPluginID("xxx~1.1.1"), "eee", id.NewPropertyID(), false, false) + res := MustNewWidget(NewWidgetID(), MustPluginID("xxx~1.1.1"), "eee", NewPropertyID(), false, false) res.SetExtended(true) assert.True(t, res.Extended()) } diff --git a/pkg/scene/widget_zone.go b/pkg/scene/widget_zone.go index cbce3ded..a7936a9e 100644 --- a/pkg/scene/widget_zone.go +++ b/pkg/scene/widget_zone.go @@ -1,7 +1,5 @@ package scene -import "github.com/reearth/reearth-backend/pkg/id" - // WidgetZone is the structure of each layer (inner and outer) of the align system. type WidgetZone struct { left *WidgetSection @@ -42,7 +40,7 @@ func (wz *WidgetZone) Section(s WidgetSectionType) *WidgetSection { return nil } -func (z *WidgetZone) Remove(wid id.WidgetID) { +func (z *WidgetZone) Remove(wid WidgetID) { if z == nil { return } @@ -52,7 +50,7 @@ func (z *WidgetZone) Remove(wid id.WidgetID) { z.right.Remove(wid) } -func (z *WidgetZone) Find(wid id.WidgetID) (int, WidgetSectionType, WidgetAreaType) { +func (z *WidgetZone) Find(wid WidgetID) (int, WidgetSectionType, WidgetAreaType) { if z == nil { return -1, "", "" } diff --git a/pkg/scene/widget_zone_test.go b/pkg/scene/widget_zone_test.go index 40e21d5b..f28f0d67 100644 --- a/pkg/scene/widget_zone_test.go +++ b/pkg/scene/widget_zone_test.go @@ -3,7 +3,6 @@ package scene import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -22,17 +21,17 @@ func TestWidgetZone_Section(t *testing.T) { } func TestWidgetZone_Find(t *testing.T) { - wid1 := id.NewWidgetID() - wid2 := id.NewWidgetID() - wid3 := id.NewWidgetID() - wid4 := id.NewWidgetID() - wid5 := id.NewWidgetID() - wid6 := id.NewWidgetID() - wid7 := id.NewWidgetID() + wid1 := NewWidgetID() + wid2 := NewWidgetID() + wid3 := NewWidgetID() + wid4 := NewWidgetID() + wid5 := NewWidgetID() + wid6 := NewWidgetID() + wid7 := NewWidgetID() testCases := []struct { Name string - Input id.WidgetID + Input WidgetID Expected1 int Expected2 WidgetSectionType Expected3 WidgetAreaType @@ -61,7 +60,7 @@ func TestWidgetZone_Find(t *testing.T) { }, { Name: "invalid id", - Input: id.NewWidgetID(), + Input: NewWidgetID(), Expected1: -1, Expected2: "", Expected3: "", @@ -90,9 +89,9 @@ func TestWidgetZone_Find(t *testing.T) { } ez := NewWidgetZone() - ez.Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]id.WidgetID{wid1, wid2, wid3}) - ez.Section(WidgetSectionCenter).Area(WidgetAreaTop).AddAll([]id.WidgetID{wid4, wid5}) - ez.Section(WidgetSectionRight).Area(WidgetAreaTop).AddAll([]id.WidgetID{wid6, wid7}) + ez.Section(WidgetSectionLeft).Area(WidgetAreaTop).AddAll([]WidgetID{wid1, wid2, wid3}) + ez.Section(WidgetSectionCenter).Area(WidgetAreaTop).AddAll([]WidgetID{wid4, wid5}) + ez.Section(WidgetSectionRight).Area(WidgetAreaTop).AddAll([]WidgetID{wid6, wid7}) index, section, area := ez.Find(tc.Input) assert.Equal(tt, tc.Expected1, index) @@ -103,50 +102,50 @@ func TestWidgetZone_Find(t *testing.T) { } func TestWidgetZone_Remove(t *testing.T) { - wid := id.NewWidgetID() + wid := NewWidgetID() testCases := []struct { Name string Section WidgetSectionType - Input id.WidgetID - Expected []id.WidgetID + Input WidgetID + Expected []WidgetID Nil bool }{ { Name: "left: remove a widget from widget section", Section: WidgetSectionLeft, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "left: couldn't find widgetId", Section: WidgetSectionLeft, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "center: remove a widget from widget section", Section: WidgetSectionCenter, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "center: couldn't find widgetId", Section: WidgetSectionCenter, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "right: remove a widget from widget section", Section: WidgetSectionRight, Input: wid, - Expected: []id.WidgetID{}, + Expected: []WidgetID{}, }, { Name: "right: couldn't find widgetId", Section: WidgetSectionRight, - Input: id.NewWidgetID(), - Expected: []id.WidgetID{wid}, + Input: NewWidgetID(), + Expected: []WidgetID{wid}, }, { Name: "nil", diff --git a/pkg/tag/group_builder.go b/pkg/tag/group_builder.go index 7b948021..4774ca48 100644 --- a/pkg/tag/group_builder.go +++ b/pkg/tag/group_builder.go @@ -1,9 +1,5 @@ package tag -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type GroupBuilder struct { g *Group } @@ -22,7 +18,7 @@ func GroupFrom(t Tag) *Group { func (b *GroupBuilder) Build() (*Group, error) { if b.g.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.g.sceneId.IsNil() { return nil, ErrInvalidSceneID @@ -34,13 +30,13 @@ func (b *GroupBuilder) Build() (*Group, error) { return b.g, nil } -func (b *GroupBuilder) ID(tid id.TagID) *GroupBuilder { +func (b *GroupBuilder) ID(tid ID) *GroupBuilder { b.g.id = tid return b } func (b *GroupBuilder) NewID() *GroupBuilder { - b.g.id = id.NewTagID() + b.g.id = NewID() return b } @@ -49,7 +45,7 @@ func (b *GroupBuilder) Label(l string) *GroupBuilder { return b } -func (b *GroupBuilder) Scene(sid id.SceneID) *GroupBuilder { +func (b *GroupBuilder) Scene(sid SceneID) *GroupBuilder { b.g.sceneId = sid return b } diff --git a/pkg/tag/group_test.go b/pkg/tag/group_test.go index 160246ad..cda1ad63 100644 --- a/pkg/tag/group_test.go +++ b/pkg/tag/group_test.go @@ -3,7 +3,6 @@ package tag import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -11,20 +10,20 @@ var _ Tag = &Group{} func TestGroupBuilder_NewID(t *testing.T) { b := NewGroup().NewID() - assert.NotEqual(t, id.TagID{}, b.g.id) + assert.NotEqual(t, ID{}, b.g.id) } func TestGroupBuilder_Build(t *testing.T) { - tid := id.NewTagID() - sid := id.NewSceneID() - tags := []id.TagID{ - id.NewTagID(), - id.NewTagID(), + tid := NewID() + sid := NewSceneID() + tags := []ID{ + NewID(), + NewID(), } testCases := []struct { Name, Label string - Id id.TagID - Scene id.SceneID + Id ID + Scene SceneID Tags *List Expected struct { Group Group @@ -34,18 +33,18 @@ func TestGroupBuilder_Build(t *testing.T) { { Name: "fail: nil tag ID", Label: "xxx", - Scene: id.NewSceneID(), + Scene: NewSceneID(), Expected: struct { Group Group Error error }{ - Error: id.ErrInvalidID, + Error: ErrInvalidID, }, }, { Name: "fail: empty label", - Id: id.NewTagID(), - Scene: id.NewSceneID(), + Id: NewID(), + Scene: NewSceneID(), Expected: struct { Group Group Error error @@ -56,7 +55,7 @@ func TestGroupBuilder_Build(t *testing.T) { { Name: "fail: nil scene ID", Label: "xxx", - Id: id.NewTagID(), + Id: NewID(), Expected: struct { Group Group Error error diff --git a/pkg/tag/id.go b/pkg/tag/id.go new file mode 100644 index 00000000..2b0e5d43 --- /dev/null +++ b/pkg/tag/id.go @@ -0,0 +1,41 @@ +package tag + +import "github.com/reearth/reearth-backend/pkg/id" + +type ID = id.TagID +type SceneID = id.SceneID +type DatasetID = id.DatasetID +type DatasetSchemaID = id.DatasetSchemaID +type DatasetFieldID = id.DatasetSchemaFieldID + +var NewID = id.NewTagID +var NewSceneID = id.NewSceneID +var NewDatasetID = id.NewDatasetID +var NewDatasetSchemaID = id.NewDatasetSchemaID +var NewDatasetFieldID = id.NewDatasetSchemaFieldID + +var MustID = id.MustTagID +var MustSceneID = id.MustSceneID +var MustDatasetID = id.MustDatasetID +var MustDatasetSchemaID = id.MustDatasetSchemaID +var MustDatasetFieldID = id.MustDatasetSchemaFieldID + +var IDFrom = id.TagIDFrom +var SceneIDFrom = id.SceneIDFrom +var DatasetIDFrom = id.DatasetIDFrom +var DatasetSchemaIDFrom = id.DatasetSchemaIDFrom +var DatasetFieldIDFrom = id.DatasetSchemaFieldIDFrom + +var IDFromRef = id.TagIDFromRef +var SceneIDFromRef = id.SceneIDFromRef +var DatasetIDFromRef = id.DatasetIDFromRef +var DatasetSchemaIDFromRef = id.DatasetSchemaIDFromRef +var DatasetFieldIDFromRef = id.DatasetSchemaFieldIDFromRef + +var IDFromRefID = id.TagIDFromRefID +var SceneIDFromRefID = id.SceneIDFromRefID +var DatasetIDFromRefID = id.DatasetIDFromRefID +var DatasetSchemaIDFromRefID = id.DatasetSchemaIDFromRefID +var DatasetFieldIDFromRefID = id.DatasetSchemaFieldIDFromRefID + +var ErrInvalidID = id.ErrInvalidID diff --git a/pkg/tag/item.go b/pkg/tag/item.go index efefa027..34ad6b09 100644 --- a/pkg/tag/item.go +++ b/pkg/tag/item.go @@ -1,32 +1,30 @@ package tag -import "github.com/reearth/reearth-backend/pkg/id" - type Item struct { tag - parent *id.TagID - linkedDatasetFieldID *id.DatasetSchemaFieldID - linkedDatasetID *id.DatasetID - linkedDatasetSchemaID *id.DatasetSchemaID + parent *ID + linkedDatasetFieldID *DatasetFieldID + linkedDatasetID *DatasetID + linkedDatasetSchemaID *DatasetSchemaID } -func (i *Item) Parent() *id.TagID { +func (i *Item) Parent() *ID { return i.parent.CopyRef() } -func (i *Item) LinkedDatasetFieldID() *id.DatasetSchemaFieldID { +func (i *Item) LinkedDatasetFieldID() *DatasetFieldID { return i.linkedDatasetFieldID.CopyRef() } -func (i *Item) LinkedDatasetID() *id.DatasetID { +func (i *Item) LinkedDatasetID() *DatasetID { return i.linkedDatasetID.CopyRef() } -func (i *Item) LinkedDatasetSchemaID() *id.DatasetSchemaID { +func (i *Item) LinkedDatasetSchemaID() *DatasetSchemaID { return i.linkedDatasetSchemaID.CopyRef() } -func (i *Item) SetParent(p *id.TagID) { +func (i *Item) SetParent(p *ID) { if i == nil { return } diff --git a/pkg/tag/item_builder.go b/pkg/tag/item_builder.go index a44cbb7d..ed2a048a 100644 --- a/pkg/tag/item_builder.go +++ b/pkg/tag/item_builder.go @@ -1,7 +1,5 @@ package tag -import "github.com/reearth/reearth-backend/pkg/id" - type ItemBuilder struct { i *Item } @@ -20,7 +18,7 @@ func ItemFrom(t Tag) *Item { func (b *ItemBuilder) Build() (*Item, error) { if b.i.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.i.sceneId.IsNil() { return nil, ErrInvalidSceneID @@ -31,13 +29,13 @@ func (b *ItemBuilder) Build() (*Item, error) { return b.i, nil } -func (b *ItemBuilder) ID(tid id.TagID) *ItemBuilder { +func (b *ItemBuilder) ID(tid ID) *ItemBuilder { b.i.id = tid return b } func (b *ItemBuilder) NewID() *ItemBuilder { - b.i.id = id.NewTagID() + b.i.id = NewID() return b } @@ -46,27 +44,27 @@ func (b *ItemBuilder) Label(l string) *ItemBuilder { return b } -func (b *ItemBuilder) Scene(sid id.SceneID) *ItemBuilder { +func (b *ItemBuilder) Scene(sid SceneID) *ItemBuilder { b.i.sceneId = sid return b } -func (b *ItemBuilder) Parent(p *id.TagID) *ItemBuilder { +func (b *ItemBuilder) Parent(p *ID) *ItemBuilder { b.i.parent = p.CopyRef() return b } -func (b *ItemBuilder) LinkedDatasetFieldID(dfid *id.DatasetSchemaFieldID) *ItemBuilder { +func (b *ItemBuilder) LinkedDatasetFieldID(dfid *DatasetFieldID) *ItemBuilder { b.i.linkedDatasetFieldID = dfid return b } -func (b *ItemBuilder) LinkedDatasetID(did *id.DatasetID) *ItemBuilder { +func (b *ItemBuilder) LinkedDatasetID(did *DatasetID) *ItemBuilder { b.i.linkedDatasetID = did return b } -func (b *ItemBuilder) LinkedDatasetSchemaID(dsid *id.DatasetSchemaID) *ItemBuilder { +func (b *ItemBuilder) LinkedDatasetSchemaID(dsid *DatasetSchemaID) *ItemBuilder { b.i.linkedDatasetSchemaID = dsid return b } diff --git a/pkg/tag/item_test.go b/pkg/tag/item_test.go index a2ab775c..886f97e2 100644 --- a/pkg/tag/item_test.go +++ b/pkg/tag/item_test.go @@ -3,7 +3,6 @@ package tag import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -11,22 +10,22 @@ var _ Tag = &Item{} func TestItemBuilder_NewID(t *testing.T) { b := NewItem().NewID() - assert.NotEqual(t, id.TagID{}, b.i.id) + assert.NotEqual(t, ID{}, b.i.id) } func TestItemBuilder_Build(t *testing.T) { - tid := id.NewTagID() - sid := id.NewSceneID() - dfid := id.NewDatasetSchemaFieldID() - did := id.NewDatasetID() - dsid := id.NewDatasetSchemaID() + tid := NewID() + sid := NewSceneID() + dfid := NewDatasetFieldID() + did := NewDatasetID() + dsid := NewDatasetSchemaID() testCases := []struct { Name, Label string - Id id.TagID - Scene id.SceneID - LinkedDatasetFieldID *id.DatasetSchemaFieldID - LinkedDatasetID *id.DatasetID - LinkedDatasetSchemaID *id.DatasetSchemaID + Id ID + Scene SceneID + LinkedDatasetFieldID *DatasetFieldID + LinkedDatasetID *DatasetID + LinkedDatasetSchemaID *DatasetSchemaID Expected struct { Item Item Error error @@ -35,18 +34,18 @@ func TestItemBuilder_Build(t *testing.T) { { Name: "fail: nil tag ID", Label: "xxx", - Scene: id.NewSceneID(), + Scene: NewSceneID(), Expected: struct { Item Item Error error }{ - Error: id.ErrInvalidID, + Error: ErrInvalidID, }, }, { Name: "fail: empty label", - Id: id.NewTagID(), - Scene: id.NewSceneID(), + Id: NewID(), + Scene: NewSceneID(), Expected: struct { Item Item Error error @@ -57,7 +56,7 @@ func TestItemBuilder_Build(t *testing.T) { { Name: "fail: nil scene ID", Label: "xxx", - Id: id.NewTagID(), + Id: NewID(), Expected: struct { Item Item Error error diff --git a/pkg/tag/list.go b/pkg/tag/list.go index b0d0779b..320b4de2 100644 --- a/pkg/tag/list.go +++ b/pkg/tag/list.go @@ -1,27 +1,25 @@ package tag -import "github.com/reearth/reearth-backend/pkg/id" - type List struct { - tags []id.TagID + tags []ID } func NewList() *List { - return &List{tags: []id.TagID{}} + return &List{tags: []ID{}} } -func NewListFromTags(tags []id.TagID) *List { +func NewListFromTags(tags []ID) *List { return &List{tags: tags} } -func (tl *List) Tags() []id.TagID { +func (tl *List) Tags() []ID { if tl == nil || tl.tags == nil { return nil } - return append([]id.TagID{}, tl.tags...) + return append([]ID{}, tl.tags...) } -func (tl *List) Has(tid id.TagID) bool { +func (tl *List) Has(tid ID) bool { if tl == nil || tl.tags == nil { return false } @@ -33,14 +31,14 @@ func (tl *List) Has(tid id.TagID) bool { return false } -func (tl *List) Add(tags ...id.TagID) { +func (tl *List) Add(tags ...ID) { if tl == nil || tl.tags == nil { return } tl.tags = append(tl.tags, tags...) } -func (tl *List) Remove(tags ...id.TagID) { +func (tl *List) Remove(tags ...ID) { if tl == nil || tl.tags == nil { return } diff --git a/pkg/tag/list_test.go b/pkg/tag/list_test.go index c8e9f55d..8e2e4325 100644 --- a/pkg/tag/list_test.go +++ b/pkg/tag/list_test.go @@ -3,25 +3,24 @@ package tag import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestList_Add(t *testing.T) { - tid := id.NewTagID() + tid := NewID() var tl *List tl.Add(tid) assert.Nil(t, tl.Tags()) tl = NewList() tl.Add(tid) - expected := []id.TagID{tid} + expected := []ID{tid} assert.Equal(t, expected, tl.Tags()) } func TestList_Remove(t *testing.T) { - tid := id.NewTagID() - tid2 := id.NewTagID() - tags := []id.TagID{ + tid := NewID() + tid2 := NewID() + tags := []ID{ tid, tid2, } @@ -30,20 +29,20 @@ func TestList_Remove(t *testing.T) { assert.Nil(t, tl.Tags()) tl = NewListFromTags(tags) tl.Remove(tid2) - expected := []id.TagID{tid} + expected := []ID{tid} assert.Equal(t, expected, tl.Tags()) } func TestList_Has(t *testing.T) { - tid1 := id.NewTagID() - tid2 := id.NewTagID() - tags := []id.TagID{ + tid1 := NewID() + tid2 := NewID() + tags := []ID{ tid1, } testCases := []struct { Name string - Tags []id.TagID - TID id.TagID + Tags []ID + TID ID Expected bool }{ { diff --git a/pkg/tag/tag.go b/pkg/tag/tag.go index 797fbd9f..166c2ea7 100644 --- a/pkg/tag/tag.go +++ b/pkg/tag/tag.go @@ -2,8 +2,6 @@ package tag import ( "errors" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( @@ -12,23 +10,23 @@ var ( ) type tag struct { - id id.TagID + id ID label string - sceneId id.SceneID + sceneId SceneID } type Tag interface { - ID() id.TagID - Scene() id.SceneID + ID() ID + Scene() SceneID Label() string Rename(string) } -func (t *tag) ID() id.TagID { +func (t *tag) ID() ID { return t.id } -func (t *tag) Scene() id.SceneID { +func (t *tag) Scene() SceneID { return t.sceneId } diff --git a/pkg/user/builder.go b/pkg/user/builder.go index afdaed61..e822fb35 100644 --- a/pkg/user/builder.go +++ b/pkg/user/builder.go @@ -1,7 +1,6 @@ package user import ( - "github.com/reearth/reearth-backend/pkg/id" "golang.org/x/text/language" ) @@ -15,7 +14,7 @@ func New() *Builder { func (b *Builder) Build() (*User, error) { if b.u.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } return b.u, nil } @@ -28,13 +27,13 @@ func (b *Builder) MustBuild() *User { return r } -func (b *Builder) ID(id id.UserID) *Builder { +func (b *Builder) ID(id ID) *Builder { b.u.id = id return b } func (b *Builder) NewID() *Builder { - b.u.id = id.NewUserID() + b.u.id = NewID() return b } @@ -48,7 +47,7 @@ func (b *Builder) Email(email string) *Builder { return b } -func (b *Builder) Team(team id.TeamID) *Builder { +func (b *Builder) Team(team TeamID) *Builder { b.u.team = team return b } diff --git a/pkg/user/builder_test.go b/pkg/user/builder_test.go index 01a106e5..19394510 100644 --- a/pkg/user/builder_test.go +++ b/pkg/user/builder_test.go @@ -4,13 +4,12 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" "golang.org/x/text/language" ) func TestBuilder_ID(t *testing.T) { - uid := id.NewUserID() + uid := NewID() b := New().ID(uid).MustBuild() assert.Equal(t, uid, b.ID()) } @@ -26,7 +25,7 @@ func TestBuilder_NewID(t *testing.T) { } func TestBuilder_Team(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() b := New().NewID().Team(tid).MustBuild() assert.Equal(t, tid, b.Team()) } @@ -94,12 +93,12 @@ func TestNew(t *testing.T) { } func TestBuilder_Build(t *testing.T) { - uid := id.NewUserID() - tid := id.NewTeamID() + uid := NewID() + tid := NewTeamID() testCases := []struct { Name, UserName, Lang, Email string - UID id.UserID - TID id.TeamID + UID ID + TID TeamID Auths []Auth Expected *User err error @@ -129,7 +128,7 @@ func TestBuilder_Build(t *testing.T) { }, { Name: "failed invalid id", Expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, } for _, tc := range testCases { @@ -146,12 +145,12 @@ func TestBuilder_Build(t *testing.T) { } func TestBuilder_MustBuild(t *testing.T) { - uid := id.NewUserID() - tid := id.NewTeamID() + uid := NewID() + tid := NewTeamID() testCases := []struct { Name, UserName, Lang, Email string - UID id.UserID - TID id.TeamID + UID ID + TID TeamID Auths []Auth Expected *User err error @@ -181,7 +180,7 @@ func TestBuilder_MustBuild(t *testing.T) { }, { Name: "failed invalid id", Expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, } for _, tc := range testCases { diff --git a/pkg/user/id.go b/pkg/user/id.go new file mode 100644 index 00000000..a051c0c6 --- /dev/null +++ b/pkg/user/id.go @@ -0,0 +1,23 @@ +package user + +import "github.com/reearth/reearth-backend/pkg/id" + +type ID = id.UserID +type TeamID = id.TeamID + +var NewID = id.NewUserID +var NewTeamID = id.NewTeamID + +var MustID = id.MustUserID +var MustTeamID = id.MustTeamID + +var IDFrom = id.UserIDFrom +var TeamIDFrom = id.TeamIDFrom + +var IDFromRef = id.UserIDFromRef +var TeamIDFromRef = id.TeamIDFromRef + +var IDFromRefID = id.UserIDFromRefID +var TeamIDFromRefID = id.TeamIDFromRefID + +var ErrInvalidID = id.ErrInvalidID diff --git a/pkg/user/initializer.go b/pkg/user/initializer.go index f28c19a1..a50d7229 100644 --- a/pkg/user/initializer.go +++ b/pkg/user/initializer.go @@ -1,7 +1,6 @@ package user import ( - "github.com/reearth/reearth-backend/pkg/id" "golang.org/x/text/language" ) @@ -11,16 +10,16 @@ type InitParams struct { Auth0Sub string Lang *language.Tag Theme *Theme - UserID *id.UserID - TeamID *id.TeamID + UserID *ID + TeamID *TeamID } func Init(p InitParams) (*User, *Team, error) { if p.UserID == nil { - p.UserID = id.NewUserID().Ref() + p.UserID = NewID().Ref() } if p.TeamID == nil { - p.TeamID = id.NewTeamID().Ref() + p.TeamID = NewTeamID().Ref() } if p.Lang == nil { p.Lang = &language.Tag{} @@ -46,7 +45,7 @@ func Init(p InitParams) (*User, *Team, error) { t, err := NewTeam(). ID(*p.TeamID). Name(p.Name). - Members(map[id.UserID]Role{u.ID(): RoleOwner}). + Members(map[ID]Role{u.ID(): RoleOwner}). Personal(true). Build() if err != nil { diff --git a/pkg/user/initializer_test.go b/pkg/user/initializer_test.go index 769b87ab..9ca67263 100644 --- a/pkg/user/initializer_test.go +++ b/pkg/user/initializer_test.go @@ -4,17 +4,16 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestInit(t *testing.T) { - uid := id.NewUserID() - tid := id.NewTeamID() + uid := NewID() + tid := NewTeamID() testCases := []struct { Name, Email, Username, Sub string - UID *id.UserID - TID *id.TeamID + UID *ID + TID *TeamID ExpectedUser *User ExpectedTeam *Team Err error @@ -36,7 +35,7 @@ func TestInit(t *testing.T) { ExpectedTeam: NewTeam(). ID(tid). Name("nnn"). - Members(map[id.UserID]Role{uid: RoleOwner}). + Members(map[ID]Role{uid: RoleOwner}). Personal(true). MustBuild(), Err: nil, @@ -58,7 +57,7 @@ func TestInit(t *testing.T) { ExpectedTeam: NewTeam(). NewID(). Name("nnn"). - Members(map[id.UserID]Role{uid: RoleOwner}). + Members(map[ID]Role{uid: RoleOwner}). Personal(true). MustBuild(), Err: nil, @@ -80,7 +79,7 @@ func TestInit(t *testing.T) { ExpectedTeam: NewTeam(). ID(tid). Name("nnn"). - Members(map[id.UserID]Role{uid: RoleOwner}). + Members(map[ID]Role{uid: RoleOwner}). Personal(true). MustBuild(), Err: nil, diff --git a/pkg/user/members.go b/pkg/user/members.go index a60d80ac..e42c310e 100644 --- a/pkg/user/members.go +++ b/pkg/user/members.go @@ -3,8 +3,6 @@ package user import ( "errors" "sort" - - "github.com/reearth/reearth-backend/pkg/id" ) var ( @@ -15,22 +13,22 @@ var ( ) type Members struct { - members map[id.UserID]Role + members map[ID]Role fixed bool } func NewMembers() *Members { - m := &Members{members: map[id.UserID]Role{}} + m := &Members{members: map[ID]Role{}} return m } -func NewFixedMembers(u id.UserID) *Members { - m := &Members{members: map[id.UserID]Role{u: RoleOwner}, fixed: true} +func NewFixedMembers(u ID) *Members { + m := &Members{members: map[ID]Role{u: RoleOwner}, fixed: true} return m } -func NewMembersWith(members map[id.UserID]Role) *Members { - m := &Members{members: map[id.UserID]Role{}} +func NewMembersWith(members map[ID]Role) *Members { + m := &Members{members: map[ID]Role{}} for k, v := range members { m.members[k] = v } @@ -41,15 +39,15 @@ func CopyMembers(members *Members) *Members { return NewMembersWith(members.members) } -func (m *Members) Members() map[id.UserID]Role { - members := make(map[id.UserID]Role) +func (m *Members) Members() map[ID]Role { + members := make(map[ID]Role) for k, v := range m.members { members[k] = v } return members } -func (m *Members) ContainsUser(u id.UserID) bool { +func (m *Members) ContainsUser(u ID) bool { for k := range m.members { if k == u { return true @@ -62,11 +60,11 @@ func (m *Members) Count() int { return len(m.members) } -func (m *Members) GetRole(u id.UserID) Role { +func (m *Members) GetRole(u ID) Role { return m.members[u] } -func (m *Members) UpdateRole(u id.UserID, role Role) error { +func (m *Members) UpdateRole(u ID, role Role) error { if m.fixed { return ErrCannotModifyPersonalTeam } @@ -81,7 +79,7 @@ func (m *Members) UpdateRole(u id.UserID, role Role) error { return nil } -func (m *Members) Join(u id.UserID, role Role) error { +func (m *Members) Join(u ID, role Role) error { if m.fixed { return ErrCannotModifyPersonalTeam } @@ -95,7 +93,7 @@ func (m *Members) Join(u id.UserID, role Role) error { return nil } -func (m *Members) Leave(u id.UserID) error { +func (m *Members) Leave(u ID) error { if m.fixed { return ErrCannotModifyPersonalTeam } @@ -107,8 +105,8 @@ func (m *Members) Leave(u id.UserID) error { return nil } -func (m *Members) UsersByRole(role Role) []id.UserID { - users := make([]id.UserID, 0, len(m.members)) +func (m *Members) UsersByRole(role Role) []ID { + users := make([]ID, 0, len(m.members)) for u, r := range m.members { if r == role { users = append(users, u) @@ -122,6 +120,6 @@ func (m *Members) UsersByRole(role Role) []id.UserID { return users } -func (m *Members) IsOnlyOwner(u id.UserID) bool { +func (m *Members) IsOnlyOwner(u ID) bool { return len(m.UsersByRole(RoleOwner)) == 1 && m.members[u] == RoleOwner } diff --git a/pkg/user/members_test.go b/pkg/user/members_test.go index 6216f90a..a08902b0 100644 --- a/pkg/user/members_test.go +++ b/pkg/user/members_test.go @@ -4,7 +4,6 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) @@ -15,30 +14,30 @@ func TestNewMembers(t *testing.T) { } func TestNewMembersWith(t *testing.T) { - uid := id.NewUserID() - m := NewMembersWith(map[id.UserID]Role{uid: RoleOwner}) + uid := NewID() + m := NewMembersWith(map[ID]Role{uid: RoleOwner}) assert.NotNil(t, m) - assert.Equal(t, map[id.UserID]Role{uid: RoleOwner}, m.Members()) + assert.Equal(t, map[ID]Role{uid: RoleOwner}, m.Members()) } func TestMembers_ContainsUser(t *testing.T) { - uid1 := id.NewUserID() - uid2 := id.NewUserID() + uid1 := NewID() + uid2 := NewID() testCases := []struct { Name string M *Members - UID id.UserID + UID ID Expected bool }{ { Name: "existing user", - M: NewMembersWith(map[id.UserID]Role{uid1: RoleOwner, uid2: RoleReader}), + M: NewMembersWith(map[ID]Role{uid1: RoleOwner, uid2: RoleReader}), UID: uid1, Expected: true, }, { Name: "not existing user", - M: NewMembersWith(map[id.UserID]Role{uid2: RoleReader}), + M: NewMembersWith(map[ID]Role{uid2: RoleReader}), UID: uid1, Expected: false, }, @@ -53,40 +52,40 @@ func TestMembers_ContainsUser(t *testing.T) { } func TestCopyMembers(t *testing.T) { - uid := id.NewUserID() - m := NewMembersWith(map[id.UserID]Role{uid: RoleOwner}) + uid := NewID() + m := NewMembersWith(map[ID]Role{uid: RoleOwner}) m2 := CopyMembers(m) assert.Equal(t, m, m2) } func TestMembers_Count(t *testing.T) { - m := NewMembersWith(map[id.UserID]Role{id.NewUserID(): RoleOwner}) + m := NewMembersWith(map[ID]Role{NewID(): RoleOwner}) assert.Equal(t, len(m.Members()), m.Count()) } func TestMembers_GetRole(t *testing.T) { - uid := id.NewUserID() - m := NewMembersWith(map[id.UserID]Role{uid: RoleOwner}) + uid := NewID() + m := NewMembersWith(map[ID]Role{uid: RoleOwner}) assert.Equal(t, RoleOwner, m.GetRole(uid)) } func TestMembers_IsOnlyOwner(t *testing.T) { - uid := id.NewUserID() - m := NewMembersWith(map[id.UserID]Role{uid: RoleOwner, id.NewUserID(): RoleReader}) + uid := NewID() + m := NewMembersWith(map[ID]Role{uid: RoleOwner, NewID(): RoleReader}) assert.True(t, m.IsOnlyOwner(uid)) } func TestMembers_Leave(t *testing.T) { - uid := id.NewUserID() + uid := NewID() testCases := []struct { Name string M *Members - UID id.UserID + UID ID err error }{ { Name: "success user left", - M: NewMembersWith(map[id.UserID]Role{uid: RoleWriter, id.NewUserID(): RoleOwner}), + M: NewMembersWith(map[ID]Role{uid: RoleWriter, NewID(): RoleOwner}), UID: uid, err: nil, }, @@ -98,8 +97,8 @@ func TestMembers_Leave(t *testing.T) { }, { Name: "fail user not in the team", - M: NewMembersWith(map[id.UserID]Role{uid: RoleWriter, id.NewUserID(): RoleOwner}), - UID: id.NewUserID(), + M: NewMembersWith(map[ID]Role{uid: RoleWriter, NewID(): RoleOwner}), + UID: NewID(), err: ErrTargetUserNotInTheTeam, }, } @@ -118,23 +117,23 @@ func TestMembers_Leave(t *testing.T) { } func TestMembers_Members(t *testing.T) { - uid := id.NewUserID() - m := NewMembersWith(map[id.UserID]Role{uid: RoleOwner}) - assert.Equal(t, map[id.UserID]Role{uid: RoleOwner}, m.Members()) + uid := NewID() + m := NewMembersWith(map[ID]Role{uid: RoleOwner}) + assert.Equal(t, map[ID]Role{uid: RoleOwner}, m.Members()) } func TestMembers_UpdateRole(t *testing.T) { - uid := id.NewUserID() + uid := NewID() testCases := []struct { Name string M *Members - UID id.UserID + UID ID NewRole, Expected Role err error }{ { Name: "success role updated", - M: NewMembersWith(map[id.UserID]Role{uid: RoleWriter}), + M: NewMembersWith(map[ID]Role{uid: RoleWriter}), UID: uid, NewRole: RoleOwner, Expected: RoleOwner, @@ -142,7 +141,7 @@ func TestMembers_UpdateRole(t *testing.T) { }, { Name: "nil role", - M: NewMembersWith(map[id.UserID]Role{uid: RoleOwner}), + M: NewMembersWith(map[ID]Role{uid: RoleOwner}), UID: uid, NewRole: "", Expected: RoleOwner, @@ -157,8 +156,8 @@ func TestMembers_UpdateRole(t *testing.T) { }, { Name: "fail user not in the team", - M: NewMembersWith(map[id.UserID]Role{uid: RoleOwner}), - UID: id.NewUserID(), + M: NewMembersWith(map[ID]Role{uid: RoleOwner}), + UID: NewID(), NewRole: "", err: ErrTargetUserNotInTheTeam, }, @@ -178,18 +177,18 @@ func TestMembers_UpdateRole(t *testing.T) { } func TestMembers_Join(t *testing.T) { - uid := id.NewUserID() - uid2 := id.NewUserID() + uid := NewID() + uid2 := NewID() testCases := []struct { Name string M *Members - UID id.UserID + UID ID JoinRole, ExpectedRole Role err error }{ { Name: "success join user", - M: NewMembersWith(map[id.UserID]Role{uid: RoleWriter}), + M: NewMembersWith(map[ID]Role{uid: RoleWriter}), UID: uid2, JoinRole: "xxx", ExpectedRole: "xxx", @@ -197,7 +196,7 @@ func TestMembers_Join(t *testing.T) { }, { Name: "success join user", - M: NewMembersWith(map[id.UserID]Role{uid: RoleWriter}), + M: NewMembersWith(map[ID]Role{uid: RoleWriter}), UID: uid2, JoinRole: "", ExpectedRole: RoleReader, @@ -212,7 +211,7 @@ func TestMembers_Join(t *testing.T) { }, { Name: "fail user already joined", - M: NewMembersWith(map[id.UserID]Role{uid: RoleOwner}), + M: NewMembersWith(map[ID]Role{uid: RoleOwner}), UID: uid, JoinRole: "", err: ErrUserAlreadyJoined, @@ -234,20 +233,20 @@ func TestMembers_Join(t *testing.T) { } func TestMembers_UsersByRole(t *testing.T) { - uid := id.NewUserID() - uid2 := id.NewUserID() + uid := NewID() + uid2 := NewID() testCases := []struct { Name string M *Members Role Role - Expected []id.UserID + Expected []ID err error }{ { Name: "success join user", - M: NewMembersWith(map[id.UserID]Role{uid: "xxx", uid2: "xxx"}), + M: NewMembersWith(map[ID]Role{uid: "xxx", uid2: "xxx"}), Role: "xxx", - Expected: []id.UserID{uid2, uid}, + Expected: []ID{uid2, uid}, }, } for _, tc := range testCases { diff --git a/pkg/user/team.go b/pkg/user/team.go index 021a392f..3015389f 100644 --- a/pkg/user/team.go +++ b/pkg/user/team.go @@ -1,14 +1,12 @@ package user -import "github.com/reearth/reearth-backend/pkg/id" - type Team struct { - id id.TeamID + id TeamID name string members Members } -func (t *Team) ID() id.TeamID { +func (t *Team) ID() TeamID { return t.id } diff --git a/pkg/user/team_builder.go b/pkg/user/team_builder.go index 8f53bdcc..d6be1f42 100644 --- a/pkg/user/team_builder.go +++ b/pkg/user/team_builder.go @@ -1,12 +1,8 @@ package user -import ( - "github.com/reearth/reearth-backend/pkg/id" -) - type TeamBuilder struct { t *Team - members map[id.UserID]Role + members map[ID]Role personal bool } @@ -16,7 +12,7 @@ func NewTeam() *TeamBuilder { func (b *TeamBuilder) Build() (*Team, error) { if b.t.id.IsNil() { - return nil, id.ErrInvalidID + return nil, ErrInvalidID } if b.members == nil { b.t.members = *NewMembers() @@ -35,13 +31,13 @@ func (b *TeamBuilder) MustBuild() *Team { return r } -func (b *TeamBuilder) ID(id id.TeamID) *TeamBuilder { +func (b *TeamBuilder) ID(id TeamID) *TeamBuilder { b.t.id = id return b } func (b *TeamBuilder) NewID() *TeamBuilder { - b.t.id = id.NewTeamID() + b.t.id = NewTeamID() return b } @@ -50,7 +46,7 @@ func (b *TeamBuilder) Name(name string) *TeamBuilder { return b } -func (b *TeamBuilder) Members(members map[id.UserID]Role) *TeamBuilder { +func (b *TeamBuilder) Members(members map[ID]Role) *TeamBuilder { b.members = members return b } diff --git a/pkg/user/team_builder_test.go b/pkg/user/team_builder_test.go index eb630bec..13cf2aae 100644 --- a/pkg/user/team_builder_test.go +++ b/pkg/user/team_builder_test.go @@ -4,18 +4,17 @@ import ( "errors" "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestTeamBuilder_ID(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() tm := NewTeam().ID(tid).MustBuild() assert.Equal(t, tid, tm.ID()) } func TestTeamBuilder_Members(t *testing.T) { - m := map[id.UserID]Role{id.NewUserID(): RoleOwner} + m := map[ID]Role{NewID(): RoleOwner} tm := NewTeam().NewID().Members(m).MustBuild() assert.Equal(t, m, tm.Members().Members()) } @@ -36,12 +35,12 @@ func TestTeamBuilder_NewID(t *testing.T) { } func TestTeamBuilder_Build(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() testCases := []struct { Name, UserName string - TID id.TeamID + TID TeamID Personal bool - Members map[id.UserID]Role + Members map[ID]Role Expected *Team err error }{ @@ -50,7 +49,7 @@ func TestTeamBuilder_Build(t *testing.T) { UserName: "xxx", TID: tid, Personal: true, - Expected: NewTeam().ID(tid).Members(map[id.UserID]Role{id.NewUserID(): RoleOwner}).Personal(true).Name("xxx").MustBuild(), + Expected: NewTeam().ID(tid).Members(map[ID]Role{NewID(): RoleOwner}).Personal(true).Name("xxx").MustBuild(), err: nil, }, { Name: "success create team with nil members", @@ -62,7 +61,7 @@ func TestTeamBuilder_Build(t *testing.T) { { Name: "fail invalid id", Expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, } @@ -80,12 +79,12 @@ func TestTeamBuilder_Build(t *testing.T) { } func TestTeamBuilder_MustBuild(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() testCases := []struct { Name, UserName string - TID id.TeamID + TID TeamID Personal bool - Members map[id.UserID]Role + Members map[ID]Role Expected *Team err error }{ @@ -94,7 +93,7 @@ func TestTeamBuilder_MustBuild(t *testing.T) { UserName: "xxx", TID: tid, Personal: true, - Expected: NewTeam().ID(tid).Members(map[id.UserID]Role{id.NewUserID(): RoleOwner}).Personal(true).Name("xxx").MustBuild(), + Expected: NewTeam().ID(tid).Members(map[ID]Role{NewID(): RoleOwner}).Personal(true).Name("xxx").MustBuild(), err: nil, }, { Name: "success create team with nil members", @@ -106,7 +105,7 @@ func TestTeamBuilder_MustBuild(t *testing.T) { { Name: "fail invalid id", Expected: nil, - err: id.ErrInvalidID, + err: ErrInvalidID, }, } diff --git a/pkg/user/team_test.go b/pkg/user/team_test.go index f01e4f84..aa2bcb79 100644 --- a/pkg/user/team_test.go +++ b/pkg/user/team_test.go @@ -3,12 +3,11 @@ package user import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" ) func TestTeam_ID(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() tm := NewTeam().ID(tid).MustBuild() assert.Equal(t, tid, tm.ID()) } @@ -19,8 +18,8 @@ func TestTeam_Name(t *testing.T) { } func TestTeam_Members(t *testing.T) { - m := map[id.UserID]Role{ - id.NewUserID(): RoleOwner, + m := map[ID]Role{ + NewID(): RoleOwner, } tm := NewTeam().NewID().Members(m).MustBuild() assert.Equal(t, m, tm.Members().Members()) diff --git a/pkg/user/user.go b/pkg/user/user.go index 24359fb9..5277999d 100644 --- a/pkg/user/user.go +++ b/pkg/user/user.go @@ -1,21 +1,20 @@ package user import ( - "github.com/reearth/reearth-backend/pkg/id" "golang.org/x/text/language" ) type User struct { - id id.UserID + id ID name string email string - team id.TeamID + team TeamID auths []Auth lang language.Tag theme Theme } -func (u *User) ID() id.UserID { +func (u *User) ID() ID { return u.id } @@ -27,7 +26,7 @@ func (u *User) Email() string { return u.email } -func (u *User) Team() id.TeamID { +func (u *User) Team() TeamID { return u.team } @@ -47,7 +46,7 @@ func (u *User) UpdateEmail(email string) { u.email = email } -func (u *User) UpdateTeam(team id.TeamID) { +func (u *User) UpdateTeam(team TeamID) { u.team = team } diff --git a/pkg/user/user_test.go b/pkg/user/user_test.go index 9f782760..262bcbd7 100644 --- a/pkg/user/user_test.go +++ b/pkg/user/user_test.go @@ -3,22 +3,21 @@ package user import ( "testing" - "github.com/reearth/reearth-backend/pkg/id" "github.com/stretchr/testify/assert" "golang.org/x/text/language" ) func TestUser(t *testing.T) { - uid := id.NewUserID() - tid := id.NewTeamID() + uid := NewID() + tid := NewTeamID() testCases := []struct { Name string User *User Expected struct { - Id id.UserID + Id ID Name string Email string - Team id.TeamID + Team TeamID Auths []Auth Lang language.Tag } @@ -35,10 +34,10 @@ func TestUser(t *testing.T) { Sub: "sss", }}).MustBuild(), Expected: struct { - Id id.UserID + Id ID Name string Email string - Team id.TeamID + Team TeamID Auths []Auth Lang language.Tag }{ @@ -265,7 +264,7 @@ func TestUser_UpdateLang(t *testing.T) { } func TestUser_UpdateTeam(t *testing.T) { - tid := id.NewTeamID() + tid := NewTeamID() u := New().NewID().MustBuild() u.UpdateTeam(tid) assert.Equal(t, tid, u.Team()) From 4aaeca8a16df8e3f1e1892d66ae0421ea58c9708 Mon Sep 17 00:00:00 2001 From: rot1024 Date: Sat, 15 Jan 2022 00:53:06 +0900 Subject: [PATCH 4/5] move schemas --- .vscode/settings.json | 8 ++++---- pkg/plugin/manifest/parser.go | 2 +- pkg/plugin/manifest/parser_translation.go | 2 +- pkg/plugin/manifest/schema_gen.go | 2 +- .../plugin_manifest.json | 4 ++-- .../plugin_manifest_translation.json | 4 ++-- 6 files changed, 11 insertions(+), 11 deletions(-) rename plugin_manifest_schema.json => schemas/plugin_manifest.json (98%) rename plugin_manifest_schema_translation.json => schemas/plugin_manifest_translation.json (95%) diff --git a/.vscode/settings.json b/.vscode/settings.json index 21b1151e..7f4bc2dd 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -6,10 +6,10 @@ "yaml.validate": true, "yaml.hover": true, "yaml.schemas": { - "./plugin_manifest_schema.json": [ + "./schemas/plugin_manifest.json": [ "/pkg/builtin/manifest.yml" ], - "./plugin_manifest_schema_translation.json": [ + "./schemas/plugin_manifest_translation.json": [ "/pkg/builtin/manifest_*.yml" ] }, @@ -18,13 +18,13 @@ "fileMatch": [ "/pkg/builtin/manifest.json" ], - "url": "./plugin_manifest_schema.json" + "url": "./schemas/plugin_manifest.json" }, { "fileMatch": [ "/pkg/builtin/manifest_*.json" ], - "url": "./plugin_manifest_schema_translation.json" + "url": "./schemas/plugin_manifest_translation.json" } ] } diff --git a/pkg/plugin/manifest/parser.go b/pkg/plugin/manifest/parser.go index 83c9f1ee..e6729cb8 100644 --- a/pkg/plugin/manifest/parser.go +++ b/pkg/plugin/manifest/parser.go @@ -1,6 +1,6 @@ package manifest -//go:generate go run github.com/idubinskiy/schematyper -o schema_gen.go --package manifest ../../../plugin_manifest_schema.json +//go:generate go run github.com/idubinskiy/schematyper -o schema_gen.go --package manifest ../../../schemas/plugin_manifest.json import ( "errors" diff --git a/pkg/plugin/manifest/parser_translation.go b/pkg/plugin/manifest/parser_translation.go index 5bcb209f..0816f4e5 100644 --- a/pkg/plugin/manifest/parser_translation.go +++ b/pkg/plugin/manifest/parser_translation.go @@ -1,7 +1,7 @@ package manifest // Generating types with schema typer for translation schema is disabled because some fields are wrongly typed. -// DISABLED go:generate go run github.com/idubinskiy/schematyper -o schema_translation_gen.go --package manifest --prefix Translation ../../../plugin_manifest_schema_translation.json +// DISABLED go:generate go run github.com/idubinskiy/schematyper -o schema_translation_gen.go --package manifest --prefix Translation ../../../schemas/plugin_manifest_translation.json import ( "errors" diff --git a/pkg/plugin/manifest/schema_gen.go b/pkg/plugin/manifest/schema_gen.go index db3c4e3b..0bb41474 100644 --- a/pkg/plugin/manifest/schema_gen.go +++ b/pkg/plugin/manifest/schema_gen.go @@ -1,6 +1,6 @@ package manifest -// generated by "/var/folders/lz/nhqy382n28g31wb4f_40gbmc0000gp/T/go-build612118365/b001/exe/schematyper -o schema_gen.go --package manifest ../../../plugin_manifest_schema.json" -- DO NOT EDIT +// generated by "/var/folders/lz/nhqy382n28g31wb4f_40gbmc0000gp/T/go-build612118365/b001/exe/schematyper -o schema_gen.go --package manifest ../../../schemas/plugin_manifest.json" -- DO NOT EDIT type Choice struct { Icon string `json:"icon,omitempty"` diff --git a/plugin_manifest_schema.json b/schemas/plugin_manifest.json similarity index 98% rename from plugin_manifest_schema.json rename to schemas/plugin_manifest.json index a149f9b9..037ba972 100644 --- a/plugin_manifest_schema.json +++ b/schemas/plugin_manifest.json @@ -1,7 +1,7 @@ { - "$id": "https://app.reearth.io/schemas/plugin-manifest", + "$id": "https://reearth.io/schemas/plugin_manifest.json", "$schema": "http://json-schema.org/draft-04/schema", - "description": "Re:Earth plugin manifest schema", + "title": "Re:Earth plugin manifest", "definitions": { "id": { "$id": "#id", diff --git a/plugin_manifest_schema_translation.json b/schemas/plugin_manifest_translation.json similarity index 95% rename from plugin_manifest_schema_translation.json rename to schemas/plugin_manifest_translation.json index 2a6f20eb..30dad9d8 100644 --- a/plugin_manifest_schema_translation.json +++ b/schemas/plugin_manifest_translation.json @@ -1,7 +1,7 @@ { - "$id": "https://app.reearth.io/schemas/plugin-manifest-translation", + "$id": "https://reearth.io/schemas/plugin_manifest_translation.json", "$schema": "http://json-schema.org/draft-04/schema", - "description": "Re:Earth plugin manifest schema translation", + "title": "Re:Earth plugin manifest translation", "definitions": { "propertySchemaField": { "$id": "#propertySchemaField", From 436a119213b4aecd4adb8ebbaa37775a6b4f9826 Mon Sep 17 00:00:00 2001 From: rot1024 Date: Sat, 15 Jan 2022 01:20:41 +0900 Subject: [PATCH 5/5] remove unused file --- pkg/property/id_test.go | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 pkg/property/id_test.go diff --git a/pkg/property/id_test.go b/pkg/property/id_test.go deleted file mode 100644 index 137bb595..00000000 --- a/pkg/property/id_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package property - -func mockNewItemID(id ItemID) func() { - original := NewItemID - NewItemID = func() ItemID { return id } - return func() { - NewItemID = original - } -}