From 0a4d9113dd9cebb3b9f236a5a0c8978017ea72e2 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 8 Mar 2024 12:20:34 +0100 Subject: [PATCH 01/48] add sub cmd feature-experimentation --- .../analyze/analyze.go | 3 +- .../analyze/code-samples/README.md | 0 .../code-samples/flagship/flutter/sample.dart | 0 .../code-samples/flagship/go/SDK_V2/sample.go | 0 .../code-samples/flagship/ios/SDK_V2/sample.m | 0 .../flagship/ios/SDK_V2/sample.swift | 0 .../code-samples/flagship/ios/SDK_V3/sample.m | 0 .../flagship/ios/SDK_V3/sample.swift | 0 .../flagship/java/SDK_V2/sample.java | 0 .../flagship/java/SDK_V2/sample.kt | 0 .../flagship/java/SDK_V3/sample.java | 0 .../flagship/java/SDK_V3/sample.kt | 0 .../code-samples/flagship/js/SDK_V2/sample.js | 0 .../code-samples/flagship/js/SDK_V2/sample.ts | 0 .../code-samples/flagship/js/SDK_V3/sample.js | 0 .../code-samples/flagship/js/SDK_V3/sample.ts | 0 .../flagship/net/SDK_V1/sample.cs | 0 .../flagship/net/SDK_V1/sample.fs | 0 .../flagship/net/SDK_V1/sample.vb | 0 .../flagship/net/SDK_V3/sample.cs | 0 .../flagship/net/SDK_V3/sample.fs | 0 .../flagship/net/SDK_V3/sample.vb | 0 .../flagship/php/SDK_V1/sample.php | 0 .../flagship/php/SDK_V2/sample.php | 0 .../flagship/php/SDK_V3/sample.php | 0 .../flagship/python/SDK_V2/sample.py | 0 .../flagship/react/SDK_V2/sample.jsx | 0 .../flagship/react/SDK_V3/sample.jsx | 0 .../launchDarkly/flutter/sample-LD.dart | 0 .../code-samples/launchDarkly/go/sample-LD.go | 0 .../code-samples/launchDarkly/ios/sample-LD.m | 0 .../launchDarkly/ios/sample-LD.swift | 0 .../launchDarkly/java/sample-LD.java | 0 .../launchDarkly/java/sample-LD.kt | 0 .../code-samples/launchDarkly/js/sample-LD.js | 0 .../code-samples/launchDarkly/js/sample-LD.ts | 0 .../launchDarkly/net/sample-LD.cs | 0 .../launchDarkly/php/sample-LD.php | 0 .../launchDarkly/python/sample-LD.py | 0 .../launchDarkly/react/sample-LD.jsx | 0 .../code-samples/optimizely/go/sample-OPT.go | 0 .../code-samples/optimizely/ios/sample-OPT.m | 0 .../optimizely/ios/sample-OPT.swift | 0 .../optimizely/java/sample-OPT.java | 0 .../optimizely/java/sample-OPT.kt | 0 .../code-samples/optimizely/js/sample-OPT.js | 0 .../code-samples/optimizely/js/sample-OPT.ts | 0 .../code-samples/optimizely/net/sample-OPT.cs | 0 .../optimizely/php/sample-OPT.php | 0 .../optimizely/python/sample-OPT.py | 0 .../optimizely/react/sample-OPT.jsx | 0 .../code-samples/split/go/sample-SPLIT.go | 0 .../code-samples/split/java/sample-SPLIT.java | 0 .../code-samples/split/java/sample-SPLIT.kt | 0 .../code-samples/split/js/sample-SPLIT.js | 0 .../code-samples/split/js/sample-SPLIT.ts | 0 .../code-samples/split/net/sample-SPLIT.cs | 0 .../code-samples/split/php/sample-SPLIT.php | 0 .../code-samples/split/python/sample-SPLIT.py | 0 .../analyze/code-samples/vwo/go/sample-VWO.go | 0 .../code-samples/vwo/java/sample-VWO.java | 0 .../code-samples/vwo/java/sample-VWO.kt | 0 .../analyze/code-samples/vwo/js/sample-VWO.js | 0 .../analyze/code-samples/vwo/js/sample-VWO.ts | 0 .../code-samples/vwo/net/sample-VWO.cs | 0 .../code-samples/vwo/php/sample-VWO.php | 0 .../code-samples/vwo/python/sample-VWO.py | 0 .../analyze/flag/create.go | 0 .../analyze/flag/example-regex.json | 0 .../analyze/flag/flag.go | 0 .../analyze/flag/list.go | 0 .../launchdarkly-regexes.json | 0 .../optimizely-regexes.json | 0 .../predefined-regexes/split-regexes.json | 0 .../predefined-regexes/template-regexes.json | 0 .../flag/predefined-regexes/vwo-regexes.json | 0 .../campaign/campaign.go | 0 .../campaign/campaign_test.go | 0 .../campaign/create.go | 0 .../campaign/delete.go | 0 .../campaign/edit.go | 0 .../campaign/get.go | 0 .../campaign/list.go | 0 .../campaign/switch.go | 0 .../feature_experimentation.go | 49 +++++++++++++++++++ .../flag/create.go | 0 .../flag/delete.go | 0 .../flag/edit.go | 0 .../flag/flag.go | 0 .../flag/flag_test.go | 0 cmd/{ => feature_experimentation}/flag/get.go | 0 .../flag/list.go | 0 .../goal/create.go | 0 .../goal/delete.go | 0 .../goal/edit.go | 0 cmd/{ => feature_experimentation}/goal/get.go | 0 .../goal/goal.go | 0 .../goal/goal_test.go | 0 .../goal/list.go | 0 .../panic/panic.go | 0 .../panic/panic_test.go | 0 .../project/create.go | 0 .../project/delete.go | 0 .../project/edit.go | 0 .../project/get.go | 0 .../project/list.go | 0 .../project/project.go | 0 .../project/project_test.go | 0 .../project/switch.go | 0 .../resource/load.go | 0 .../resource/loadResource.json | 0 .../resource/resource.go | 0 .../targeting_key/create.go | 0 .../targeting_key/delete.go | 0 .../targeting_key/edit.go | 0 .../targeting_key/get.go | 0 .../targeting_key/list.go | 0 .../targeting_key/targeting_key.go | 0 .../targeting_key/targeting_key_test.go | 0 .../user/create.go | 0 .../user/delete.go | 0 .../user/edit.go | 0 .../user/list.go | 0 .../user/user.go | 0 .../user/user_test.go | 0 .../variation/create.go | 0 .../variation/delete.go | 0 .../variation/edit.go | 0 .../variation/get.go | 0 .../variation/list.go | 0 .../variation/variation.go | 0 .../variation/variation_test.go | 0 .../variation_group/create.go | 0 .../variation_group/delete.go | 0 .../variation_group/edit.go | 0 .../variation_group/get.go | 0 .../variation_group/list.go | 0 .../variation_group/variation_group.go | 0 .../variation_group/variation_group_test.go | 0 cmd/root.go | 34 ++++--------- 140 files changed, 60 insertions(+), 26 deletions(-) rename cmd/{ => feature_experimentation}/analyze/analyze.go (88%) rename cmd/{ => feature_experimentation}/analyze/code-samples/README.md (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/flutter/sample.dart (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/go/SDK_V2/sample.go (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/ios/SDK_V2/sample.m (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/ios/SDK_V2/sample.swift (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/ios/SDK_V3/sample.m (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/ios/SDK_V3/sample.swift (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/java/SDK_V2/sample.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/java/SDK_V2/sample.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/java/SDK_V3/sample.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/java/SDK_V3/sample.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/js/SDK_V2/sample.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/js/SDK_V2/sample.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/js/SDK_V3/sample.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/js/SDK_V3/sample.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V1/sample.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V1/sample.fs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V1/sample.vb (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V3/sample.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V3/sample.fs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/net/SDK_V3/sample.vb (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/php/SDK_V1/sample.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/php/SDK_V2/sample.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/php/SDK_V3/sample.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/python/SDK_V2/sample.py (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/react/SDK_V2/sample.jsx (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/flagship/react/SDK_V3/sample.jsx (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/flutter/sample-LD.dart (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/go/sample-LD.go (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/ios/sample-LD.m (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/ios/sample-LD.swift (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/java/sample-LD.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/java/sample-LD.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/js/sample-LD.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/js/sample-LD.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/net/sample-LD.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/php/sample-LD.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/python/sample-LD.py (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/launchDarkly/react/sample-LD.jsx (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/go/sample-OPT.go (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/ios/sample-OPT.m (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/ios/sample-OPT.swift (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/java/sample-OPT.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/java/sample-OPT.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/js/sample-OPT.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/js/sample-OPT.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/net/sample-OPT.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/php/sample-OPT.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/python/sample-OPT.py (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/optimizely/react/sample-OPT.jsx (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/go/sample-SPLIT.go (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/java/sample-SPLIT.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/java/sample-SPLIT.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/js/sample-SPLIT.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/js/sample-SPLIT.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/net/sample-SPLIT.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/php/sample-SPLIT.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/split/python/sample-SPLIT.py (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/go/sample-VWO.go (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/java/sample-VWO.java (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/java/sample-VWO.kt (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/js/sample-VWO.js (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/js/sample-VWO.ts (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/net/sample-VWO.cs (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/php/sample-VWO.php (100%) rename cmd/{ => feature_experimentation}/analyze/code-samples/vwo/python/sample-VWO.py (100%) rename cmd/{ => feature_experimentation}/analyze/flag/create.go (100%) rename cmd/{ => feature_experimentation}/analyze/flag/example-regex.json (100%) rename cmd/{ => feature_experimentation}/analyze/flag/flag.go (100%) rename cmd/{ => feature_experimentation}/analyze/flag/list.go (100%) rename cmd/{ => feature_experimentation}/analyze/flag/predefined-regexes/launchdarkly-regexes.json (100%) rename cmd/{ => feature_experimentation}/analyze/flag/predefined-regexes/optimizely-regexes.json (100%) rename cmd/{ => feature_experimentation}/analyze/flag/predefined-regexes/split-regexes.json (100%) rename cmd/{ => feature_experimentation}/analyze/flag/predefined-regexes/template-regexes.json (100%) rename cmd/{ => feature_experimentation}/analyze/flag/predefined-regexes/vwo-regexes.json (100%) rename cmd/{ => feature_experimentation}/campaign/campaign.go (100%) rename cmd/{ => feature_experimentation}/campaign/campaign_test.go (100%) rename cmd/{ => feature_experimentation}/campaign/create.go (100%) rename cmd/{ => feature_experimentation}/campaign/delete.go (100%) rename cmd/{ => feature_experimentation}/campaign/edit.go (100%) rename cmd/{ => feature_experimentation}/campaign/get.go (100%) rename cmd/{ => feature_experimentation}/campaign/list.go (100%) rename cmd/{ => feature_experimentation}/campaign/switch.go (100%) create mode 100644 cmd/feature_experimentation/feature_experimentation.go rename cmd/{ => feature_experimentation}/flag/create.go (100%) rename cmd/{ => feature_experimentation}/flag/delete.go (100%) rename cmd/{ => feature_experimentation}/flag/edit.go (100%) rename cmd/{ => feature_experimentation}/flag/flag.go (100%) rename cmd/{ => feature_experimentation}/flag/flag_test.go (100%) rename cmd/{ => feature_experimentation}/flag/get.go (100%) rename cmd/{ => feature_experimentation}/flag/list.go (100%) rename cmd/{ => feature_experimentation}/goal/create.go (100%) rename cmd/{ => feature_experimentation}/goal/delete.go (100%) rename cmd/{ => feature_experimentation}/goal/edit.go (100%) rename cmd/{ => feature_experimentation}/goal/get.go (100%) rename cmd/{ => feature_experimentation}/goal/goal.go (100%) rename cmd/{ => feature_experimentation}/goal/goal_test.go (100%) rename cmd/{ => feature_experimentation}/goal/list.go (100%) rename cmd/{ => feature_experimentation}/panic/panic.go (100%) rename cmd/{ => feature_experimentation}/panic/panic_test.go (100%) rename cmd/{ => feature_experimentation}/project/create.go (100%) rename cmd/{ => feature_experimentation}/project/delete.go (100%) rename cmd/{ => feature_experimentation}/project/edit.go (100%) rename cmd/{ => feature_experimentation}/project/get.go (100%) rename cmd/{ => feature_experimentation}/project/list.go (100%) rename cmd/{ => feature_experimentation}/project/project.go (100%) rename cmd/{ => feature_experimentation}/project/project_test.go (100%) rename cmd/{ => feature_experimentation}/project/switch.go (100%) rename cmd/{ => feature_experimentation}/resource/load.go (100%) rename cmd/{ => feature_experimentation}/resource/loadResource.json (100%) rename cmd/{ => feature_experimentation}/resource/resource.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/create.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/delete.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/edit.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/get.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/list.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/targeting_key.go (100%) rename cmd/{ => feature_experimentation}/targeting_key/targeting_key_test.go (100%) rename cmd/{ => feature_experimentation}/user/create.go (100%) rename cmd/{ => feature_experimentation}/user/delete.go (100%) rename cmd/{ => feature_experimentation}/user/edit.go (100%) rename cmd/{ => feature_experimentation}/user/list.go (100%) rename cmd/{ => feature_experimentation}/user/user.go (100%) rename cmd/{ => feature_experimentation}/user/user_test.go (100%) rename cmd/{ => feature_experimentation}/variation/create.go (100%) rename cmd/{ => feature_experimentation}/variation/delete.go (100%) rename cmd/{ => feature_experimentation}/variation/edit.go (100%) rename cmd/{ => feature_experimentation}/variation/get.go (100%) rename cmd/{ => feature_experimentation}/variation/list.go (100%) rename cmd/{ => feature_experimentation}/variation/variation.go (100%) rename cmd/{ => feature_experimentation}/variation/variation_test.go (100%) rename cmd/{ => feature_experimentation}/variation_group/create.go (100%) rename cmd/{ => feature_experimentation}/variation_group/delete.go (100%) rename cmd/{ => feature_experimentation}/variation_group/edit.go (100%) rename cmd/{ => feature_experimentation}/variation_group/get.go (100%) rename cmd/{ => feature_experimentation}/variation_group/list.go (100%) rename cmd/{ => feature_experimentation}/variation_group/variation_group.go (100%) rename cmd/{ => feature_experimentation}/variation_group/variation_group_test.go (100%) diff --git a/cmd/analyze/analyze.go b/cmd/feature_experimentation/analyze/analyze.go similarity index 88% rename from cmd/analyze/analyze.go rename to cmd/feature_experimentation/analyze/analyze.go index 902542f..5efa4df 100644 --- a/cmd/analyze/analyze.go +++ b/cmd/feature_experimentation/analyze/analyze.go @@ -1,12 +1,11 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package analyze import ( "github.com/flagship-io/codebase-analyzer/pkg/config" - "github.com/flagship-io/flagship/cmd/analyze/flag" + "github.com/flagship-io/flagship/cmd/feature_experimentation/flag" "github.com/spf13/cobra" ) diff --git a/cmd/analyze/code-samples/README.md b/cmd/feature_experimentation/analyze/code-samples/README.md similarity index 100% rename from cmd/analyze/code-samples/README.md rename to cmd/feature_experimentation/analyze/code-samples/README.md diff --git a/cmd/analyze/code-samples/flagship/flutter/sample.dart b/cmd/feature_experimentation/analyze/code-samples/flagship/flutter/sample.dart similarity index 100% rename from cmd/analyze/code-samples/flagship/flutter/sample.dart rename to cmd/feature_experimentation/analyze/code-samples/flagship/flutter/sample.dart diff --git a/cmd/analyze/code-samples/flagship/go/SDK_V2/sample.go b/cmd/feature_experimentation/analyze/code-samples/flagship/go/SDK_V2/sample.go similarity index 100% rename from cmd/analyze/code-samples/flagship/go/SDK_V2/sample.go rename to cmd/feature_experimentation/analyze/code-samples/flagship/go/SDK_V2/sample.go diff --git a/cmd/analyze/code-samples/flagship/ios/SDK_V2/sample.m b/cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V2/sample.m similarity index 100% rename from cmd/analyze/code-samples/flagship/ios/SDK_V2/sample.m rename to cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V2/sample.m diff --git a/cmd/analyze/code-samples/flagship/ios/SDK_V2/sample.swift b/cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V2/sample.swift similarity index 100% rename from cmd/analyze/code-samples/flagship/ios/SDK_V2/sample.swift rename to cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V2/sample.swift diff --git a/cmd/analyze/code-samples/flagship/ios/SDK_V3/sample.m b/cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V3/sample.m similarity index 100% rename from cmd/analyze/code-samples/flagship/ios/SDK_V3/sample.m rename to cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V3/sample.m diff --git a/cmd/analyze/code-samples/flagship/ios/SDK_V3/sample.swift b/cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V3/sample.swift similarity index 100% rename from cmd/analyze/code-samples/flagship/ios/SDK_V3/sample.swift rename to cmd/feature_experimentation/analyze/code-samples/flagship/ios/SDK_V3/sample.swift diff --git a/cmd/analyze/code-samples/flagship/java/SDK_V2/sample.java b/cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V2/sample.java similarity index 100% rename from cmd/analyze/code-samples/flagship/java/SDK_V2/sample.java rename to cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V2/sample.java diff --git a/cmd/analyze/code-samples/flagship/java/SDK_V2/sample.kt b/cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V2/sample.kt similarity index 100% rename from cmd/analyze/code-samples/flagship/java/SDK_V2/sample.kt rename to cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V2/sample.kt diff --git a/cmd/analyze/code-samples/flagship/java/SDK_V3/sample.java b/cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V3/sample.java similarity index 100% rename from cmd/analyze/code-samples/flagship/java/SDK_V3/sample.java rename to cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V3/sample.java diff --git a/cmd/analyze/code-samples/flagship/java/SDK_V3/sample.kt b/cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V3/sample.kt similarity index 100% rename from cmd/analyze/code-samples/flagship/java/SDK_V3/sample.kt rename to cmd/feature_experimentation/analyze/code-samples/flagship/java/SDK_V3/sample.kt diff --git a/cmd/analyze/code-samples/flagship/js/SDK_V2/sample.js b/cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V2/sample.js similarity index 100% rename from cmd/analyze/code-samples/flagship/js/SDK_V2/sample.js rename to cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V2/sample.js diff --git a/cmd/analyze/code-samples/flagship/js/SDK_V2/sample.ts b/cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V2/sample.ts similarity index 100% rename from cmd/analyze/code-samples/flagship/js/SDK_V2/sample.ts rename to cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V2/sample.ts diff --git a/cmd/analyze/code-samples/flagship/js/SDK_V3/sample.js b/cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V3/sample.js similarity index 100% rename from cmd/analyze/code-samples/flagship/js/SDK_V3/sample.js rename to cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V3/sample.js diff --git a/cmd/analyze/code-samples/flagship/js/SDK_V3/sample.ts b/cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V3/sample.ts similarity index 100% rename from cmd/analyze/code-samples/flagship/js/SDK_V3/sample.ts rename to cmd/feature_experimentation/analyze/code-samples/flagship/js/SDK_V3/sample.ts diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V1/sample.cs b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.cs similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V1/sample.cs rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.cs diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V1/sample.fs b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.fs similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V1/sample.fs rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.fs diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V1/sample.vb b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.vb similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V1/sample.vb rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V1/sample.vb diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V3/sample.cs b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.cs similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V3/sample.cs rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.cs diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V3/sample.fs b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.fs similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V3/sample.fs rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.fs diff --git a/cmd/analyze/code-samples/flagship/net/SDK_V3/sample.vb b/cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.vb similarity index 100% rename from cmd/analyze/code-samples/flagship/net/SDK_V3/sample.vb rename to cmd/feature_experimentation/analyze/code-samples/flagship/net/SDK_V3/sample.vb diff --git a/cmd/analyze/code-samples/flagship/php/SDK_V1/sample.php b/cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V1/sample.php similarity index 100% rename from cmd/analyze/code-samples/flagship/php/SDK_V1/sample.php rename to cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V1/sample.php diff --git a/cmd/analyze/code-samples/flagship/php/SDK_V2/sample.php b/cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V2/sample.php similarity index 100% rename from cmd/analyze/code-samples/flagship/php/SDK_V2/sample.php rename to cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V2/sample.php diff --git a/cmd/analyze/code-samples/flagship/php/SDK_V3/sample.php b/cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V3/sample.php similarity index 100% rename from cmd/analyze/code-samples/flagship/php/SDK_V3/sample.php rename to cmd/feature_experimentation/analyze/code-samples/flagship/php/SDK_V3/sample.php diff --git a/cmd/analyze/code-samples/flagship/python/SDK_V2/sample.py b/cmd/feature_experimentation/analyze/code-samples/flagship/python/SDK_V2/sample.py similarity index 100% rename from cmd/analyze/code-samples/flagship/python/SDK_V2/sample.py rename to cmd/feature_experimentation/analyze/code-samples/flagship/python/SDK_V2/sample.py diff --git a/cmd/analyze/code-samples/flagship/react/SDK_V2/sample.jsx b/cmd/feature_experimentation/analyze/code-samples/flagship/react/SDK_V2/sample.jsx similarity index 100% rename from cmd/analyze/code-samples/flagship/react/SDK_V2/sample.jsx rename to cmd/feature_experimentation/analyze/code-samples/flagship/react/SDK_V2/sample.jsx diff --git a/cmd/analyze/code-samples/flagship/react/SDK_V3/sample.jsx b/cmd/feature_experimentation/analyze/code-samples/flagship/react/SDK_V3/sample.jsx similarity index 100% rename from cmd/analyze/code-samples/flagship/react/SDK_V3/sample.jsx rename to cmd/feature_experimentation/analyze/code-samples/flagship/react/SDK_V3/sample.jsx diff --git a/cmd/analyze/code-samples/launchDarkly/flutter/sample-LD.dart b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/flutter/sample-LD.dart similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/flutter/sample-LD.dart rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/flutter/sample-LD.dart diff --git a/cmd/analyze/code-samples/launchDarkly/go/sample-LD.go b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/go/sample-LD.go similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/go/sample-LD.go rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/go/sample-LD.go diff --git a/cmd/analyze/code-samples/launchDarkly/ios/sample-LD.m b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/ios/sample-LD.m similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/ios/sample-LD.m rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/ios/sample-LD.m diff --git a/cmd/analyze/code-samples/launchDarkly/ios/sample-LD.swift b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/ios/sample-LD.swift similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/ios/sample-LD.swift rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/ios/sample-LD.swift diff --git a/cmd/analyze/code-samples/launchDarkly/java/sample-LD.java b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/java/sample-LD.java similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/java/sample-LD.java rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/java/sample-LD.java diff --git a/cmd/analyze/code-samples/launchDarkly/java/sample-LD.kt b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/java/sample-LD.kt similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/java/sample-LD.kt rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/java/sample-LD.kt diff --git a/cmd/analyze/code-samples/launchDarkly/js/sample-LD.js b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/js/sample-LD.js similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/js/sample-LD.js rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/js/sample-LD.js diff --git a/cmd/analyze/code-samples/launchDarkly/js/sample-LD.ts b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/js/sample-LD.ts similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/js/sample-LD.ts rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/js/sample-LD.ts diff --git a/cmd/analyze/code-samples/launchDarkly/net/sample-LD.cs b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/net/sample-LD.cs similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/net/sample-LD.cs rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/net/sample-LD.cs diff --git a/cmd/analyze/code-samples/launchDarkly/php/sample-LD.php b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/php/sample-LD.php similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/php/sample-LD.php rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/php/sample-LD.php diff --git a/cmd/analyze/code-samples/launchDarkly/python/sample-LD.py b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/python/sample-LD.py similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/python/sample-LD.py rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/python/sample-LD.py diff --git a/cmd/analyze/code-samples/launchDarkly/react/sample-LD.jsx b/cmd/feature_experimentation/analyze/code-samples/launchDarkly/react/sample-LD.jsx similarity index 100% rename from cmd/analyze/code-samples/launchDarkly/react/sample-LD.jsx rename to cmd/feature_experimentation/analyze/code-samples/launchDarkly/react/sample-LD.jsx diff --git a/cmd/analyze/code-samples/optimizely/go/sample-OPT.go b/cmd/feature_experimentation/analyze/code-samples/optimizely/go/sample-OPT.go similarity index 100% rename from cmd/analyze/code-samples/optimizely/go/sample-OPT.go rename to cmd/feature_experimentation/analyze/code-samples/optimizely/go/sample-OPT.go diff --git a/cmd/analyze/code-samples/optimizely/ios/sample-OPT.m b/cmd/feature_experimentation/analyze/code-samples/optimizely/ios/sample-OPT.m similarity index 100% rename from cmd/analyze/code-samples/optimizely/ios/sample-OPT.m rename to cmd/feature_experimentation/analyze/code-samples/optimizely/ios/sample-OPT.m diff --git a/cmd/analyze/code-samples/optimizely/ios/sample-OPT.swift b/cmd/feature_experimentation/analyze/code-samples/optimizely/ios/sample-OPT.swift similarity index 100% rename from cmd/analyze/code-samples/optimizely/ios/sample-OPT.swift rename to cmd/feature_experimentation/analyze/code-samples/optimizely/ios/sample-OPT.swift diff --git a/cmd/analyze/code-samples/optimizely/java/sample-OPT.java b/cmd/feature_experimentation/analyze/code-samples/optimizely/java/sample-OPT.java similarity index 100% rename from cmd/analyze/code-samples/optimizely/java/sample-OPT.java rename to cmd/feature_experimentation/analyze/code-samples/optimizely/java/sample-OPT.java diff --git a/cmd/analyze/code-samples/optimizely/java/sample-OPT.kt b/cmd/feature_experimentation/analyze/code-samples/optimizely/java/sample-OPT.kt similarity index 100% rename from cmd/analyze/code-samples/optimizely/java/sample-OPT.kt rename to cmd/feature_experimentation/analyze/code-samples/optimizely/java/sample-OPT.kt diff --git a/cmd/analyze/code-samples/optimizely/js/sample-OPT.js b/cmd/feature_experimentation/analyze/code-samples/optimizely/js/sample-OPT.js similarity index 100% rename from cmd/analyze/code-samples/optimizely/js/sample-OPT.js rename to cmd/feature_experimentation/analyze/code-samples/optimizely/js/sample-OPT.js diff --git a/cmd/analyze/code-samples/optimizely/js/sample-OPT.ts b/cmd/feature_experimentation/analyze/code-samples/optimizely/js/sample-OPT.ts similarity index 100% rename from cmd/analyze/code-samples/optimizely/js/sample-OPT.ts rename to cmd/feature_experimentation/analyze/code-samples/optimizely/js/sample-OPT.ts diff --git a/cmd/analyze/code-samples/optimizely/net/sample-OPT.cs b/cmd/feature_experimentation/analyze/code-samples/optimizely/net/sample-OPT.cs similarity index 100% rename from cmd/analyze/code-samples/optimizely/net/sample-OPT.cs rename to cmd/feature_experimentation/analyze/code-samples/optimizely/net/sample-OPT.cs diff --git a/cmd/analyze/code-samples/optimizely/php/sample-OPT.php b/cmd/feature_experimentation/analyze/code-samples/optimizely/php/sample-OPT.php similarity index 100% rename from cmd/analyze/code-samples/optimizely/php/sample-OPT.php rename to cmd/feature_experimentation/analyze/code-samples/optimizely/php/sample-OPT.php diff --git a/cmd/analyze/code-samples/optimizely/python/sample-OPT.py b/cmd/feature_experimentation/analyze/code-samples/optimizely/python/sample-OPT.py similarity index 100% rename from cmd/analyze/code-samples/optimizely/python/sample-OPT.py rename to cmd/feature_experimentation/analyze/code-samples/optimizely/python/sample-OPT.py diff --git a/cmd/analyze/code-samples/optimizely/react/sample-OPT.jsx b/cmd/feature_experimentation/analyze/code-samples/optimizely/react/sample-OPT.jsx similarity index 100% rename from cmd/analyze/code-samples/optimizely/react/sample-OPT.jsx rename to cmd/feature_experimentation/analyze/code-samples/optimizely/react/sample-OPT.jsx diff --git a/cmd/analyze/code-samples/split/go/sample-SPLIT.go b/cmd/feature_experimentation/analyze/code-samples/split/go/sample-SPLIT.go similarity index 100% rename from cmd/analyze/code-samples/split/go/sample-SPLIT.go rename to cmd/feature_experimentation/analyze/code-samples/split/go/sample-SPLIT.go diff --git a/cmd/analyze/code-samples/split/java/sample-SPLIT.java b/cmd/feature_experimentation/analyze/code-samples/split/java/sample-SPLIT.java similarity index 100% rename from cmd/analyze/code-samples/split/java/sample-SPLIT.java rename to cmd/feature_experimentation/analyze/code-samples/split/java/sample-SPLIT.java diff --git a/cmd/analyze/code-samples/split/java/sample-SPLIT.kt b/cmd/feature_experimentation/analyze/code-samples/split/java/sample-SPLIT.kt similarity index 100% rename from cmd/analyze/code-samples/split/java/sample-SPLIT.kt rename to cmd/feature_experimentation/analyze/code-samples/split/java/sample-SPLIT.kt diff --git a/cmd/analyze/code-samples/split/js/sample-SPLIT.js b/cmd/feature_experimentation/analyze/code-samples/split/js/sample-SPLIT.js similarity index 100% rename from cmd/analyze/code-samples/split/js/sample-SPLIT.js rename to cmd/feature_experimentation/analyze/code-samples/split/js/sample-SPLIT.js diff --git a/cmd/analyze/code-samples/split/js/sample-SPLIT.ts b/cmd/feature_experimentation/analyze/code-samples/split/js/sample-SPLIT.ts similarity index 100% rename from cmd/analyze/code-samples/split/js/sample-SPLIT.ts rename to cmd/feature_experimentation/analyze/code-samples/split/js/sample-SPLIT.ts diff --git a/cmd/analyze/code-samples/split/net/sample-SPLIT.cs b/cmd/feature_experimentation/analyze/code-samples/split/net/sample-SPLIT.cs similarity index 100% rename from cmd/analyze/code-samples/split/net/sample-SPLIT.cs rename to cmd/feature_experimentation/analyze/code-samples/split/net/sample-SPLIT.cs diff --git a/cmd/analyze/code-samples/split/php/sample-SPLIT.php b/cmd/feature_experimentation/analyze/code-samples/split/php/sample-SPLIT.php similarity index 100% rename from cmd/analyze/code-samples/split/php/sample-SPLIT.php rename to cmd/feature_experimentation/analyze/code-samples/split/php/sample-SPLIT.php diff --git a/cmd/analyze/code-samples/split/python/sample-SPLIT.py b/cmd/feature_experimentation/analyze/code-samples/split/python/sample-SPLIT.py similarity index 100% rename from cmd/analyze/code-samples/split/python/sample-SPLIT.py rename to cmd/feature_experimentation/analyze/code-samples/split/python/sample-SPLIT.py diff --git a/cmd/analyze/code-samples/vwo/go/sample-VWO.go b/cmd/feature_experimentation/analyze/code-samples/vwo/go/sample-VWO.go similarity index 100% rename from cmd/analyze/code-samples/vwo/go/sample-VWO.go rename to cmd/feature_experimentation/analyze/code-samples/vwo/go/sample-VWO.go diff --git a/cmd/analyze/code-samples/vwo/java/sample-VWO.java b/cmd/feature_experimentation/analyze/code-samples/vwo/java/sample-VWO.java similarity index 100% rename from cmd/analyze/code-samples/vwo/java/sample-VWO.java rename to cmd/feature_experimentation/analyze/code-samples/vwo/java/sample-VWO.java diff --git a/cmd/analyze/code-samples/vwo/java/sample-VWO.kt b/cmd/feature_experimentation/analyze/code-samples/vwo/java/sample-VWO.kt similarity index 100% rename from cmd/analyze/code-samples/vwo/java/sample-VWO.kt rename to cmd/feature_experimentation/analyze/code-samples/vwo/java/sample-VWO.kt diff --git a/cmd/analyze/code-samples/vwo/js/sample-VWO.js b/cmd/feature_experimentation/analyze/code-samples/vwo/js/sample-VWO.js similarity index 100% rename from cmd/analyze/code-samples/vwo/js/sample-VWO.js rename to cmd/feature_experimentation/analyze/code-samples/vwo/js/sample-VWO.js diff --git a/cmd/analyze/code-samples/vwo/js/sample-VWO.ts b/cmd/feature_experimentation/analyze/code-samples/vwo/js/sample-VWO.ts similarity index 100% rename from cmd/analyze/code-samples/vwo/js/sample-VWO.ts rename to cmd/feature_experimentation/analyze/code-samples/vwo/js/sample-VWO.ts diff --git a/cmd/analyze/code-samples/vwo/net/sample-VWO.cs b/cmd/feature_experimentation/analyze/code-samples/vwo/net/sample-VWO.cs similarity index 100% rename from cmd/analyze/code-samples/vwo/net/sample-VWO.cs rename to cmd/feature_experimentation/analyze/code-samples/vwo/net/sample-VWO.cs diff --git a/cmd/analyze/code-samples/vwo/php/sample-VWO.php b/cmd/feature_experimentation/analyze/code-samples/vwo/php/sample-VWO.php similarity index 100% rename from cmd/analyze/code-samples/vwo/php/sample-VWO.php rename to cmd/feature_experimentation/analyze/code-samples/vwo/php/sample-VWO.php diff --git a/cmd/analyze/code-samples/vwo/python/sample-VWO.py b/cmd/feature_experimentation/analyze/code-samples/vwo/python/sample-VWO.py similarity index 100% rename from cmd/analyze/code-samples/vwo/python/sample-VWO.py rename to cmd/feature_experimentation/analyze/code-samples/vwo/python/sample-VWO.py diff --git a/cmd/analyze/flag/create.go b/cmd/feature_experimentation/analyze/flag/create.go similarity index 100% rename from cmd/analyze/flag/create.go rename to cmd/feature_experimentation/analyze/flag/create.go diff --git a/cmd/analyze/flag/example-regex.json b/cmd/feature_experimentation/analyze/flag/example-regex.json similarity index 100% rename from cmd/analyze/flag/example-regex.json rename to cmd/feature_experimentation/analyze/flag/example-regex.json diff --git a/cmd/analyze/flag/flag.go b/cmd/feature_experimentation/analyze/flag/flag.go similarity index 100% rename from cmd/analyze/flag/flag.go rename to cmd/feature_experimentation/analyze/flag/flag.go diff --git a/cmd/analyze/flag/list.go b/cmd/feature_experimentation/analyze/flag/list.go similarity index 100% rename from cmd/analyze/flag/list.go rename to cmd/feature_experimentation/analyze/flag/list.go diff --git a/cmd/analyze/flag/predefined-regexes/launchdarkly-regexes.json b/cmd/feature_experimentation/analyze/flag/predefined-regexes/launchdarkly-regexes.json similarity index 100% rename from cmd/analyze/flag/predefined-regexes/launchdarkly-regexes.json rename to cmd/feature_experimentation/analyze/flag/predefined-regexes/launchdarkly-regexes.json diff --git a/cmd/analyze/flag/predefined-regexes/optimizely-regexes.json b/cmd/feature_experimentation/analyze/flag/predefined-regexes/optimizely-regexes.json similarity index 100% rename from cmd/analyze/flag/predefined-regexes/optimizely-regexes.json rename to cmd/feature_experimentation/analyze/flag/predefined-regexes/optimizely-regexes.json diff --git a/cmd/analyze/flag/predefined-regexes/split-regexes.json b/cmd/feature_experimentation/analyze/flag/predefined-regexes/split-regexes.json similarity index 100% rename from cmd/analyze/flag/predefined-regexes/split-regexes.json rename to cmd/feature_experimentation/analyze/flag/predefined-regexes/split-regexes.json diff --git a/cmd/analyze/flag/predefined-regexes/template-regexes.json b/cmd/feature_experimentation/analyze/flag/predefined-regexes/template-regexes.json similarity index 100% rename from cmd/analyze/flag/predefined-regexes/template-regexes.json rename to cmd/feature_experimentation/analyze/flag/predefined-regexes/template-regexes.json diff --git a/cmd/analyze/flag/predefined-regexes/vwo-regexes.json b/cmd/feature_experimentation/analyze/flag/predefined-regexes/vwo-regexes.json similarity index 100% rename from cmd/analyze/flag/predefined-regexes/vwo-regexes.json rename to cmd/feature_experimentation/analyze/flag/predefined-regexes/vwo-regexes.json diff --git a/cmd/campaign/campaign.go b/cmd/feature_experimentation/campaign/campaign.go similarity index 100% rename from cmd/campaign/campaign.go rename to cmd/feature_experimentation/campaign/campaign.go diff --git a/cmd/campaign/campaign_test.go b/cmd/feature_experimentation/campaign/campaign_test.go similarity index 100% rename from cmd/campaign/campaign_test.go rename to cmd/feature_experimentation/campaign/campaign_test.go diff --git a/cmd/campaign/create.go b/cmd/feature_experimentation/campaign/create.go similarity index 100% rename from cmd/campaign/create.go rename to cmd/feature_experimentation/campaign/create.go diff --git a/cmd/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go similarity index 100% rename from cmd/campaign/delete.go rename to cmd/feature_experimentation/campaign/delete.go diff --git a/cmd/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go similarity index 100% rename from cmd/campaign/edit.go rename to cmd/feature_experimentation/campaign/edit.go diff --git a/cmd/campaign/get.go b/cmd/feature_experimentation/campaign/get.go similarity index 100% rename from cmd/campaign/get.go rename to cmd/feature_experimentation/campaign/get.go diff --git a/cmd/campaign/list.go b/cmd/feature_experimentation/campaign/list.go similarity index 100% rename from cmd/campaign/list.go rename to cmd/feature_experimentation/campaign/list.go diff --git a/cmd/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go similarity index 100% rename from cmd/campaign/switch.go rename to cmd/feature_experimentation/campaign/switch.go diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go new file mode 100644 index 0000000..849c666 --- /dev/null +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -0,0 +1,49 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package feature_experimentation + +import ( + "github.com/flagship-io/flagship/cmd/feature_experimentation/analyze" + "github.com/flagship-io/flagship/cmd/feature_experimentation/campaign" + "github.com/flagship-io/flagship/cmd/feature_experimentation/flag" + "github.com/flagship-io/flagship/cmd/feature_experimentation/goal" + "github.com/flagship-io/flagship/cmd/feature_experimentation/panic" + "github.com/flagship-io/flagship/cmd/feature_experimentation/project" + "github.com/flagship-io/flagship/cmd/feature_experimentation/resource" + targetingkey "github.com/flagship-io/flagship/cmd/feature_experimentation/targeting_key" + "github.com/flagship-io/flagship/cmd/feature_experimentation/user" + "github.com/flagship-io/flagship/cmd/feature_experimentation/variation" + variationgroup "github.com/flagship-io/flagship/cmd/feature_experimentation/variation_group" + + "github.com/spf13/cobra" +) + +// FeatureExperimentationCmd represents the feature experimentation command +var FeatureExperimentationCmd = &cobra.Command{ + Use: "feature-experimentation [project|campaign|flag|goal|targeting-key|variation-group|variation]", + Aliases: []string{"feature-experimentation", "feature-exp", "fe", "feat-exp"}, + Short: "Manage resources related to the feature experimentation product", + Long: `Manage resources related to the feature experimentation product in your account`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func addSubCommandPalettes() { + FeatureExperimentationCmd.AddCommand(campaign.CampaignCmd) + FeatureExperimentationCmd.AddCommand(project.ProjectCmd) + FeatureExperimentationCmd.AddCommand(panic.PanicCmd) + FeatureExperimentationCmd.AddCommand(user.UserCmd) + FeatureExperimentationCmd.AddCommand(variationgroup.VariationGroupCmd) + FeatureExperimentationCmd.AddCommand(variation.VariationCmd) + FeatureExperimentationCmd.AddCommand(flag.FlagCmd) + FeatureExperimentationCmd.AddCommand(goal.GoalCmd) + FeatureExperimentationCmd.AddCommand(targetingkey.TargetingKeyCmd) + FeatureExperimentationCmd.AddCommand(analyze.AnalyzeCmd) + FeatureExperimentationCmd.AddCommand(resource.ResourceCmd) +} + +func init() { + addSubCommandPalettes() +} diff --git a/cmd/flag/create.go b/cmd/feature_experimentation/flag/create.go similarity index 100% rename from cmd/flag/create.go rename to cmd/feature_experimentation/flag/create.go diff --git a/cmd/flag/delete.go b/cmd/feature_experimentation/flag/delete.go similarity index 100% rename from cmd/flag/delete.go rename to cmd/feature_experimentation/flag/delete.go diff --git a/cmd/flag/edit.go b/cmd/feature_experimentation/flag/edit.go similarity index 100% rename from cmd/flag/edit.go rename to cmd/feature_experimentation/flag/edit.go diff --git a/cmd/flag/flag.go b/cmd/feature_experimentation/flag/flag.go similarity index 100% rename from cmd/flag/flag.go rename to cmd/feature_experimentation/flag/flag.go diff --git a/cmd/flag/flag_test.go b/cmd/feature_experimentation/flag/flag_test.go similarity index 100% rename from cmd/flag/flag_test.go rename to cmd/feature_experimentation/flag/flag_test.go diff --git a/cmd/flag/get.go b/cmd/feature_experimentation/flag/get.go similarity index 100% rename from cmd/flag/get.go rename to cmd/feature_experimentation/flag/get.go diff --git a/cmd/flag/list.go b/cmd/feature_experimentation/flag/list.go similarity index 100% rename from cmd/flag/list.go rename to cmd/feature_experimentation/flag/list.go diff --git a/cmd/goal/create.go b/cmd/feature_experimentation/goal/create.go similarity index 100% rename from cmd/goal/create.go rename to cmd/feature_experimentation/goal/create.go diff --git a/cmd/goal/delete.go b/cmd/feature_experimentation/goal/delete.go similarity index 100% rename from cmd/goal/delete.go rename to cmd/feature_experimentation/goal/delete.go diff --git a/cmd/goal/edit.go b/cmd/feature_experimentation/goal/edit.go similarity index 100% rename from cmd/goal/edit.go rename to cmd/feature_experimentation/goal/edit.go diff --git a/cmd/goal/get.go b/cmd/feature_experimentation/goal/get.go similarity index 100% rename from cmd/goal/get.go rename to cmd/feature_experimentation/goal/get.go diff --git a/cmd/goal/goal.go b/cmd/feature_experimentation/goal/goal.go similarity index 100% rename from cmd/goal/goal.go rename to cmd/feature_experimentation/goal/goal.go diff --git a/cmd/goal/goal_test.go b/cmd/feature_experimentation/goal/goal_test.go similarity index 100% rename from cmd/goal/goal_test.go rename to cmd/feature_experimentation/goal/goal_test.go diff --git a/cmd/goal/list.go b/cmd/feature_experimentation/goal/list.go similarity index 100% rename from cmd/goal/list.go rename to cmd/feature_experimentation/goal/list.go diff --git a/cmd/panic/panic.go b/cmd/feature_experimentation/panic/panic.go similarity index 100% rename from cmd/panic/panic.go rename to cmd/feature_experimentation/panic/panic.go diff --git a/cmd/panic/panic_test.go b/cmd/feature_experimentation/panic/panic_test.go similarity index 100% rename from cmd/panic/panic_test.go rename to cmd/feature_experimentation/panic/panic_test.go diff --git a/cmd/project/create.go b/cmd/feature_experimentation/project/create.go similarity index 100% rename from cmd/project/create.go rename to cmd/feature_experimentation/project/create.go diff --git a/cmd/project/delete.go b/cmd/feature_experimentation/project/delete.go similarity index 100% rename from cmd/project/delete.go rename to cmd/feature_experimentation/project/delete.go diff --git a/cmd/project/edit.go b/cmd/feature_experimentation/project/edit.go similarity index 100% rename from cmd/project/edit.go rename to cmd/feature_experimentation/project/edit.go diff --git a/cmd/project/get.go b/cmd/feature_experimentation/project/get.go similarity index 100% rename from cmd/project/get.go rename to cmd/feature_experimentation/project/get.go diff --git a/cmd/project/list.go b/cmd/feature_experimentation/project/list.go similarity index 100% rename from cmd/project/list.go rename to cmd/feature_experimentation/project/list.go diff --git a/cmd/project/project.go b/cmd/feature_experimentation/project/project.go similarity index 100% rename from cmd/project/project.go rename to cmd/feature_experimentation/project/project.go diff --git a/cmd/project/project_test.go b/cmd/feature_experimentation/project/project_test.go similarity index 100% rename from cmd/project/project_test.go rename to cmd/feature_experimentation/project/project_test.go diff --git a/cmd/project/switch.go b/cmd/feature_experimentation/project/switch.go similarity index 100% rename from cmd/project/switch.go rename to cmd/feature_experimentation/project/switch.go diff --git a/cmd/resource/load.go b/cmd/feature_experimentation/resource/load.go similarity index 100% rename from cmd/resource/load.go rename to cmd/feature_experimentation/resource/load.go diff --git a/cmd/resource/loadResource.json b/cmd/feature_experimentation/resource/loadResource.json similarity index 100% rename from cmd/resource/loadResource.json rename to cmd/feature_experimentation/resource/loadResource.json diff --git a/cmd/resource/resource.go b/cmd/feature_experimentation/resource/resource.go similarity index 100% rename from cmd/resource/resource.go rename to cmd/feature_experimentation/resource/resource.go diff --git a/cmd/targeting_key/create.go b/cmd/feature_experimentation/targeting_key/create.go similarity index 100% rename from cmd/targeting_key/create.go rename to cmd/feature_experimentation/targeting_key/create.go diff --git a/cmd/targeting_key/delete.go b/cmd/feature_experimentation/targeting_key/delete.go similarity index 100% rename from cmd/targeting_key/delete.go rename to cmd/feature_experimentation/targeting_key/delete.go diff --git a/cmd/targeting_key/edit.go b/cmd/feature_experimentation/targeting_key/edit.go similarity index 100% rename from cmd/targeting_key/edit.go rename to cmd/feature_experimentation/targeting_key/edit.go diff --git a/cmd/targeting_key/get.go b/cmd/feature_experimentation/targeting_key/get.go similarity index 100% rename from cmd/targeting_key/get.go rename to cmd/feature_experimentation/targeting_key/get.go diff --git a/cmd/targeting_key/list.go b/cmd/feature_experimentation/targeting_key/list.go similarity index 100% rename from cmd/targeting_key/list.go rename to cmd/feature_experimentation/targeting_key/list.go diff --git a/cmd/targeting_key/targeting_key.go b/cmd/feature_experimentation/targeting_key/targeting_key.go similarity index 100% rename from cmd/targeting_key/targeting_key.go rename to cmd/feature_experimentation/targeting_key/targeting_key.go diff --git a/cmd/targeting_key/targeting_key_test.go b/cmd/feature_experimentation/targeting_key/targeting_key_test.go similarity index 100% rename from cmd/targeting_key/targeting_key_test.go rename to cmd/feature_experimentation/targeting_key/targeting_key_test.go diff --git a/cmd/user/create.go b/cmd/feature_experimentation/user/create.go similarity index 100% rename from cmd/user/create.go rename to cmd/feature_experimentation/user/create.go diff --git a/cmd/user/delete.go b/cmd/feature_experimentation/user/delete.go similarity index 100% rename from cmd/user/delete.go rename to cmd/feature_experimentation/user/delete.go diff --git a/cmd/user/edit.go b/cmd/feature_experimentation/user/edit.go similarity index 100% rename from cmd/user/edit.go rename to cmd/feature_experimentation/user/edit.go diff --git a/cmd/user/list.go b/cmd/feature_experimentation/user/list.go similarity index 100% rename from cmd/user/list.go rename to cmd/feature_experimentation/user/list.go diff --git a/cmd/user/user.go b/cmd/feature_experimentation/user/user.go similarity index 100% rename from cmd/user/user.go rename to cmd/feature_experimentation/user/user.go diff --git a/cmd/user/user_test.go b/cmd/feature_experimentation/user/user_test.go similarity index 100% rename from cmd/user/user_test.go rename to cmd/feature_experimentation/user/user_test.go diff --git a/cmd/variation/create.go b/cmd/feature_experimentation/variation/create.go similarity index 100% rename from cmd/variation/create.go rename to cmd/feature_experimentation/variation/create.go diff --git a/cmd/variation/delete.go b/cmd/feature_experimentation/variation/delete.go similarity index 100% rename from cmd/variation/delete.go rename to cmd/feature_experimentation/variation/delete.go diff --git a/cmd/variation/edit.go b/cmd/feature_experimentation/variation/edit.go similarity index 100% rename from cmd/variation/edit.go rename to cmd/feature_experimentation/variation/edit.go diff --git a/cmd/variation/get.go b/cmd/feature_experimentation/variation/get.go similarity index 100% rename from cmd/variation/get.go rename to cmd/feature_experimentation/variation/get.go diff --git a/cmd/variation/list.go b/cmd/feature_experimentation/variation/list.go similarity index 100% rename from cmd/variation/list.go rename to cmd/feature_experimentation/variation/list.go diff --git a/cmd/variation/variation.go b/cmd/feature_experimentation/variation/variation.go similarity index 100% rename from cmd/variation/variation.go rename to cmd/feature_experimentation/variation/variation.go diff --git a/cmd/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go similarity index 100% rename from cmd/variation/variation_test.go rename to cmd/feature_experimentation/variation/variation_test.go diff --git a/cmd/variation_group/create.go b/cmd/feature_experimentation/variation_group/create.go similarity index 100% rename from cmd/variation_group/create.go rename to cmd/feature_experimentation/variation_group/create.go diff --git a/cmd/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go similarity index 100% rename from cmd/variation_group/delete.go rename to cmd/feature_experimentation/variation_group/delete.go diff --git a/cmd/variation_group/edit.go b/cmd/feature_experimentation/variation_group/edit.go similarity index 100% rename from cmd/variation_group/edit.go rename to cmd/feature_experimentation/variation_group/edit.go diff --git a/cmd/variation_group/get.go b/cmd/feature_experimentation/variation_group/get.go similarity index 100% rename from cmd/variation_group/get.go rename to cmd/feature_experimentation/variation_group/get.go diff --git a/cmd/variation_group/list.go b/cmd/feature_experimentation/variation_group/list.go similarity index 100% rename from cmd/variation_group/list.go rename to cmd/feature_experimentation/variation_group/list.go diff --git a/cmd/variation_group/variation_group.go b/cmd/feature_experimentation/variation_group/variation_group.go similarity index 100% rename from cmd/variation_group/variation_group.go rename to cmd/feature_experimentation/variation_group/variation_group.go diff --git a/cmd/variation_group/variation_group_test.go b/cmd/feature_experimentation/variation_group/variation_group_test.go similarity index 100% rename from cmd/variation_group/variation_group_test.go rename to cmd/feature_experimentation/variation_group/variation_group_test.go diff --git a/cmd/root.go b/cmd/root.go index 3aec8bf..09d54ac 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -6,20 +6,11 @@ package cmd import ( "os" - "github.com/flagship-io/flagship/cmd/analyze" - "github.com/flagship-io/flagship/cmd/campaign" "github.com/flagship-io/flagship/cmd/configuration" - "github.com/flagship-io/flagship/cmd/flag" - "github.com/flagship-io/flagship/cmd/goal" + "github.com/flagship-io/flagship/cmd/feature_experimentation" "github.com/flagship-io/flagship/cmd/info" - "github.com/flagship-io/flagship/cmd/panic" - "github.com/flagship-io/flagship/cmd/project" - "github.com/flagship-io/flagship/cmd/resource" - targetingkey "github.com/flagship-io/flagship/cmd/targeting_key" "github.com/flagship-io/flagship/cmd/token" - "github.com/flagship-io/flagship/cmd/user" - "github.com/flagship-io/flagship/cmd/variation" - "github.com/flagship-io/flagship/cmd/variation_group" + "github.com/flagship-io/flagship/cmd/version" "github.com/flagship-io/flagship/utils/config" httprequest "github.com/flagship-io/flagship/utils/httpRequest" @@ -58,23 +49,18 @@ func Execute() { } } -func addSubCommandPalettes() { - rootCmd.AddCommand(campaign.CampaignCmd) - rootCmd.AddCommand(project.ProjectCmd) +func addFeatureExpSubCommandPalettes() { rootCmd.AddCommand(configuration.ConfigurationCmd) - rootCmd.AddCommand(panic.PanicCmd) - rootCmd.AddCommand(user.UserCmd) - rootCmd.AddCommand(variation_group.VariationGroupCmd) - rootCmd.AddCommand(variation.VariationCmd) - rootCmd.AddCommand(flag.FlagCmd) - rootCmd.AddCommand(goal.GoalCmd) - rootCmd.AddCommand(targetingkey.TargetingKeyCmd) rootCmd.AddCommand(version.VersionCmd) rootCmd.AddCommand(token.TokenCmd) - rootCmd.AddCommand(analyze.AnalyzeCmd) - rootCmd.AddCommand(resource.ResourceCmd) rootCmd.AddCommand(info.InfoCmd) + rootCmd.AddCommand(feature_experimentation.FeatureExperimentationCmd) } + +func addWebExpSubCommandPalettes() { + +} + func init() { cobra.OnInitialize(initConfig) @@ -87,7 +73,7 @@ func init() { rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file that contains your credentials (default is $HOME/.flagship/credentials.yaml)") - addSubCommandPalettes() + addFeatureExpSubCommandPalettes() } // initConfig reads in config file and ENV variables if set. From fbbaf86aec18551e4aa9036a70a475f030d941b5 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 8 Mar 2024 12:40:05 +0100 Subject: [PATCH 02/48] separate httprequest and mockfunction of FE from WE --- Makefile | 4 ++-- cmd/configuration/use.go | 2 +- cmd/feature_experimentation/analyze/flag/create.go | 3 +-- cmd/feature_experimentation/analyze/flag/list.go | 3 +-- cmd/feature_experimentation/campaign/campaign_test.go | 2 +- cmd/feature_experimentation/campaign/create.go | 3 +-- cmd/feature_experimentation/campaign/delete.go | 3 +-- cmd/feature_experimentation/campaign/edit.go | 3 +-- cmd/feature_experimentation/campaign/get.go | 3 +-- cmd/feature_experimentation/campaign/list.go | 3 +-- cmd/feature_experimentation/campaign/switch.go | 3 +-- cmd/feature_experimentation/flag/create.go | 3 +-- cmd/feature_experimentation/flag/delete.go | 3 +-- cmd/feature_experimentation/flag/edit.go | 3 +-- cmd/feature_experimentation/flag/flag_test.go | 2 +- cmd/feature_experimentation/flag/get.go | 3 +-- cmd/feature_experimentation/flag/list.go | 3 +-- cmd/feature_experimentation/goal/create.go | 3 +-- cmd/feature_experimentation/goal/delete.go | 3 +-- cmd/feature_experimentation/goal/edit.go | 3 +-- cmd/feature_experimentation/goal/get.go | 3 +-- cmd/feature_experimentation/goal/goal_test.go | 2 +- cmd/feature_experimentation/goal/list.go | 3 +-- cmd/feature_experimentation/panic/panic.go | 3 +-- cmd/feature_experimentation/panic/panic_test.go | 2 +- cmd/feature_experimentation/project/create.go | 3 +-- cmd/feature_experimentation/project/delete.go | 3 +-- cmd/feature_experimentation/project/edit.go | 3 +-- cmd/feature_experimentation/project/get.go | 3 +-- cmd/feature_experimentation/project/list.go | 3 +-- cmd/feature_experimentation/project/project_test.go | 2 +- cmd/feature_experimentation/project/switch.go | 3 +-- cmd/feature_experimentation/resource/load.go | 2 +- cmd/feature_experimentation/targeting_key/create.go | 3 +-- cmd/feature_experimentation/targeting_key/delete.go | 3 +-- cmd/feature_experimentation/targeting_key/edit.go | 3 +-- cmd/feature_experimentation/targeting_key/get.go | 3 +-- cmd/feature_experimentation/targeting_key/list.go | 3 +-- .../targeting_key/targeting_key_test.go | 2 +- cmd/feature_experimentation/user/create.go | 3 +-- cmd/feature_experimentation/user/delete.go | 3 +-- cmd/feature_experimentation/user/edit.go | 3 +-- cmd/feature_experimentation/user/list.go | 3 +-- cmd/feature_experimentation/user/user_test.go | 2 +- cmd/feature_experimentation/variation/create.go | 3 +-- cmd/feature_experimentation/variation/delete.go | 3 +-- cmd/feature_experimentation/variation/edit.go | 3 +-- cmd/feature_experimentation/variation/get.go | 3 +-- cmd/feature_experimentation/variation/list.go | 3 +-- cmd/feature_experimentation/variation/variation_test.go | 2 +- cmd/feature_experimentation/variation_group/create.go | 3 +-- cmd/feature_experimentation/variation_group/delete.go | 3 +-- cmd/feature_experimentation/variation_group/edit.go | 3 +-- cmd/feature_experimentation/variation_group/get.go | 3 +-- cmd/feature_experimentation/variation_group/list.go | 3 +-- .../variation_group/variation_group_test.go | 2 +- cmd/root.go | 4 ++-- cmd/token/info.go | 3 +-- .../httpRequest/{ => feature_experimentation}/campaign.go | 2 +- .../{ => feature_experimentation}/campaign_test.go | 2 +- utils/httpRequest/{ => feature_experimentation}/flag.go | 2 +- .../{ => feature_experimentation}/flag_test.go | 2 +- utils/httpRequest/{ => feature_experimentation}/goal.go | 2 +- .../{ => feature_experimentation}/goal_test.go | 2 +- .../{ => feature_experimentation}/main_test.go | 8 +++++--- utils/httpRequest/{ => feature_experimentation}/panic.go | 2 +- .../{ => feature_experimentation}/panic_test.go | 2 +- .../httpRequest/{ => feature_experimentation}/project.go | 2 +- .../{ => feature_experimentation}/project_test.go | 2 +- .../httpRequest/{ => feature_experimentation}/request.go | 2 +- .../{ => feature_experimentation}/request_test.go | 2 +- .../{ => feature_experimentation}/targeting_key.go | 2 +- .../{ => feature_experimentation}/targeting_key_test.go | 2 +- utils/httpRequest/{ => feature_experimentation}/token.go | 2 +- .../{ => feature_experimentation}/token_test.go | 2 +- utils/httpRequest/{ => feature_experimentation}/user.go | 2 +- .../{ => feature_experimentation}/user_test.go | 2 +- .../{ => feature_experimentation}/variation.go | 2 +- .../{ => feature_experimentation}/variation_group.go | 2 +- .../{ => feature_experimentation}/variation_group_test.go | 2 +- .../{ => feature_experimentation}/variation_test.go | 2 +- .../{ => feature_experimentation}/campaign.go | 2 +- utils/mock_function/{ => feature_experimentation}/flag.go | 2 +- utils/mock_function/{ => feature_experimentation}/goal.go | 2 +- .../mock_function/{ => feature_experimentation}/panic.go | 2 +- .../{ => feature_experimentation}/project.go | 2 +- .../{ => feature_experimentation}/request.go | 2 +- .../{ => feature_experimentation}/targeting_key.go | 2 +- utils/mock_function/{ => feature_experimentation}/user.go | 2 +- .../{ => feature_experimentation}/variation.go | 2 +- .../{ => feature_experimentation}/variation_group.go | 2 +- 91 files changed, 97 insertions(+), 140 deletions(-) rename utils/httpRequest/{ => feature_experimentation}/campaign.go (98%) rename utils/httpRequest/{ => feature_experimentation}/campaign_test.go (99%) rename utils/httpRequest/{ => feature_experimentation}/flag.go (96%) rename utils/httpRequest/{ => feature_experimentation}/flag_test.go (98%) rename utils/httpRequest/{ => feature_experimentation}/goal.go (97%) rename utils/httpRequest/{ => feature_experimentation}/goal_test.go (97%) rename utils/httpRequest/{ => feature_experimentation}/main_test.go (75%) rename utils/httpRequest/{ => feature_experimentation}/panic.go (94%) rename utils/httpRequest/{ => feature_experimentation}/panic_test.go (83%) rename utils/httpRequest/{ => feature_experimentation}/project.go (97%) rename utils/httpRequest/{ => feature_experimentation}/project_test.go (98%) rename utils/httpRequest/{ => feature_experimentation}/request.go (99%) rename utils/httpRequest/{ => feature_experimentation}/request_test.go (97%) rename utils/httpRequest/{ => feature_experimentation}/targeting_key.go (97%) rename utils/httpRequest/{ => feature_experimentation}/targeting_key_test.go (98%) rename utils/httpRequest/{ => feature_experimentation}/token.go (97%) rename utils/httpRequest/{ => feature_experimentation}/token_test.go (95%) rename utils/httpRequest/{ => feature_experimentation}/user.go (96%) rename utils/httpRequest/{ => feature_experimentation}/user_test.go (95%) rename utils/httpRequest/{ => feature_experimentation}/variation.go (98%) rename utils/httpRequest/{ => feature_experimentation}/variation_group.go (98%) rename utils/httpRequest/{ => feature_experimentation}/variation_group_test.go (98%) rename utils/httpRequest/{ => feature_experimentation}/variation_test.go (98%) rename utils/mock_function/{ => feature_experimentation}/campaign.go (99%) rename utils/mock_function/{ => feature_experimentation}/flag.go (98%) rename utils/mock_function/{ => feature_experimentation}/goal.go (98%) rename utils/mock_function/{ => feature_experimentation}/panic.go (94%) rename utils/mock_function/{ => feature_experimentation}/project.go (98%) rename utils/mock_function/{ => feature_experimentation}/request.go (96%) rename utils/mock_function/{ => feature_experimentation}/targeting_key.go (98%) rename utils/mock_function/{ => feature_experimentation}/user.go (98%) rename utils/mock_function/{ => feature_experimentation}/variation.go (99%) rename utils/mock_function/{ => feature_experimentation}/variation_group.go (99%) diff --git a/Makefile b/Makefile index bd32835..0a90b0e 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ build: test: SHELL:=/bin/bash test: mkdir -p coverage - go test -v -race `go list ./... | grep -v cmd/analyze/code-samples` -coverprofile coverage/cover.out.tmp - cat coverage/cover.out.tmp | grep -v "mock_\|cmd/analyze/code-samples" > coverage/cover.out + go test -v -race `go list ./... | grep -v cmd/feature_experimentation/analyze/code-samples` -coverprofile coverage/cover.out.tmp + cat coverage/cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze/code-samples" > coverage/cover.out go tool cover -html=coverage/cover.out -o coverage/cover.html go tool cover -func=coverage/cover.out \ No newline at end of file diff --git a/cmd/configuration/use.go b/cmd/configuration/use.go index 4ff6b22..e844912 100644 --- a/cmd/configuration/use.go +++ b/cmd/configuration/use.go @@ -9,7 +9,7 @@ import ( "slices" "github.com/flagship-io/flagship/utils/config" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/analyze/flag/create.go b/cmd/feature_experimentation/analyze/flag/create.go index b21c510..c4639ad 100644 --- a/cmd/feature_experimentation/analyze/flag/create.go +++ b/cmd/feature_experimentation/analyze/flag/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -15,7 +14,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/rodaine/table" "github.com/spf13/cobra" "golang.org/x/exp/slices" diff --git a/cmd/feature_experimentation/analyze/flag/list.go b/cmd/feature_experimentation/analyze/flag/list.go index 243d4b9..0b879ea 100644 --- a/cmd/feature_experimentation/analyze/flag/list.go +++ b/cmd/feature_experimentation/analyze/flag/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -13,7 +12,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/kyokomi/emoji/v2" "github.com/rodaine/table" "github.com/spf13/cobra" diff --git a/cmd/feature_experimentation/campaign/campaign_test.go b/cmd/feature_experimentation/campaign/campaign_test.go index 1703ba6..ff2fcb1 100644 --- a/cmd/feature_experimentation/campaign/campaign_test.go +++ b/cmd/feature_experimentation/campaign/campaign_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/campaign/create.go b/cmd/feature_experimentation/campaign/create.go index 25d501a..755e0d4 100644 --- a/cmd/feature_experimentation/campaign/create.go +++ b/cmd/feature_experimentation/campaign/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go index 4a3cf42..db565bb 100644 --- a/cmd/feature_experimentation/campaign/delete.go +++ b/cmd/feature_experimentation/campaign/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go index d72ac82..eafc87d 100644 --- a/cmd/feature_experimentation/campaign/edit.go +++ b/cmd/feature_experimentation/campaign/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/get.go b/cmd/feature_experimentation/campaign/get.go index 27f264b..fea80f5 100644 --- a/cmd/feature_experimentation/campaign/get.go +++ b/cmd/feature_experimentation/campaign/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/campaign/list.go b/cmd/feature_experimentation/campaign/list.go index 76d2930..b9e2ff4 100644 --- a/cmd/feature_experimentation/campaign/list.go +++ b/cmd/feature_experimentation/campaign/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go index 60a2c29..d79a400 100644 --- a/cmd/feature_experimentation/campaign/switch.go +++ b/cmd/feature_experimentation/campaign/switch.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/create.go b/cmd/feature_experimentation/flag/create.go index 961816a..9f48262 100644 --- a/cmd/feature_experimentation/flag/create.go +++ b/cmd/feature_experimentation/flag/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -10,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/delete.go b/cmd/feature_experimentation/flag/delete.go index 49be244..437aaa9 100644 --- a/cmd/feature_experimentation/flag/delete.go +++ b/cmd/feature_experimentation/flag/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/edit.go b/cmd/feature_experimentation/flag/edit.go index 62fe98a..03f5182 100644 --- a/cmd/feature_experimentation/flag/edit.go +++ b/cmd/feature_experimentation/flag/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/flag_test.go b/cmd/feature_experimentation/flag/flag_test.go index f709252..290edc8 100644 --- a/cmd/feature_experimentation/flag/flag_test.go +++ b/cmd/feature_experimentation/flag/flag_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/flag/get.go b/cmd/feature_experimentation/flag/get.go index 5ce80f0..ba5ed95 100644 --- a/cmd/feature_experimentation/flag/get.go +++ b/cmd/feature_experimentation/flag/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/flag/list.go b/cmd/feature_experimentation/flag/list.go index 6e75fa5..8fc5e02 100644 --- a/cmd/feature_experimentation/flag/list.go +++ b/cmd/feature_experimentation/flag/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/goal/create.go b/cmd/feature_experimentation/goal/create.go index cdc0d64..1e07326 100644 --- a/cmd/feature_experimentation/goal/create.go +++ b/cmd/feature_experimentation/goal/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/delete.go b/cmd/feature_experimentation/goal/delete.go index 09a1f61..8c2f9c1 100644 --- a/cmd/feature_experimentation/goal/delete.go +++ b/cmd/feature_experimentation/goal/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/edit.go b/cmd/feature_experimentation/goal/edit.go index d5166be..ea80ca1 100644 --- a/cmd/feature_experimentation/goal/edit.go +++ b/cmd/feature_experimentation/goal/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/get.go b/cmd/feature_experimentation/goal/get.go index c59533e..ad7a24f 100644 --- a/cmd/feature_experimentation/goal/get.go +++ b/cmd/feature_experimentation/goal/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/goal/goal_test.go b/cmd/feature_experimentation/goal/goal_test.go index eba3da4..4c2567a 100644 --- a/cmd/feature_experimentation/goal/goal_test.go +++ b/cmd/feature_experimentation/goal/goal_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/goal/list.go b/cmd/feature_experimentation/goal/list.go index 0a4db47..2637fba 100644 --- a/cmd/feature_experimentation/goal/list.go +++ b/cmd/feature_experimentation/goal/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/panic/panic.go b/cmd/feature_experimentation/panic/panic.go index dcfd0bc..62b61e2 100644 --- a/cmd/feature_experimentation/panic/panic.go +++ b/cmd/feature_experimentation/panic/panic.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package panic @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/panic/panic_test.go b/cmd/feature_experimentation/panic/panic_test.go index f4f0272..45a566e 100644 --- a/cmd/feature_experimentation/panic/panic_test.go +++ b/cmd/feature_experimentation/panic/panic_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/project/create.go b/cmd/feature_experimentation/project/create.go index 8e59a90..ebd5daa 100644 --- a/cmd/feature_experimentation/project/create.go +++ b/cmd/feature_experimentation/project/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -10,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/delete.go b/cmd/feature_experimentation/project/delete.go index ab7f60d..b7f50ad 100644 --- a/cmd/feature_experimentation/project/delete.go +++ b/cmd/feature_experimentation/project/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/edit.go b/cmd/feature_experimentation/project/edit.go index 3025a7b..7a864c4 100644 --- a/cmd/feature_experimentation/project/edit.go +++ b/cmd/feature_experimentation/project/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -10,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/get.go b/cmd/feature_experimentation/project/get.go index d5fdf57..5b40066 100644 --- a/cmd/feature_experimentation/project/get.go +++ b/cmd/feature_experimentation/project/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/project/list.go b/cmd/feature_experimentation/project/list.go index b8fafdc..1dcd860 100644 --- a/cmd/feature_experimentation/project/list.go +++ b/cmd/feature_experimentation/project/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/project/project_test.go b/cmd/feature_experimentation/project/project_test.go index 4d3e707..e07ed5f 100644 --- a/cmd/feature_experimentation/project/project_test.go +++ b/cmd/feature_experimentation/project/project_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/project/switch.go b/cmd/feature_experimentation/project/switch.go index 7670c44..44ed0df 100644 --- a/cmd/feature_experimentation/project/switch.go +++ b/cmd/feature_experimentation/project/switch.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package project @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 2428b7d..4c988fa 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -17,7 +17,7 @@ import ( "github.com/d5/tengo/v2" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/targeting_key/create.go b/cmd/feature_experimentation/targeting_key/create.go index f874b28..16eed85 100644 --- a/cmd/feature_experimentation/targeting_key/create.go +++ b/cmd/feature_experimentation/targeting_key/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/delete.go b/cmd/feature_experimentation/targeting_key/delete.go index fd80589..1c62173 100644 --- a/cmd/feature_experimentation/targeting_key/delete.go +++ b/cmd/feature_experimentation/targeting_key/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/edit.go b/cmd/feature_experimentation/targeting_key/edit.go index da1359d..9275190 100644 --- a/cmd/feature_experimentation/targeting_key/edit.go +++ b/cmd/feature_experimentation/targeting_key/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/get.go b/cmd/feature_experimentation/targeting_key/get.go index d403433..1c389cd 100644 --- a/cmd/feature_experimentation/targeting_key/get.go +++ b/cmd/feature_experimentation/targeting_key/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/targeting_key/list.go b/cmd/feature_experimentation/targeting_key/list.go index 8aee9fc..75c13d5 100644 --- a/cmd/feature_experimentation/targeting_key/list.go +++ b/cmd/feature_experimentation/targeting_key/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/targeting_key/targeting_key_test.go b/cmd/feature_experimentation/targeting_key/targeting_key_test.go index 55b3226..3724b04 100644 --- a/cmd/feature_experimentation/targeting_key/targeting_key_test.go +++ b/cmd/feature_experimentation/targeting_key/targeting_key_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/user/create.go b/cmd/feature_experimentation/user/create.go index 8f14f0e..69f4161 100644 --- a/cmd/feature_experimentation/user/create.go +++ b/cmd/feature_experimentation/user/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package user @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/delete.go b/cmd/feature_experimentation/user/delete.go index 48408e1..8120b26 100644 --- a/cmd/feature_experimentation/user/delete.go +++ b/cmd/feature_experimentation/user/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package user @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/edit.go b/cmd/feature_experimentation/user/edit.go index ff4afc1..5167a8c 100644 --- a/cmd/feature_experimentation/user/edit.go +++ b/cmd/feature_experimentation/user/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package user @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/list.go b/cmd/feature_experimentation/user/list.go index 40626a9..333fe05 100644 --- a/cmd/feature_experimentation/user/list.go +++ b/cmd/feature_experimentation/user/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package user @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/user/user_test.go b/cmd/feature_experimentation/user/user_test.go index 29b6bf2..d6c6905 100644 --- a/cmd/feature_experimentation/user/user_test.go +++ b/cmd/feature_experimentation/user/user_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/variation/create.go b/cmd/feature_experimentation/variation/create.go index a1c9bdd..982cc96 100644 --- a/cmd/feature_experimentation/variation/create.go +++ b/cmd/feature_experimentation/variation/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index 1c7e0b5..6ef714b 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/edit.go b/cmd/feature_experimentation/variation/edit.go index ca5cb59..a39434b 100644 --- a/cmd/feature_experimentation/variation/edit.go +++ b/cmd/feature_experimentation/variation/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/get.go b/cmd/feature_experimentation/variation/get.go index a29d2fa..4c8d2d0 100644 --- a/cmd/feature_experimentation/variation/get.go +++ b/cmd/feature_experimentation/variation/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation/list.go b/cmd/feature_experimentation/variation/list.go index cdff25b..c9ca89f 100644 --- a/cmd/feature_experimentation/variation/list.go +++ b/cmd/feature_experimentation/variation/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go index 35413c2..8bb8831 100644 --- a/cmd/feature_experimentation/variation/variation_test.go +++ b/cmd/feature_experimentation/variation/variation_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/feature_experimentation/variation_group/create.go b/cmd/feature_experimentation/variation_group/create.go index 4417e59..9388f36 100644 --- a/cmd/feature_experimentation/variation_group/create.go +++ b/cmd/feature_experimentation/variation_group/create.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation_group @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go index 47d6c5b..b4ee947 100644 --- a/cmd/feature_experimentation/variation_group/delete.go +++ b/cmd/feature_experimentation/variation_group/delete.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation_group @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/edit.go b/cmd/feature_experimentation/variation_group/edit.go index 30496d7..6f6b027 100644 --- a/cmd/feature_experimentation/variation_group/edit.go +++ b/cmd/feature_experimentation/variation_group/edit.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation_group @@ -8,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/get.go b/cmd/feature_experimentation/variation_group/get.go index b65fdb4..019bfa3 100644 --- a/cmd/feature_experimentation/variation_group/get.go +++ b/cmd/feature_experimentation/variation_group/get.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation_group @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation_group/list.go b/cmd/feature_experimentation/variation_group/list.go index 9341556..bc07195 100644 --- a/cmd/feature_experimentation/variation_group/list.go +++ b/cmd/feature_experimentation/variation_group/list.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package variation_group @@ -8,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation_group/variation_group_test.go b/cmd/feature_experimentation/variation_group/variation_group_test.go index 6bde561..a893566 100644 --- a/cmd/feature_experimentation/variation_group/variation_group_test.go +++ b/cmd/feature_experimentation/variation_group/variation_group_test.go @@ -6,7 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) diff --git a/cmd/root.go b/cmd/root.go index 09d54ac..4f690a3 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -13,7 +13,7 @@ import ( "github.com/flagship-io/flagship/cmd/version" "github.com/flagship-io/flagship/utils/config" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest_fe "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -66,7 +66,7 @@ func init() { rootCmd.PersistentFlags().StringVarP(&cmdToken, "token", "t", "", "access token to manage flagship resources") rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "f", config.OutputFormat, "output format for the get and list subcommands for flagship resources. Only 3 format are possible: table, json, json-pretty") - rootCmd.PersistentFlags().StringVarP(&httprequest.UserAgent, "user-agent", "u", config.DefaultUserAgent, "custom user agent") + rootCmd.PersistentFlags().StringVarP(&httprequest_fe.UserAgent, "user-agent", "u", config.DefaultUserAgent, "custom user agent") viper.BindPFlag("token", rootCmd.PersistentFlags().Lookup("token")) viper.BindPFlag("output_format", rootCmd.PersistentFlags().Lookup("output-format")) diff --git a/cmd/token/info.go b/cmd/token/info.go index 3031c07..bf5e7ac 100644 --- a/cmd/token/info.go +++ b/cmd/token/info.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package token @@ -9,7 +8,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest" + httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/utils/httpRequest/campaign.go b/utils/httpRequest/feature_experimentation/campaign.go similarity index 98% rename from utils/httpRequest/campaign.go rename to utils/httpRequest/feature_experimentation/campaign.go index c19c55f..504e8b4 100644 --- a/utils/httpRequest/campaign.go +++ b/utils/httpRequest/feature_experimentation/campaign.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/campaign_test.go b/utils/httpRequest/feature_experimentation/campaign_test.go similarity index 99% rename from utils/httpRequest/campaign_test.go rename to utils/httpRequest/feature_experimentation/campaign_test.go index 2a8545c..30c11b8 100644 --- a/utils/httpRequest/campaign_test.go +++ b/utils/httpRequest/feature_experimentation/campaign_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/flag.go b/utils/httpRequest/feature_experimentation/flag.go similarity index 96% rename from utils/httpRequest/flag.go rename to utils/httpRequest/feature_experimentation/flag.go index 51561c9..dcaf44e 100644 --- a/utils/httpRequest/flag.go +++ b/utils/httpRequest/feature_experimentation/flag.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/flag_test.go b/utils/httpRequest/feature_experimentation/flag_test.go similarity index 98% rename from utils/httpRequest/flag_test.go rename to utils/httpRequest/feature_experimentation/flag_test.go index eee3b61..7686796 100644 --- a/utils/httpRequest/flag_test.go +++ b/utils/httpRequest/feature_experimentation/flag_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/goal.go b/utils/httpRequest/feature_experimentation/goal.go similarity index 97% rename from utils/httpRequest/goal.go rename to utils/httpRequest/feature_experimentation/goal.go index 58fbf40..d0ab43b 100644 --- a/utils/httpRequest/goal.go +++ b/utils/httpRequest/feature_experimentation/goal.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/goal_test.go b/utils/httpRequest/feature_experimentation/goal_test.go similarity index 97% rename from utils/httpRequest/goal_test.go rename to utils/httpRequest/feature_experimentation/goal_test.go index c51acb6..497b8a2 100644 --- a/utils/httpRequest/goal_test.go +++ b/utils/httpRequest/feature_experimentation/goal_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/main_test.go b/utils/httpRequest/feature_experimentation/main_test.go similarity index 75% rename from utils/httpRequest/main_test.go rename to utils/httpRequest/feature_experimentation/main_test.go index 191d18e..b988bab 100644 --- a/utils/httpRequest/main_test.go +++ b/utils/httpRequest/feature_experimentation/main_test.go @@ -1,9 +1,11 @@ -package httprequest +package feature_experimentation import ( "testing" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_ "github.com/flagship-io/flagship/utils/mock_function" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" ) @@ -19,7 +21,7 @@ func TestMain(m *testing.M) { mockfunction.APITargetingKey() mockfunction.APIVariationGroup() mockfunction.APIVariation() - mockfunction.APIToken() + mockfunction_.APIToken() mockfunction.APIUser() mockfunction.APIPanic() mockfunction.Request() diff --git a/utils/httpRequest/panic.go b/utils/httpRequest/feature_experimentation/panic.go similarity index 94% rename from utils/httpRequest/panic.go rename to utils/httpRequest/feature_experimentation/panic.go index 6a62740..1b445c2 100644 --- a/utils/httpRequest/panic.go +++ b/utils/httpRequest/feature_experimentation/panic.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/panic_test.go b/utils/httpRequest/feature_experimentation/panic_test.go similarity index 83% rename from utils/httpRequest/panic_test.go rename to utils/httpRequest/feature_experimentation/panic_test.go index 432bb47..15e07c4 100644 --- a/utils/httpRequest/panic_test.go +++ b/utils/httpRequest/feature_experimentation/panic_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/project.go b/utils/httpRequest/feature_experimentation/project.go similarity index 97% rename from utils/httpRequest/project.go rename to utils/httpRequest/feature_experimentation/project.go index 3aa0d3e..9ac54c9 100644 --- a/utils/httpRequest/project.go +++ b/utils/httpRequest/feature_experimentation/project.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/project_test.go b/utils/httpRequest/feature_experimentation/project_test.go similarity index 98% rename from utils/httpRequest/project_test.go rename to utils/httpRequest/feature_experimentation/project_test.go index 685d0f6..e191a9d 100644 --- a/utils/httpRequest/project_test.go +++ b/utils/httpRequest/feature_experimentation/project_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/request.go b/utils/httpRequest/feature_experimentation/request.go similarity index 99% rename from utils/httpRequest/request.go rename to utils/httpRequest/feature_experimentation/request.go index de469d0..773aae7 100644 --- a/utils/httpRequest/request.go +++ b/utils/httpRequest/feature_experimentation/request.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "bytes" diff --git a/utils/httpRequest/request_test.go b/utils/httpRequest/feature_experimentation/request_test.go similarity index 97% rename from utils/httpRequest/request_test.go rename to utils/httpRequest/feature_experimentation/request_test.go index b458d9f..a8fd8c2 100644 --- a/utils/httpRequest/request_test.go +++ b/utils/httpRequest/feature_experimentation/request_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/targeting_key.go b/utils/httpRequest/feature_experimentation/targeting_key.go similarity index 97% rename from utils/httpRequest/targeting_key.go rename to utils/httpRequest/feature_experimentation/targeting_key.go index 269011e..d3fc1d0 100644 --- a/utils/httpRequest/targeting_key.go +++ b/utils/httpRequest/feature_experimentation/targeting_key.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/targeting_key_test.go b/utils/httpRequest/feature_experimentation/targeting_key_test.go similarity index 98% rename from utils/httpRequest/targeting_key_test.go rename to utils/httpRequest/feature_experimentation/targeting_key_test.go index 50ca5f8..0c268b6 100644 --- a/utils/httpRequest/targeting_key_test.go +++ b/utils/httpRequest/feature_experimentation/targeting_key_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/token.go b/utils/httpRequest/feature_experimentation/token.go similarity index 97% rename from utils/httpRequest/token.go rename to utils/httpRequest/feature_experimentation/token.go index 151378b..88861e5 100644 --- a/utils/httpRequest/token.go +++ b/utils/httpRequest/feature_experimentation/token.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "encoding/json" diff --git a/utils/httpRequest/token_test.go b/utils/httpRequest/feature_experimentation/token_test.go similarity index 95% rename from utils/httpRequest/token_test.go rename to utils/httpRequest/feature_experimentation/token_test.go index 697a523..7de1ca6 100644 --- a/utils/httpRequest/token_test.go +++ b/utils/httpRequest/feature_experimentation/token_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/user.go b/utils/httpRequest/feature_experimentation/user.go similarity index 96% rename from utils/httpRequest/user.go rename to utils/httpRequest/feature_experimentation/user.go index bbe1bf8..3415927 100644 --- a/utils/httpRequest/user.go +++ b/utils/httpRequest/feature_experimentation/user.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/user_test.go b/utils/httpRequest/feature_experimentation/user_test.go similarity index 95% rename from utils/httpRequest/user_test.go rename to utils/httpRequest/feature_experimentation/user_test.go index 113aef7..a3f7f2f 100644 --- a/utils/httpRequest/user_test.go +++ b/utils/httpRequest/feature_experimentation/user_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/variation.go b/utils/httpRequest/feature_experimentation/variation.go similarity index 98% rename from utils/httpRequest/variation.go rename to utils/httpRequest/feature_experimentation/variation.go index 5a6da0e..7f57fad 100644 --- a/utils/httpRequest/variation.go +++ b/utils/httpRequest/feature_experimentation/variation.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/variation_group.go b/utils/httpRequest/feature_experimentation/variation_group.go similarity index 98% rename from utils/httpRequest/variation_group.go rename to utils/httpRequest/feature_experimentation/variation_group.go index f8d3e98..d9fad5f 100644 --- a/utils/httpRequest/variation_group.go +++ b/utils/httpRequest/feature_experimentation/variation_group.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "net/http" diff --git a/utils/httpRequest/variation_group_test.go b/utils/httpRequest/feature_experimentation/variation_group_test.go similarity index 98% rename from utils/httpRequest/variation_group_test.go rename to utils/httpRequest/feature_experimentation/variation_group_test.go index 2616e9d..cdf84d4 100644 --- a/utils/httpRequest/variation_group_test.go +++ b/utils/httpRequest/feature_experimentation/variation_group_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/httpRequest/variation_test.go b/utils/httpRequest/feature_experimentation/variation_test.go similarity index 98% rename from utils/httpRequest/variation_test.go rename to utils/httpRequest/feature_experimentation/variation_test.go index f8f0708..aea29f0 100644 --- a/utils/httpRequest/variation_test.go +++ b/utils/httpRequest/feature_experimentation/variation_test.go @@ -1,4 +1,4 @@ -package httprequest +package feature_experimentation import ( "testing" diff --git a/utils/mock_function/campaign.go b/utils/mock_function/feature_experimentation/campaign.go similarity index 99% rename from utils/mock_function/campaign.go rename to utils/mock_function/feature_experimentation/campaign.go index e06feec..f40d864 100644 --- a/utils/mock_function/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/flag.go b/utils/mock_function/feature_experimentation/flag.go similarity index 98% rename from utils/mock_function/flag.go rename to utils/mock_function/feature_experimentation/flag.go index 8b209e1..efd61f8 100644 --- a/utils/mock_function/flag.go +++ b/utils/mock_function/feature_experimentation/flag.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/goal.go b/utils/mock_function/feature_experimentation/goal.go similarity index 98% rename from utils/mock_function/goal.go rename to utils/mock_function/feature_experimentation/goal.go index 4164a5b..13059fe 100644 --- a/utils/mock_function/goal.go +++ b/utils/mock_function/feature_experimentation/goal.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/panic.go b/utils/mock_function/feature_experimentation/panic.go similarity index 94% rename from utils/mock_function/panic.go rename to utils/mock_function/feature_experimentation/panic.go index f1f3e54..8f421d4 100644 --- a/utils/mock_function/panic.go +++ b/utils/mock_function/feature_experimentation/panic.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/project.go b/utils/mock_function/feature_experimentation/project.go similarity index 98% rename from utils/mock_function/project.go rename to utils/mock_function/feature_experimentation/project.go index 73aa169..1f9af41 100644 --- a/utils/mock_function/project.go +++ b/utils/mock_function/feature_experimentation/project.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/request.go b/utils/mock_function/feature_experimentation/request.go similarity index 96% rename from utils/mock_function/request.go rename to utils/mock_function/feature_experimentation/request.go index c5f26a3..6c48c03 100644 --- a/utils/mock_function/request.go +++ b/utils/mock_function/feature_experimentation/request.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/targeting_key.go b/utils/mock_function/feature_experimentation/targeting_key.go similarity index 98% rename from utils/mock_function/targeting_key.go rename to utils/mock_function/feature_experimentation/targeting_key.go index 2901747..f43b64c 100644 --- a/utils/mock_function/targeting_key.go +++ b/utils/mock_function/feature_experimentation/targeting_key.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/user.go b/utils/mock_function/feature_experimentation/user.go similarity index 98% rename from utils/mock_function/user.go rename to utils/mock_function/feature_experimentation/user.go index 826abb8..637eade 100644 --- a/utils/mock_function/user.go +++ b/utils/mock_function/feature_experimentation/user.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/variation.go b/utils/mock_function/feature_experimentation/variation.go similarity index 99% rename from utils/mock_function/variation.go rename to utils/mock_function/feature_experimentation/variation.go index 57c6dd8..96b5723 100644 --- a/utils/mock_function/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" diff --git a/utils/mock_function/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go similarity index 99% rename from utils/mock_function/variation_group.go rename to utils/mock_function/feature_experimentation/variation_group.go index fc8cdb3..8c0514b 100644 --- a/utils/mock_function/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -1,4 +1,4 @@ -package mockfunction +package feature_experimentation import ( "net/http" From 08044a47b6dc37092b114261f4bd3e14b24cbb37 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 8 Mar 2024 16:16:18 +0100 Subject: [PATCH 03/48] add refresh token functions --- cmd/configuration/use.go | 6 +-- models/token.go | 8 +++- utils/config/config.go | 9 +++-- .../feature_experimentation/request.go | 37 ++++++++++++++++-- .../feature_experimentation/request_test.go | 2 + .../feature_experimentation/token.go | 39 +++++++++++++++---- 6 files changed, 84 insertions(+), 17 deletions(-) diff --git a/cmd/configuration/use.go b/cmd/configuration/use.go index e844912..ea8774a 100644 --- a/cmd/configuration/use.go +++ b/cmd/configuration/use.go @@ -38,17 +38,17 @@ var useCmd = &cobra.Command{ config.SelectConfiguration(ConfigurationName) config.SetOptionalsDefault(grantType, scope, expiration) - token, err := httprequest.HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), grantType, scope, expiration) + authenticationResponse, err := httprequest.HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), grantType, scope, expiration) if err != nil { log.Fatalf("%s", err) return } - if token == "" { + if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") return } else { - config.WriteToken(ConfigurationName, token) + config.WriteToken(ConfigurationName, authenticationResponse) fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") } diff --git a/models/token.go b/models/token.go index b3136e9..e343206 100644 --- a/models/token.go +++ b/models/token.go @@ -12,9 +12,15 @@ type TokenResponse struct { RefreshToken string `json:"refresh_token"` } -type TokenRequest struct { +type ClientCredentialsRequest struct { GrantType string `json:"grant_type"` Scope string `json:"scope"` ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"` } + +type RefreshTokenRequest struct { + GrantType string `json:"grant_type"` + ClientID string `json:"client_id"` + RefreshToken string `json:"refresh_token"` +} diff --git a/utils/config/config.go b/utils/config/config.go index 709a4d0..e5d323a 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -10,6 +10,7 @@ import ( "path/filepath" "regexp" + "github.com/flagship-io/flagship/models" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -158,7 +159,7 @@ func ReadCredentialsFromFile(configurationFile string) { } } -func WriteToken(configurationName, token string) { +func WriteToken(configurationName string, authenticationResponse models.TokenResponse) { configFilepath := SetPathForConfigName(configurationName) viper.SetConfigFile(configFilepath) @@ -167,7 +168,8 @@ func WriteToken(configurationName, token string) { log.Fatalf("error occurred: %v", err) } - viper.Set("token", token) + viper.Set("token", authenticationResponse.AccessToken) + viper.Set("refresh_token", authenticationResponse.RefreshToken) viper.Set("current_used_configuration", nil) Unset("current_used_configuration") @@ -182,6 +184,7 @@ func SetViperMock() { viper.GetViper().Set("account_environment_id", "account_environment_id") viper.GetViper().Set("client_id", "client_id") viper.GetViper().Set("client_secret", "client_secret") - viper.GetViper().Set("token", "token") + viper.GetViper().Set("token", "access_token") + viper.GetViper().Set("refresh_token", "refresh_token") viper.GetViper().Set("output_format", "json") } diff --git a/utils/httpRequest/feature_experimentation/request.go b/utils/httpRequest/feature_experimentation/request.go index 773aae7..d431820 100644 --- a/utils/httpRequest/feature_experimentation/request.go +++ b/utils/httpRequest/feature_experimentation/request.go @@ -35,16 +35,47 @@ func regenerateToken(configName string) { ex = config.Expiration } - token, err := HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), gt, sc, ex) + authenticationResponse, err := HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), gt, sc, ex) if err != nil { log.Fatalf("%s", err) } - if token == "" { + if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } else { fmt.Fprintln(os.Stdout, "Token generated successfully") - config.WriteToken(configName, token) + config.WriteToken(configName, authenticationResponse) + } +} + +func regenerateToken_(configName string) { + gt := viper.GetString("grant_type") + sc := viper.GetString("scope") + ex := viper.GetInt("expiration") + + if gt == "" { + gt = config.GrantType + } + + if sc == "" { + sc = config.Scope + } + + if ex == 0 { + ex = config.Expiration + } + + authenticationResponse, err := HTTPRefreshToken(viper.GetString("client_id"), viper.GetString("refresh_token")) + fmt.Println(authenticationResponse) + + if err != nil { + log.Fatalf("%s", err) + } + if authenticationResponse.AccessToken == "" { + log.Fatal("client_id or client_secret not valid") + } else { + fmt.Fprintln(os.Stdout, "Token generated successfully") + config.WriteToken(configName, authenticationResponse) } } diff --git a/utils/httpRequest/feature_experimentation/request_test.go b/utils/httpRequest/feature_experimentation/request_test.go index a8fd8c2..dda24da 100644 --- a/utils/httpRequest/feature_experimentation/request_test.go +++ b/utils/httpRequest/feature_experimentation/request_test.go @@ -58,5 +58,7 @@ func TestRegenerateToken(t *testing.T) { regenerateToken("test_configuration") assert.Equal(t, viper.IsSet("token"), true) + assert.Equal(t, viper.IsSet("refresh_token"), true) assert.Equal(t, viper.GetString("token"), "access_token") + assert.Equal(t, viper.GetString("refresh_token"), "refresh_token") } diff --git a/utils/httpRequest/feature_experimentation/token.go b/utils/httpRequest/feature_experimentation/token.go index 88861e5..21d248b 100644 --- a/utils/httpRequest/feature_experimentation/token.go +++ b/utils/httpRequest/feature_experimentation/token.go @@ -10,30 +10,55 @@ import ( "github.com/spf13/viper" ) -func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expiration int) (string, error) { +func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expiration int) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse - authRequest := models.TokenRequest{ + authRequest := models.ClientCredentialsRequest{ ClientID: client_id, ClientSecret: client_secret, Scope: scope, - GrantType: grant_type, + GrantType: "client_credentials", } authRequestJSON, err := json.Marshal(authRequest) if err != nil { - return "", err + return models.TokenResponse{}, err } respBody, err := HTTPRequest(http.MethodPost, utils.GetHostAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) if err != nil { - return "", err + return models.TokenResponse{}, err } err = json.Unmarshal(respBody, &authenticationResponse) if err != nil { - return "", err + return models.TokenResponse{}, err } - return authenticationResponse.AccessToken, err + return authenticationResponse, err +} + +func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.RefreshTokenRequest{ + ClientID: client_id, + GrantType: "refresh_token", + RefreshToken: refresh_token, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostAuth()+"/"+viper.GetString("account_id")+"/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err } func HTTPCheckToken(token string) (models.Token, error) { From da721d742970bce59e3f6761be7fcad8c65df15b Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 11 Mar 2024 17:22:39 +0100 Subject: [PATCH 04/48] reorganizing pakcages --- .github/workflows/ci.yml | 4 +- cmd/configuration/use.go | 2 +- .../analyze/flag/create.go | 2 +- .../analyze/flag/list.go | 2 +- .../campaign/create.go | 2 +- .../campaign/delete.go | 2 +- cmd/feature_experimentation/campaign/edit.go | 2 +- cmd/feature_experimentation/campaign/get.go | 2 +- cmd/feature_experimentation/campaign/list.go | 2 +- .../campaign/switch.go | 2 +- cmd/feature_experimentation/flag/create.go | 2 +- cmd/feature_experimentation/flag/delete.go | 2 +- cmd/feature_experimentation/flag/edit.go | 2 +- cmd/feature_experimentation/flag/get.go | 2 +- cmd/feature_experimentation/flag/list.go | 2 +- cmd/feature_experimentation/goal/create.go | 2 +- cmd/feature_experimentation/goal/delete.go | 2 +- cmd/feature_experimentation/goal/edit.go | 2 +- cmd/feature_experimentation/goal/get.go | 2 +- cmd/feature_experimentation/goal/list.go | 2 +- cmd/feature_experimentation/panic/panic.go | 2 +- cmd/feature_experimentation/project/create.go | 2 +- cmd/feature_experimentation/project/delete.go | 2 +- cmd/feature_experimentation/project/edit.go | 2 +- cmd/feature_experimentation/project/get.go | 2 +- cmd/feature_experimentation/project/list.go | 2 +- cmd/feature_experimentation/project/switch.go | 2 +- cmd/feature_experimentation/resource/load.go | 13 +++--- .../targeting_key/create.go | 2 +- .../targeting_key/delete.go | 2 +- .../targeting_key/edit.go | 2 +- .../targeting_key/get.go | 2 +- .../targeting_key/list.go | 2 +- cmd/feature_experimentation/user/create.go | 2 +- cmd/feature_experimentation/user/delete.go | 2 +- cmd/feature_experimentation/user/edit.go | 2 +- cmd/feature_experimentation/user/list.go | 2 +- .../variation/create.go | 2 +- .../variation/delete.go | 2 +- cmd/feature_experimentation/variation/edit.go | 2 +- cmd/feature_experimentation/variation/get.go | 2 +- cmd/feature_experimentation/variation/list.go | 2 +- .../variation_group/create.go | 2 +- .../variation_group/delete.go | 2 +- .../variation_group/edit.go | 2 +- .../variation_group/get.go | 2 +- .../variation_group/list.go | 2 +- cmd/root.go | 4 +- cmd/token/info.go | 2 +- cmd/token/token_test.go | 11 ----- .../feature_experimentation/campaign.go | 45 ------------------ .../feature_experimentation/flag.go | 30 ------------ .../feature_experimentation/goal.go | 30 ------------ .../feature_experimentation/project.go | 45 ------------------ .../feature_experimentation/targeting_key.go | 30 ------------ .../feature_experimentation/user.go | 23 ---------- .../feature_experimentation/variation.go | 30 ------------ .../variation_group.go | 30 ------------ .../feature_experimentation/campaign.go | 46 +++++++++++++++++++ .../feature_experimentation/campaign_test.go | 0 .../feature_experimentation/flag.go | 31 +++++++++++++ .../feature_experimentation/flag_test.go | 0 .../feature_experimentation/goal.go | 31 +++++++++++++ .../feature_experimentation/goal_test.go | 0 .../feature_experimentation/main_test.go | 3 -- .../feature_experimentation/panic.go | 3 +- .../feature_experimentation/panic_test.go | 0 .../feature_experimentation/project.go | 46 +++++++++++++++++++ .../feature_experimentation/project_test.go | 0 .../feature_experimentation/targeting_key.go | 31 +++++++++++++ .../targeting_key_test.go | 0 .../feature_experimentation/user.go | 24 ++++++++++ .../feature_experimentation/user_test.go | 0 .../feature_experimentation/variation.go | 31 +++++++++++++ .../variation_group.go | 31 +++++++++++++ .../variation_group_test.go | 0 .../feature_experimentation/variation_test.go | 0 utils/http_request/main_test.go | 19 ++++++++ .../request.go | 2 +- .../request_test.go | 2 +- .../token.go | 2 +- .../token_test.go | 5 +- .../{feature_experimentation => }/request.go | 2 +- 83 files changed, 356 insertions(+), 340 deletions(-) delete mode 100644 utils/httpRequest/feature_experimentation/campaign.go delete mode 100644 utils/httpRequest/feature_experimentation/flag.go delete mode 100644 utils/httpRequest/feature_experimentation/goal.go delete mode 100644 utils/httpRequest/feature_experimentation/project.go delete mode 100644 utils/httpRequest/feature_experimentation/targeting_key.go delete mode 100644 utils/httpRequest/feature_experimentation/user.go delete mode 100644 utils/httpRequest/feature_experimentation/variation.go delete mode 100644 utils/httpRequest/feature_experimentation/variation_group.go create mode 100644 utils/http_request/feature_experimentation/campaign.go rename utils/{httpRequest => http_request}/feature_experimentation/campaign_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/flag.go rename utils/{httpRequest => http_request}/feature_experimentation/flag_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/goal.go rename utils/{httpRequest => http_request}/feature_experimentation/goal_test.go (100%) rename utils/{httpRequest => http_request}/feature_experimentation/main_test.go (81%) rename utils/{httpRequest => http_request}/feature_experimentation/panic.go (57%) rename utils/{httpRequest => http_request}/feature_experimentation/panic_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/project.go rename utils/{httpRequest => http_request}/feature_experimentation/project_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/targeting_key.go rename utils/{httpRequest => http_request}/feature_experimentation/targeting_key_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/user.go rename utils/{httpRequest => http_request}/feature_experimentation/user_test.go (100%) create mode 100644 utils/http_request/feature_experimentation/variation.go create mode 100644 utils/http_request/feature_experimentation/variation_group.go rename utils/{httpRequest => http_request}/feature_experimentation/variation_group_test.go (100%) rename utils/{httpRequest => http_request}/feature_experimentation/variation_test.go (100%) create mode 100644 utils/http_request/main_test.go rename utils/{httpRequest/feature_experimentation => http_request}/request.go (99%) rename utils/{httpRequest/feature_experimentation => http_request}/request_test.go (97%) rename utils/{httpRequest/feature_experimentation => http_request}/token.go (98%) rename utils/{httpRequest/feature_experimentation => http_request}/token_test.go (81%) rename utils/mock_function/{feature_experimentation => }/request.go (96%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 979b3d4..4f023d1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,9 +15,9 @@ jobs: - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Run tests - run: go test -race `go list ./... | grep -v cmd/analyze/code-samples | grep -v cmd/configuration | grep -v utils/httpRequest` -coverprofile cover.out.tmp + run: go test -race `go list ./... | grep -v cmd/analyze/code-samples | grep -v cmd/configuration | grep -v utils/http_request` -coverprofile cover.out.tmp - name: Removes mocks from tests - run: cat cover.out.tmp | grep -v "mock_\|cmd/analyze/code-samples-example|cmd/configuration|utils/httpRequest" > cover.out + run: cat cover.out.tmp | grep -v "mock_\|cmd/analyze/code-samples-example|cmd/configuration|utils/http_request" > cover.out - uses: codecov/codecov-action@v2 with: file: ./cover.out diff --git a/cmd/configuration/use.go b/cmd/configuration/use.go index ea8774a..446cf7d 100644 --- a/cmd/configuration/use.go +++ b/cmd/configuration/use.go @@ -9,7 +9,7 @@ import ( "slices" "github.com/flagship-io/flagship/utils/config" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/analyze/flag/create.go b/cmd/feature_experimentation/analyze/flag/create.go index c4639ad..a4d1617 100644 --- a/cmd/feature_experimentation/analyze/flag/create.go +++ b/cmd/feature_experimentation/analyze/flag/create.go @@ -14,7 +14,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/rodaine/table" "github.com/spf13/cobra" "golang.org/x/exp/slices" diff --git a/cmd/feature_experimentation/analyze/flag/list.go b/cmd/feature_experimentation/analyze/flag/list.go index 0b879ea..8869728 100644 --- a/cmd/feature_experimentation/analyze/flag/list.go +++ b/cmd/feature_experimentation/analyze/flag/list.go @@ -12,7 +12,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/kyokomi/emoji/v2" "github.com/rodaine/table" "github.com/spf13/cobra" diff --git a/cmd/feature_experimentation/campaign/create.go b/cmd/feature_experimentation/campaign/create.go index 755e0d4..a79f642 100644 --- a/cmd/feature_experimentation/campaign/create.go +++ b/cmd/feature_experimentation/campaign/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go index db565bb..f481e0d 100644 --- a/cmd/feature_experimentation/campaign/delete.go +++ b/cmd/feature_experimentation/campaign/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go index eafc87d..53ec30f 100644 --- a/cmd/feature_experimentation/campaign/edit.go +++ b/cmd/feature_experimentation/campaign/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/campaign/get.go b/cmd/feature_experimentation/campaign/get.go index fea80f5..f9ddc60 100644 --- a/cmd/feature_experimentation/campaign/get.go +++ b/cmd/feature_experimentation/campaign/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/campaign/list.go b/cmd/feature_experimentation/campaign/list.go index b9e2ff4..5f877b6 100644 --- a/cmd/feature_experimentation/campaign/list.go +++ b/cmd/feature_experimentation/campaign/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go index d79a400..219b785 100644 --- a/cmd/feature_experimentation/campaign/switch.go +++ b/cmd/feature_experimentation/campaign/switch.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/create.go b/cmd/feature_experimentation/flag/create.go index 9f48262..93f917c 100644 --- a/cmd/feature_experimentation/flag/create.go +++ b/cmd/feature_experimentation/flag/create.go @@ -9,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/delete.go b/cmd/feature_experimentation/flag/delete.go index 437aaa9..f588ab7 100644 --- a/cmd/feature_experimentation/flag/delete.go +++ b/cmd/feature_experimentation/flag/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/edit.go b/cmd/feature_experimentation/flag/edit.go index 03f5182..ef17017 100644 --- a/cmd/feature_experimentation/flag/edit.go +++ b/cmd/feature_experimentation/flag/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/get.go b/cmd/feature_experimentation/flag/get.go index ba5ed95..655749d 100644 --- a/cmd/feature_experimentation/flag/get.go +++ b/cmd/feature_experimentation/flag/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/flag/list.go b/cmd/feature_experimentation/flag/list.go index 8fc5e02..e0fbe8d 100644 --- a/cmd/feature_experimentation/flag/list.go +++ b/cmd/feature_experimentation/flag/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/goal/create.go b/cmd/feature_experimentation/goal/create.go index 1e07326..4b8a22d 100644 --- a/cmd/feature_experimentation/goal/create.go +++ b/cmd/feature_experimentation/goal/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/delete.go b/cmd/feature_experimentation/goal/delete.go index 8c2f9c1..12f0dc7 100644 --- a/cmd/feature_experimentation/goal/delete.go +++ b/cmd/feature_experimentation/goal/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/edit.go b/cmd/feature_experimentation/goal/edit.go index ea80ca1..68a868d 100644 --- a/cmd/feature_experimentation/goal/edit.go +++ b/cmd/feature_experimentation/goal/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/goal/get.go b/cmd/feature_experimentation/goal/get.go index ad7a24f..80af134 100644 --- a/cmd/feature_experimentation/goal/get.go +++ b/cmd/feature_experimentation/goal/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/goal/list.go b/cmd/feature_experimentation/goal/list.go index 2637fba..2983cf8 100644 --- a/cmd/feature_experimentation/goal/list.go +++ b/cmd/feature_experimentation/goal/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/panic/panic.go b/cmd/feature_experimentation/panic/panic.go index 62b61e2..6366be0 100644 --- a/cmd/feature_experimentation/panic/panic.go +++ b/cmd/feature_experimentation/panic/panic.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/create.go b/cmd/feature_experimentation/project/create.go index ebd5daa..b07ecbf 100644 --- a/cmd/feature_experimentation/project/create.go +++ b/cmd/feature_experimentation/project/create.go @@ -9,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/delete.go b/cmd/feature_experimentation/project/delete.go index b7f50ad..548d2fa 100644 --- a/cmd/feature_experimentation/project/delete.go +++ b/cmd/feature_experimentation/project/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/edit.go b/cmd/feature_experimentation/project/edit.go index 7a864c4..ed27963 100644 --- a/cmd/feature_experimentation/project/edit.go +++ b/cmd/feature_experimentation/project/edit.go @@ -9,7 +9,7 @@ import ( "log" "github.com/flagship-io/flagship/models" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/get.go b/cmd/feature_experimentation/project/get.go index 5b40066..203d27a 100644 --- a/cmd/feature_experimentation/project/get.go +++ b/cmd/feature_experimentation/project/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/project/list.go b/cmd/feature_experimentation/project/list.go index 1dcd860..bf769b3 100644 --- a/cmd/feature_experimentation/project/list.go +++ b/cmd/feature_experimentation/project/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/project/switch.go b/cmd/feature_experimentation/project/switch.go index 44ed0df..331eadd 100644 --- a/cmd/feature_experimentation/project/switch.go +++ b/cmd/feature_experimentation/project/switch.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 4c988fa..9d74523 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -17,7 +17,8 @@ import ( "github.com/d5/tengo/v2" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" + featureexp "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -35,7 +36,7 @@ type ResourceData struct { } func (f *ProjectData) Save(data string) ([]byte, error) { - return httprequest.HTTPCreateProject([]byte(data)) + return featureexp.HTTPCreateProject([]byte(data)) } type CampaignData struct { @@ -48,7 +49,7 @@ type CampaignData struct { } func (f *CampaignData) Save(data string) ([]byte, error) { - return httprequest.HTTPCreateCampaign(data) + return featureexp.HTTPCreateCampaign(data) } type FlagData struct { @@ -56,7 +57,7 @@ type FlagData struct { } func (f *FlagData) Save(data string) ([]byte, error) { - return httprequest.HTTPCreateFlag(data) + return featureexp.HTTPCreateFlag(data) } type GoalData struct { @@ -64,7 +65,7 @@ type GoalData struct { } func (f *GoalData) Save(data string) ([]byte, error) { - return httprequest.HTTPCreateGoal(data) + return featureexp.HTTPCreateGoal(data) } type TargetingKeysData struct { @@ -72,7 +73,7 @@ type TargetingKeysData struct { } func (f *TargetingKeysData) Save(data string) ([]byte, error) { - return httprequest.HTTPCreateTargetingKey(data) + return featureexp.HTTPCreateTargetingKey(data) } type VariationGroupData struct { diff --git a/cmd/feature_experimentation/targeting_key/create.go b/cmd/feature_experimentation/targeting_key/create.go index 16eed85..0ef4872 100644 --- a/cmd/feature_experimentation/targeting_key/create.go +++ b/cmd/feature_experimentation/targeting_key/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/delete.go b/cmd/feature_experimentation/targeting_key/delete.go index 1c62173..0805630 100644 --- a/cmd/feature_experimentation/targeting_key/delete.go +++ b/cmd/feature_experimentation/targeting_key/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/edit.go b/cmd/feature_experimentation/targeting_key/edit.go index 9275190..1e60e08 100644 --- a/cmd/feature_experimentation/targeting_key/edit.go +++ b/cmd/feature_experimentation/targeting_key/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/targeting_key/get.go b/cmd/feature_experimentation/targeting_key/get.go index 1c389cd..08f4260 100644 --- a/cmd/feature_experimentation/targeting_key/get.go +++ b/cmd/feature_experimentation/targeting_key/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/targeting_key/list.go b/cmd/feature_experimentation/targeting_key/list.go index 75c13d5..dc0e321 100644 --- a/cmd/feature_experimentation/targeting_key/list.go +++ b/cmd/feature_experimentation/targeting_key/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/user/create.go b/cmd/feature_experimentation/user/create.go index 69f4161..aea2ed6 100644 --- a/cmd/feature_experimentation/user/create.go +++ b/cmd/feature_experimentation/user/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/delete.go b/cmd/feature_experimentation/user/delete.go index 8120b26..7d41356 100644 --- a/cmd/feature_experimentation/user/delete.go +++ b/cmd/feature_experimentation/user/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/edit.go b/cmd/feature_experimentation/user/edit.go index 5167a8c..dcbe16d 100644 --- a/cmd/feature_experimentation/user/edit.go +++ b/cmd/feature_experimentation/user/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/user/list.go b/cmd/feature_experimentation/user/list.go index 333fe05..fe60d3d 100644 --- a/cmd/feature_experimentation/user/list.go +++ b/cmd/feature_experimentation/user/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation/create.go b/cmd/feature_experimentation/variation/create.go index 982cc96..5f2a146 100644 --- a/cmd/feature_experimentation/variation/create.go +++ b/cmd/feature_experimentation/variation/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index 6ef714b..b2aff80 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/edit.go b/cmd/feature_experimentation/variation/edit.go index a39434b..e966d5a 100644 --- a/cmd/feature_experimentation/variation/edit.go +++ b/cmd/feature_experimentation/variation/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation/get.go b/cmd/feature_experimentation/variation/get.go index 4c8d2d0..6b04d1a 100644 --- a/cmd/feature_experimentation/variation/get.go +++ b/cmd/feature_experimentation/variation/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation/list.go b/cmd/feature_experimentation/variation/list.go index c9ca89f..c888113 100644 --- a/cmd/feature_experimentation/variation/list.go +++ b/cmd/feature_experimentation/variation/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation_group/create.go b/cmd/feature_experimentation/variation_group/create.go index 9388f36..cb25909 100644 --- a/cmd/feature_experimentation/variation_group/create.go +++ b/cmd/feature_experimentation/variation_group/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go index b4ee947..f1bf03a 100644 --- a/cmd/feature_experimentation/variation_group/delete.go +++ b/cmd/feature_experimentation/variation_group/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/edit.go b/cmd/feature_experimentation/variation_group/edit.go index 6f6b027..db939c5 100644 --- a/cmd/feature_experimentation/variation_group/edit.go +++ b/cmd/feature_experimentation/variation_group/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/variation_group/get.go b/cmd/feature_experimentation/variation_group/get.go index 019bfa3..ca46419 100644 --- a/cmd/feature_experimentation/variation_group/get.go +++ b/cmd/feature_experimentation/variation_group/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/feature_experimentation/variation_group/list.go b/cmd/feature_experimentation/variation_group/list.go index bc07195..0a7db05 100644 --- a/cmd/feature_experimentation/variation_group/list.go +++ b/cmd/feature_experimentation/variation_group/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/root.go b/cmd/root.go index 4f690a3..5903a0d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -13,7 +13,7 @@ import ( "github.com/flagship-io/flagship/cmd/version" "github.com/flagship-io/flagship/utils/config" - httprequest_fe "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -66,7 +66,7 @@ func init() { rootCmd.PersistentFlags().StringVarP(&cmdToken, "token", "t", "", "access token to manage flagship resources") rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "f", config.OutputFormat, "output format for the get and list subcommands for flagship resources. Only 3 format are possible: table, json, json-pretty") - rootCmd.PersistentFlags().StringVarP(&httprequest_fe.UserAgent, "user-agent", "u", config.DefaultUserAgent, "custom user agent") + rootCmd.PersistentFlags().StringVarP(&httprequest.UserAgent, "user-agent", "u", config.DefaultUserAgent, "custom user agent") viper.BindPFlag("token", rootCmd.PersistentFlags().Lookup("token")) viper.BindPFlag("output_format", rootCmd.PersistentFlags().Lookup("output-format")) diff --git a/cmd/token/info.go b/cmd/token/info.go index bf5e7ac..ca49691 100644 --- a/cmd/token/info.go +++ b/cmd/token/info.go @@ -8,7 +8,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/httpRequest/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) diff --git a/cmd/token/token_test.go b/cmd/token/token_test.go index 4268d3e..d43e33e 100644 --- a/cmd/token/token_test.go +++ b/cmd/token/token_test.go @@ -1,7 +1,6 @@ package token import ( - "encoding/json" "testing" "github.com/flagship-io/flagship/models" @@ -31,13 +30,3 @@ func TestTokenHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TokenCmd, "--help") assert.Contains(t, output, "Manage your token\n") } - -func TestTokenInfoCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(TokenCmd, "info") - - err := json.Unmarshal([]byte(output), &testToken) - - assert.Nil(t, err) - - assert.Equal(t, mockfunction.TestToken, testToken) -} diff --git a/utils/httpRequest/feature_experimentation/campaign.go b/utils/httpRequest/feature_experimentation/campaign.go deleted file mode 100644 index 504e8b4..0000000 --- a/utils/httpRequest/feature_experimentation/campaign.go +++ /dev/null @@ -1,45 +0,0 @@ -package feature_experimentation - -import ( - "encoding/json" - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListCampaign() ([]models.Campaign, error) { - return HTTPGetAllPages[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns") -} - -func HTTPGetCampaign(id string) (models.Campaign, error) { - return HTTPGetItem[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + id) -} - -func HTTPCreateCampaign(data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", []byte(data)) -} - -func HTTPEditCampaign(id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, []byte(data)) -} - -func HTTPSwitchCampaign(id, state string) error { - campaignSwitchRequest := models.CampaignSwitchRequest{ - State: state, - } - - campaignSwitchRequestJSON, err := json.Marshal(campaignSwitchRequest) - if err != nil { - return err - } - - _, err = HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) - return err -} - -func HTTPDeleteCampaign(id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/flag.go b/utils/httpRequest/feature_experimentation/flag.go deleted file mode 100644 index dcaf44e..0000000 --- a/utils/httpRequest/feature_experimentation/flag.go +++ /dev/null @@ -1,30 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListFlag() ([]models.Flag, error) { - return HTTPGetAllPages[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags") -} - -func HTTPGetFlag(id string) (models.Flag, error) { - return HTTPGetItem[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags/" + id) -} - -func HTTPCreateFlag(data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", []byte(data)) -} - -func HTTPEditFlag(id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, []byte(data)) -} - -func HTTPDeleteFlag(id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/goal.go b/utils/httpRequest/feature_experimentation/goal.go deleted file mode 100644 index d0ab43b..0000000 --- a/utils/httpRequest/feature_experimentation/goal.go +++ /dev/null @@ -1,30 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListGoal() ([]models.Goal, error) { - return HTTPGetAllPages[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals") -} - -func HTTPGetGoal(id string) (models.Goal, error) { - return HTTPGetItem[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals/" + id) -} - -func HTTPCreateGoal(data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", []byte(data)) -} - -func HTTPEditGoal(id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, []byte(data)) -} - -func HTTPDeleteGoal(id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/project.go b/utils/httpRequest/feature_experimentation/project.go deleted file mode 100644 index 9ac54c9..0000000 --- a/utils/httpRequest/feature_experimentation/project.go +++ /dev/null @@ -1,45 +0,0 @@ -package feature_experimentation - -import ( - "encoding/json" - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListProject() ([]models.Project, error) { - return HTTPGetAllPages[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects") -} - -func HTTPGetProject(id string) (models.Project, error) { - return HTTPGetItem[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects/" + id) -} - -func HTTPCreateProject(data []byte) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", data) -} - -func HTTPEditProject(id string, data []byte) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, data) -} - -func HTTPSwitchProject(id, state string) error { - projectRequest := models.ProjectSwitchRequest{ - State: state, - } - - projectRequestJSON, err := json.Marshal(projectRequest) - if err != nil { - return err - } - - _, err = HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id+"/toggle", projectRequestJSON) - return err -} - -func HTTPDeleteProject(id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/targeting_key.go b/utils/httpRequest/feature_experimentation/targeting_key.go deleted file mode 100644 index d3fc1d0..0000000 --- a/utils/httpRequest/feature_experimentation/targeting_key.go +++ /dev/null @@ -1,30 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListTargetingKey() ([]models.TargetingKey, error) { - return HTTPGetAllPages[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys") -} - -func HTTPGetTargetingKey(id string) (models.TargetingKey, error) { - return HTTPGetItem[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys/" + id) -} - -func HTTPCreateTargetingKey(data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", []byte(data)) -} - -func HTTPEditTargetingKey(id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, []byte(data)) -} - -func HTTPDeleteTargetingKey(id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/user.go b/utils/httpRequest/feature_experimentation/user.go deleted file mode 100644 index 3415927..0000000 --- a/utils/httpRequest/feature_experimentation/user.go +++ /dev/null @@ -1,23 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - "net/url" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListUsers() ([]models.User, error) { - return HTTPGetAllPages[models.User](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/users") -} - -func HTTPBatchUpdateUsers(data string) ([]byte, error) { - return HTTPRequest(http.MethodPut, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", []byte(data)) -} - -func HTTPDeleteUsers(email string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/variation.go b/utils/httpRequest/feature_experimentation/variation.go deleted file mode 100644 index 7f57fad..0000000 --- a/utils/httpRequest/feature_experimentation/variation.go +++ /dev/null @@ -1,30 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return HTTPGetAllPages[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") -} - -func HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { - return HTTPGetItem[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) -} - -func HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) -} - -func HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) -} - -func HTTPDeleteVariation(campaignID, variationGroupID, id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) - return err -} diff --git a/utils/httpRequest/feature_experimentation/variation_group.go b/utils/httpRequest/feature_experimentation/variation_group.go deleted file mode 100644 index d9fad5f..0000000 --- a/utils/httpRequest/feature_experimentation/variation_group.go +++ /dev/null @@ -1,30 +0,0 @@ -package feature_experimentation - -import ( - "net/http" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { - return HTTPGetAllPages[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups") -} - -func HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { - return HTTPGetItem[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + id) -} - -func HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { - return HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) -} - -func HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { - return HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) -} - -func HTTPDeleteVariationGroup(campaignID, id string) error { - _, err := HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) - return err -} diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go new file mode 100644 index 0000000..24d29ca --- /dev/null +++ b/utils/http_request/feature_experimentation/campaign.go @@ -0,0 +1,46 @@ +package feature_experimentation + +import ( + "encoding/json" + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListCampaign() ([]models.Campaign, error) { + return httprequest.HTTPGetAllPages[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns") +} + +func HTTPGetCampaign(id string) (models.Campaign, error) { + return httprequest.HTTPGetItem[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + id) +} + +func HTTPCreateCampaign(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", []byte(data)) +} + +func HTTPEditCampaign(id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, []byte(data)) +} + +func HTTPSwitchCampaign(id, state string) error { + campaignSwitchRequest := models.CampaignSwitchRequest{ + State: state, + } + + campaignSwitchRequestJSON, err := json.Marshal(campaignSwitchRequest) + if err != nil { + return err + } + + _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + return err +} + +func HTTPDeleteCampaign(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/campaign_test.go b/utils/http_request/feature_experimentation/campaign_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/campaign_test.go rename to utils/http_request/feature_experimentation/campaign_test.go diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go new file mode 100644 index 0000000..d92637d --- /dev/null +++ b/utils/http_request/feature_experimentation/flag.go @@ -0,0 +1,31 @@ +package feature_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListFlag() ([]models.Flag, error) { + return httprequest.HTTPGetAllPages[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags") +} + +func HTTPGetFlag(id string) (models.Flag, error) { + return httprequest.HTTPGetItem[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags/" + id) +} + +func HTTPCreateFlag(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", []byte(data)) +} + +func HTTPEditFlag(id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, []byte(data)) +} + +func HTTPDeleteFlag(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/flag_test.go b/utils/http_request/feature_experimentation/flag_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/flag_test.go rename to utils/http_request/feature_experimentation/flag_test.go diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go new file mode 100644 index 0000000..e3d30cc --- /dev/null +++ b/utils/http_request/feature_experimentation/goal.go @@ -0,0 +1,31 @@ +package feature_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListGoal() ([]models.Goal, error) { + return httprequest.HTTPGetAllPages[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals") +} + +func HTTPGetGoal(id string) (models.Goal, error) { + return httprequest.HTTPGetItem[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals/" + id) +} + +func HTTPCreateGoal(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", []byte(data)) +} + +func HTTPEditGoal(id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, []byte(data)) +} + +func HTTPDeleteGoal(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/goal_test.go b/utils/http_request/feature_experimentation/goal_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/goal_test.go rename to utils/http_request/feature_experimentation/goal_test.go diff --git a/utils/httpRequest/feature_experimentation/main_test.go b/utils/http_request/feature_experimentation/main_test.go similarity index 81% rename from utils/httpRequest/feature_experimentation/main_test.go rename to utils/http_request/feature_experimentation/main_test.go index b988bab..fa626a1 100644 --- a/utils/httpRequest/feature_experimentation/main_test.go +++ b/utils/http_request/feature_experimentation/main_test.go @@ -3,7 +3,6 @@ package feature_experimentation import ( "testing" - mockfunction_ "github.com/flagship-io/flagship/utils/mock_function" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" @@ -21,9 +20,7 @@ func TestMain(m *testing.M) { mockfunction.APITargetingKey() mockfunction.APIVariationGroup() mockfunction.APIVariation() - mockfunction_.APIToken() mockfunction.APIUser() mockfunction.APIPanic() - mockfunction.Request() m.Run() } diff --git a/utils/httpRequest/feature_experimentation/panic.go b/utils/http_request/feature_experimentation/panic.go similarity index 57% rename from utils/httpRequest/feature_experimentation/panic.go rename to utils/http_request/feature_experimentation/panic.go index 1b445c2..8247caa 100644 --- a/utils/httpRequest/feature_experimentation/panic.go +++ b/utils/http_request/feature_experimentation/panic.go @@ -6,6 +6,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" ) @@ -14,6 +15,6 @@ func HTTPUpdatePanic(panicStatus string) ([]byte, error) { if err != nil { return nil, err } - resp, err := HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", panicRequestJSON) + resp, err := httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", panicRequestJSON) return resp, err } diff --git a/utils/httpRequest/feature_experimentation/panic_test.go b/utils/http_request/feature_experimentation/panic_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/panic_test.go rename to utils/http_request/feature_experimentation/panic_test.go diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go new file mode 100644 index 0000000..a88f6f9 --- /dev/null +++ b/utils/http_request/feature_experimentation/project.go @@ -0,0 +1,46 @@ +package feature_experimentation + +import ( + "encoding/json" + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListProject() ([]models.Project, error) { + return httprequest.HTTPGetAllPages[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects") +} + +func HTTPGetProject(id string) (models.Project, error) { + return httprequest.HTTPGetItem[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects/" + id) +} + +func HTTPCreateProject(data []byte) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", data) +} + +func HTTPEditProject(id string, data []byte) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, data) +} + +func HTTPSwitchProject(id, state string) error { + projectRequest := models.ProjectSwitchRequest{ + State: state, + } + + projectRequestJSON, err := json.Marshal(projectRequest) + if err != nil { + return err + } + + _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id+"/toggle", projectRequestJSON) + return err +} + +func HTTPDeleteProject(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/project_test.go b/utils/http_request/feature_experimentation/project_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/project_test.go rename to utils/http_request/feature_experimentation/project_test.go diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go new file mode 100644 index 0000000..b54bfc7 --- /dev/null +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -0,0 +1,31 @@ +package feature_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListTargetingKey() ([]models.TargetingKey, error) { + return httprequest.HTTPGetAllPages[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys") +} + +func HTTPGetTargetingKey(id string) (models.TargetingKey, error) { + return httprequest.HTTPGetItem[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys/" + id) +} + +func HTTPCreateTargetingKey(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", []byte(data)) +} + +func HTTPEditTargetingKey(id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, []byte(data)) +} + +func HTTPDeleteTargetingKey(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/targeting_key_test.go b/utils/http_request/feature_experimentation/targeting_key_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/targeting_key_test.go rename to utils/http_request/feature_experimentation/targeting_key_test.go diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go new file mode 100644 index 0000000..5e535a8 --- /dev/null +++ b/utils/http_request/feature_experimentation/user.go @@ -0,0 +1,24 @@ +package feature_experimentation + +import ( + "net/http" + "net/url" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListUsers() ([]models.User, error) { + return httprequest.HTTPGetAllPages[models.User](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/users") +} + +func HTTPBatchUpdateUsers(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPut, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", []byte(data)) +} + +func HTTPDeleteUsers(email string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/user_test.go b/utils/http_request/feature_experimentation/user_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/user_test.go rename to utils/http_request/feature_experimentation/user_test.go diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go new file mode 100644 index 0000000..00aca4b --- /dev/null +++ b/utils/http_request/feature_experimentation/variation.go @@ -0,0 +1,31 @@ +package feature_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { + return httprequest.HTTPGetAllPages[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") +} + +func HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { + return httprequest.HTTPGetItem[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) +} + +func HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) +} + +func HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) +} + +func HTTPDeleteVariation(campaignID, variationGroupID, id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) + return err +} diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go new file mode 100644 index 0000000..ba15400 --- /dev/null +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -0,0 +1,31 @@ +package feature_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { + return httprequest.HTTPGetAllPages[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups") +} + +func HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { + return httprequest.HTTPGetItem[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + id) +} + +func HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) +} + +func HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) +} + +func HTTPDeleteVariationGroup(campaignID, id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) + return err +} diff --git a/utils/httpRequest/feature_experimentation/variation_group_test.go b/utils/http_request/feature_experimentation/variation_group_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/variation_group_test.go rename to utils/http_request/feature_experimentation/variation_group_test.go diff --git a/utils/httpRequest/feature_experimentation/variation_test.go b/utils/http_request/feature_experimentation/variation_test.go similarity index 100% rename from utils/httpRequest/feature_experimentation/variation_test.go rename to utils/http_request/feature_experimentation/variation_test.go diff --git a/utils/http_request/main_test.go b/utils/http_request/main_test.go new file mode 100644 index 0000000..0d933af --- /dev/null +++ b/utils/http_request/main_test.go @@ -0,0 +1,19 @@ +package http_request + +import ( + "testing" + + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + + "github.com/jarcoal/httpmock" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + mockfunction.APIToken() + mockfunction.Request() + m.Run() +} diff --git a/utils/httpRequest/feature_experimentation/request.go b/utils/http_request/request.go similarity index 99% rename from utils/httpRequest/feature_experimentation/request.go rename to utils/http_request/request.go index d431820..454c5ac 100644 --- a/utils/httpRequest/feature_experimentation/request.go +++ b/utils/http_request/request.go @@ -1,4 +1,4 @@ -package feature_experimentation +package http_request import ( "bytes" diff --git a/utils/httpRequest/feature_experimentation/request_test.go b/utils/http_request/request_test.go similarity index 97% rename from utils/httpRequest/feature_experimentation/request_test.go rename to utils/http_request/request_test.go index dda24da..8ab7fe8 100644 --- a/utils/httpRequest/feature_experimentation/request_test.go +++ b/utils/http_request/request_test.go @@ -1,4 +1,4 @@ -package feature_experimentation +package http_request import ( "encoding/json" diff --git a/utils/httpRequest/feature_experimentation/token.go b/utils/http_request/token.go similarity index 98% rename from utils/httpRequest/feature_experimentation/token.go rename to utils/http_request/token.go index 21d248b..da16023 100644 --- a/utils/httpRequest/feature_experimentation/token.go +++ b/utils/http_request/token.go @@ -1,4 +1,4 @@ -package feature_experimentation +package http_request import ( "encoding/json" diff --git a/utils/httpRequest/feature_experimentation/token_test.go b/utils/http_request/token_test.go similarity index 81% rename from utils/httpRequest/feature_experimentation/token_test.go rename to utils/http_request/token_test.go index 7de1ca6..88e1d54 100644 --- a/utils/httpRequest/feature_experimentation/token_test.go +++ b/utils/http_request/token_test.go @@ -1,4 +1,4 @@ -package feature_experimentation +package http_request import ( "testing" @@ -25,5 +25,6 @@ func TestHTTPCreateToken(t *testing.T) { assert.NotNil(t, respBody) assert.Nil(t, err) - assert.Equal(t, "access_token", respBody) + assert.Equal(t, "access_token", respBody.AccessToken) + assert.Equal(t, "refresh_token", respBody.RefreshToken) } diff --git a/utils/mock_function/feature_experimentation/request.go b/utils/mock_function/request.go similarity index 96% rename from utils/mock_function/feature_experimentation/request.go rename to utils/mock_function/request.go index 6c48c03..c5f26a3 100644 --- a/utils/mock_function/feature_experimentation/request.go +++ b/utils/mock_function/request.go @@ -1,4 +1,4 @@ -package feature_experimentation +package mockfunction import ( "net/http" From 4e97672803798db928bffac8cde3159f8c2e763e Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 13 Mar 2024 12:07:07 +0100 Subject: [PATCH 05/48] separate feat exp and web exp host --- .../analyze/flag/flag.go | 5 +- cmd/feature_experimentation/resource/load.go | 4 +- cmd/root.go | 10 +-- cmd/web_experimentation/campaign/campaign.go | 24 ++++++ cmd/web_experimentation/campaign/get.go | 41 +++++++++ cmd/web_experimentation/campaign/list.go | 31 +++++++ .../global_code/global_code.go | 18 ++++ cmd/web_experimentation/global_code/list.go | 38 +++++++++ cmd/web_experimentation/variation/get.go | 42 +++++++++ .../variation/variation.go | 35 ++++++++ .../web_experimentation.go | 33 +++++++ models/campaign-test.go | 27 ++++++ models/global-code.go | 7 ++ models/vatiation-test.go | 24 ++++++ utils/const.go | 12 ++- .../feature_experimentation/campaign.go | 12 +-- .../feature_experimentation/flag.go | 10 +-- .../feature_experimentation/goal.go | 10 +-- .../feature_experimentation/panic.go | 2 +- .../feature_experimentation/project.go | 12 +-- .../feature_experimentation/targeting_key.go | 10 +-- .../feature_experimentation/user.go | 6 +- .../feature_experimentation/variation.go | 10 +-- .../variation_group.go | 10 +-- utils/http_request/request.go | 68 ++++++++++----- utils/http_request/token.go | 6 +- .../web_experimentation/campaign.go | 45 ++++++++++ .../web_experimentation/campaign_test.go | 85 +++++++++++++++++++ .../web_experimentation/global_code.go | 16 ++++ .../web_experimentation/variation.go | 14 +++ .../feature_experimentation/campaign.go | 12 +-- .../feature_experimentation/flag.go | 10 +-- .../feature_experimentation/goal.go | 10 +-- .../feature_experimentation/panic.go | 2 +- .../feature_experimentation/project.go | 12 +-- .../feature_experimentation/targeting_key.go | 10 +-- .../feature_experimentation/user.go | 6 +- .../feature_experimentation/variation.go | 10 +-- .../variation_group.go | 10 +-- utils/mock_function/token.go | 4 +- 40 files changed, 631 insertions(+), 122 deletions(-) create mode 100644 cmd/web_experimentation/campaign/campaign.go create mode 100644 cmd/web_experimentation/campaign/get.go create mode 100644 cmd/web_experimentation/campaign/list.go create mode 100644 cmd/web_experimentation/global_code/global_code.go create mode 100644 cmd/web_experimentation/global_code/list.go create mode 100644 cmd/web_experimentation/variation/get.go create mode 100644 cmd/web_experimentation/variation/variation.go create mode 100644 cmd/web_experimentation/web_experimentation.go create mode 100644 models/campaign-test.go create mode 100644 models/global-code.go create mode 100644 models/vatiation-test.go create mode 100644 utils/http_request/web_experimentation/campaign.go create mode 100644 utils/http_request/web_experimentation/campaign_test.go create mode 100644 utils/http_request/web_experimentation/global_code.go create mode 100644 utils/http_request/web_experimentation/variation.go diff --git a/cmd/feature_experimentation/analyze/flag/flag.go b/cmd/feature_experimentation/analyze/flag/flag.go index e1e805e..9ebdebd 100644 --- a/cmd/feature_experimentation/analyze/flag/flag.go +++ b/cmd/feature_experimentation/analyze/flag/flag.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -64,8 +63,8 @@ func PreRunConfiguration() { } FSConfig = &cbaConfig.Config{ - FlagshipAPIURL: utils.GetHost(), - FlagshipAuthAPIURL: utils.GetHostAuth(), + FlagshipAPIURL: utils.GetFeatureExperimentationHost(), + FlagshipAuthAPIURL: utils.GetHostFeatureExperimentationAuth(), FlagshipAPIToken: viper.GetString("token"), FlagshipAccountID: viper.GetString("account_id"), FlagshipEnvironmentID: viper.GetString("account_environment_id"), diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 9d74523..b6fc578 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -289,11 +289,11 @@ func ScriptResource(resources []Resource) { } if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { - response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+url, dataResource) + response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+url, dataResource) } if resource.Name == Goal || resource.Name == Campaign { - response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+url, dataResource) + response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+url, dataResource) } if err != nil { diff --git a/cmd/root.go b/cmd/root.go index 5903a0d..59a5210 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -10,6 +10,7 @@ import ( "github.com/flagship-io/flagship/cmd/feature_experimentation" "github.com/flagship-io/flagship/cmd/info" "github.com/flagship-io/flagship/cmd/token" + "github.com/flagship-io/flagship/cmd/web_experimentation" "github.com/flagship-io/flagship/cmd/version" "github.com/flagship-io/flagship/utils/config" @@ -49,16 +50,13 @@ func Execute() { } } -func addFeatureExpSubCommandPalettes() { +func addSubCommandPalettes() { rootCmd.AddCommand(configuration.ConfigurationCmd) rootCmd.AddCommand(version.VersionCmd) rootCmd.AddCommand(token.TokenCmd) rootCmd.AddCommand(info.InfoCmd) rootCmd.AddCommand(feature_experimentation.FeatureExperimentationCmd) -} - -func addWebExpSubCommandPalettes() { - + rootCmd.AddCommand(web_experimentation.WebExperimentationCmd) } func init() { @@ -73,7 +71,7 @@ func init() { rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file that contains your credentials (default is $HOME/.flagship/credentials.yaml)") - addFeatureExpSubCommandPalettes() + addSubCommandPalettes() } // initConfig reads in config file and ENV variables if set. diff --git a/cmd/web_experimentation/campaign/campaign.go b/cmd/web_experimentation/campaign/campaign.go new file mode 100644 index 0000000..e59988d --- /dev/null +++ b/cmd/web_experimentation/campaign/campaign.go @@ -0,0 +1,24 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign + +import ( + "github.com/spf13/cobra" +) + +var ( + CampaignID string + Status string + DataRaw string +) + +// campaignCmd represents the campaign command +var CampaignCmd = &cobra.Command{ + Use: "test [create|edit|get|list|delete|switch]", + Short: "Manage your tests", + Long: `Manage your tests`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/campaign/get.go b/cmd/web_experimentation/campaign/get.go new file mode 100644 index 0000000..356421a --- /dev/null +++ b/cmd/web_experimentation/campaign/get.go @@ -0,0 +1,41 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign + +import ( + "encoding/json" + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + "github.com/spf13/cobra" +) + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ]", + Short: "Get a test", + Long: `Get a test in your account`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.HTTPGetTest(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + jsonBody, err := json.Marshal(body) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Printf("%s", string(jsonBody)) + }, +} + +func init() { + getCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the test you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + CampaignCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/campaign/list.go b/cmd/web_experimentation/campaign/list.go new file mode 100644 index 0000000..b64e5cb --- /dev/null +++ b/cmd/web_experimentation/campaign/list.go @@ -0,0 +1,31 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "List all campaigns", + Long: `List all campaigns`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.HTTPListTest() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "Name", "Description", "Type", "State"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + CampaignCmd.AddCommand(listCmd) +} diff --git a/cmd/web_experimentation/global_code/global_code.go b/cmd/web_experimentation/global_code/global_code.go new file mode 100644 index 0000000..f2456d2 --- /dev/null +++ b/cmd/web_experimentation/global_code/global_code.go @@ -0,0 +1,18 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package global_code + +import ( + "github.com/spf13/cobra" +) + +// globalCodeCmd represents the global code command +var GlobalCodeCmd = &cobra.Command{ + Use: "global-code [get|list]", + Short: "Manage your tests", + Long: `Manage your tests`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/global_code/list.go b/cmd/web_experimentation/global_code/list.go new file mode 100644 index 0000000..c33a876 --- /dev/null +++ b/cmd/web_experimentation/global_code/list.go @@ -0,0 +1,38 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package global_code + +import ( + "encoding/json" + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + "github.com/spf13/cobra" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "List all global code", + Long: `List all global code`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.HTTPListGlobalCode() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + jsonBody, err := json.Marshal(body) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Printf("%s", string(jsonBody)) + + }, +} + +func init() { + GlobalCodeCmd.AddCommand(listCmd) +} diff --git a/cmd/web_experimentation/variation/get.go b/cmd/web_experimentation/variation/get.go new file mode 100644 index 0000000..8b8e5fb --- /dev/null +++ b/cmd/web_experimentation/variation/get.go @@ -0,0 +1,42 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation + +import ( + "encoding/json" + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + "github.com/spf13/cobra" +) + +// getCmd represents the get command +var getCmd = &cobra.Command{ + Use: "get [--test-id=] [-i= | --id=]", + Short: "Get a variation", + Long: `Get a variation in your campaign`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.HTTPGetVariation(TestID, VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + fmt.Println(body) + jsonBody, err := json.Marshal(body) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Printf("%s", string(jsonBody)) + }, +} + +func init() { + getCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the variation group you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + VariationCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/variation/variation.go b/cmd/web_experimentation/variation/variation.go new file mode 100644 index 0000000..a5aa120 --- /dev/null +++ b/cmd/web_experimentation/variation/variation.go @@ -0,0 +1,35 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com + +*/ + +package variation + +import ( + "log" + + "github.com/spf13/cobra" +) + +var ( + TestID int + VariationID int +) + +// VariationCmd represents the variation command +var VariationCmd = &cobra.Command{ + Use: "variation [create|edit|get|delete]", + Short: "Manage your variation", + Long: `Manage your variation in your test`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func init() { + VariationCmd.PersistentFlags().IntVarP(&TestID, "test-id", "", 0, "id of the campaign where you want to manage your variation group") + + if err := VariationCmd.MarkPersistentFlagRequired("test-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } +} diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go new file mode 100644 index 0000000..0c18b85 --- /dev/null +++ b/cmd/web_experimentation/web_experimentation.go @@ -0,0 +1,33 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package web_experimentation + +import ( + "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" + "github.com/flagship-io/flagship/cmd/web_experimentation/global_code" + "github.com/flagship-io/flagship/cmd/web_experimentation/variation" + + "github.com/spf13/cobra" +) + +// WebExperimentationCmd represents the web experimentation command +var WebExperimentationCmd = &cobra.Command{ + Use: "web-experimentation [campaign]", + Aliases: []string{"web-experimentation", "web-exp", "we"}, + Short: "Manage resources related to the feature experimentation product", + Long: `Manage resources related to the feature experimentation product in your account`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func addSubCommandPalettes() { + WebExperimentationCmd.AddCommand(campaign.CampaignCmd) + WebExperimentationCmd.AddCommand(global_code.GlobalCodeCmd) + WebExperimentationCmd.AddCommand(variation.VariationCmd) +} + +func init() { + addSubCommandPalettes() +} diff --git a/models/campaign-test.go b/models/campaign-test.go new file mode 100644 index 0000000..a3e4d38 --- /dev/null +++ b/models/campaign-test.go @@ -0,0 +1,27 @@ +package models + +type Test struct { + Id int `json:"id,omitempty"` + Name string `json:"name"` + Url string `json:"url"` + Description string `json:"description"` + Type string `json:"type"` + SubType string `json:"sub_type"` + State string `json:"state"` + Traffic *Traffic `json:"traffic"` + Variations *[]TestVariation `json:"variations"` +} + +type Traffic struct { + Value int `json:"value"` + LastIncreasedTraffic string `json:"last_increased_traffic"` + Visitors int `json:"visitors"` + OriginalVisitors int `json:"original_visitors"` + VisitorsLimit int `json:"visitors_limit"` +} + +type DateTemplate struct { + ReadableDate string `json:"readable_date"` + Timestamp int `json:"timestamp"` + Pattern string `json:"pattern"` +} diff --git a/models/global-code.go b/models/global-code.go new file mode 100644 index 0000000..9fcb46b --- /dev/null +++ b/models/global-code.go @@ -0,0 +1,7 @@ +package models + +type GlobalCode struct { + Id int `json:"id,omitempty"` + Code string `json:"code"` + CreatedAt DateTemplate `json:"created_at"` +} diff --git a/models/vatiation-test.go b/models/vatiation-test.go new file mode 100644 index 0000000..6436dbf --- /dev/null +++ b/models/vatiation-test.go @@ -0,0 +1,24 @@ +package models + +type TestVariation struct { + Id int `json:"id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Type string `json:"type"` + Traffic int `json:"traffic"` + VisualEditor bool `json:"visual_editor"` + CodeEditor bool `json:"code_editor"` + Components *[]Component `json:"components"` +} + +type Component struct { + Id int `json:"id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Tags []string `json:"tags"` + Js string `json:"js"` + Css string `json:"css"` + Html string `json:"html"` + Form string `json:"form"` + Options string `json:"options"` +} diff --git a/utils/const.go b/utils/const.go index 1061db5..b8da3b1 100644 --- a/utils/const.go +++ b/utils/const.go @@ -2,7 +2,7 @@ package utils import "os" -func GetHost() string { +func GetFeatureExperimentationHost() string { if os.Getenv("STAGING") == "true" { return "https://staging-api.flagship.io" } @@ -10,7 +10,15 @@ func GetHost() string { return "https://api.flagship.io" } -func GetHostAuth() string { +func GetWebExperimentationHost() string { + if os.Getenv("STAGING") == "true" { + return "https://staging-api.abtasty.com/api" + } + + return "https://api.abtasty.com/api" +} + +func GetHostFeatureExperimentationAuth() string { if os.Getenv("STAGING") == "true" { return "https://staging-auth.flagship.io" } diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index 24d29ca..341e45d 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -11,19 +11,19 @@ import ( ) func HTTPListCampaign() ([]models.Campaign, error) { - return httprequest.HTTPGetAllPages[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns") + return httprequest.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns") } func HTTPGetCampaign(id string) (models.Campaign, error) { - return httprequest.HTTPGetItem[models.Campaign](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + id) + return httprequest.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + id) } func HTTPCreateCampaign(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", []byte(data)) } func HTTPEditCampaign(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, []byte(data)) } func HTTPSwitchCampaign(id, state string) error { @@ -36,11 +36,11 @@ func HTTPSwitchCampaign(id, state string) error { return err } - _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) return err } func HTTPDeleteCampaign(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go index d92637d..e3f157f 100644 --- a/utils/http_request/feature_experimentation/flag.go +++ b/utils/http_request/feature_experimentation/flag.go @@ -10,22 +10,22 @@ import ( ) func HTTPListFlag() ([]models.Flag, error) { - return httprequest.HTTPGetAllPages[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags") + return httprequest.HTTPGetAllPages[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags") } func HTTPGetFlag(id string) (models.Flag, error) { - return httprequest.HTTPGetItem[models.Flag](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags/" + id) + return httprequest.HTTPGetItem[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags/" + id) } func HTTPCreateFlag(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", []byte(data)) } func HTTPEditFlag(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, []byte(data)) } func HTTPDeleteFlag(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go index e3d30cc..1e7ab86 100644 --- a/utils/http_request/feature_experimentation/goal.go +++ b/utils/http_request/feature_experimentation/goal.go @@ -10,22 +10,22 @@ import ( ) func HTTPListGoal() ([]models.Goal, error) { - return httprequest.HTTPGetAllPages[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals") + return httprequest.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals") } func HTTPGetGoal(id string) (models.Goal, error) { - return httprequest.HTTPGetItem[models.Goal](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals/" + id) + return httprequest.HTTPGetItem[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals/" + id) } func HTTPCreateGoal(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", []byte(data)) } func HTTPEditGoal(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, []byte(data)) } func HTTPDeleteGoal(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/panic.go b/utils/http_request/feature_experimentation/panic.go index 8247caa..9b5d3cd 100644 --- a/utils/http_request/feature_experimentation/panic.go +++ b/utils/http_request/feature_experimentation/panic.go @@ -15,6 +15,6 @@ func HTTPUpdatePanic(panicStatus string) ([]byte, error) { if err != nil { return nil, err } - resp, err := httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", panicRequestJSON) + resp, err := httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", panicRequestJSON) return resp, err } diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go index a88f6f9..b61d343 100644 --- a/utils/http_request/feature_experimentation/project.go +++ b/utils/http_request/feature_experimentation/project.go @@ -11,19 +11,19 @@ import ( ) func HTTPListProject() ([]models.Project, error) { - return httprequest.HTTPGetAllPages[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects") + return httprequest.HTTPGetAllPages[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects") } func HTTPGetProject(id string) (models.Project, error) { - return httprequest.HTTPGetItem[models.Project](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects/" + id) + return httprequest.HTTPGetItem[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects/" + id) } func HTTPCreateProject(data []byte) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", data) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", data) } func HTTPEditProject(id string, data []byte) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, data) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, data) } func HTTPSwitchProject(id, state string) error { @@ -36,11 +36,11 @@ func HTTPSwitchProject(id, state string) error { return err } - _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id+"/toggle", projectRequestJSON) + _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id+"/toggle", projectRequestJSON) return err } func HTTPDeleteProject(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go index b54bfc7..4b8f7d3 100644 --- a/utils/http_request/feature_experimentation/targeting_key.go +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -10,22 +10,22 @@ import ( ) func HTTPListTargetingKey() ([]models.TargetingKey, error) { - return httprequest.HTTPGetAllPages[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys") + return httprequest.HTTPGetAllPages[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys") } func HTTPGetTargetingKey(id string) (models.TargetingKey, error) { - return httprequest.HTTPGetItem[models.TargetingKey](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys/" + id) + return httprequest.HTTPGetItem[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys/" + id) } func HTTPCreateTargetingKey(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", []byte(data)) } func HTTPEditTargetingKey(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, []byte(data)) } func HTTPDeleteTargetingKey(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go index 5e535a8..cab2b32 100644 --- a/utils/http_request/feature_experimentation/user.go +++ b/utils/http_request/feature_experimentation/user.go @@ -11,14 +11,14 @@ import ( ) func HTTPListUsers() ([]models.User, error) { - return httprequest.HTTPGetAllPages[models.User](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/users") + return httprequest.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/users") } func HTTPBatchUpdateUsers(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPut, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", []byte(data)) + return httprequest.HTTPRequest(http.MethodPut, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", []byte(data)) } func HTTPDeleteUsers(email string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), nil) return err } diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index 00aca4b..2a9e256 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -10,22 +10,22 @@ import ( ) func HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return httprequest.HTTPGetAllPages[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") + return httprequest.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") } func HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { - return httprequest.HTTPGetItem[models.Variation](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) + return httprequest.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) } func HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) } func HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) } func HTTPDeleteVariation(campaignID, variationGroupID, id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go index ba15400..2f67351 100644 --- a/utils/http_request/feature_experimentation/variation_group.go +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -10,22 +10,22 @@ import ( ) func HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { - return httprequest.HTTPGetAllPages[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups") + return httprequest.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups") } func HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { - return httprequest.HTTPGetItem[models.VariationGroup](utils.GetHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + id) + return httprequest.HTTPGetItem[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + id) } func HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) + return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) } func HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) + return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) } func HTTPDeleteVariationGroup(campaignID, id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) return err } diff --git a/utils/http_request/request.go b/utils/http_request/request.go index 454c5ac..ef08ad6 100644 --- a/utils/http_request/request.go +++ b/utils/http_request/request.go @@ -8,7 +8,6 @@ import ( "io" "log" "net/http" - "os" "strings" "time" @@ -18,7 +17,7 @@ import ( var UserAgent string -func regenerateToken(configName string) { +func regenerateToken_(configName string) { gt := viper.GetString("grant_type") sc := viper.GetString("scope") ex := viper.GetInt("expiration") @@ -43,30 +42,12 @@ func regenerateToken(configName string) { if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } else { - fmt.Fprintln(os.Stdout, "Token generated successfully") config.WriteToken(configName, authenticationResponse) } } -func regenerateToken_(configName string) { - gt := viper.GetString("grant_type") - sc := viper.GetString("scope") - ex := viper.GetInt("expiration") - - if gt == "" { - gt = config.GrantType - } - - if sc == "" { - sc = config.Scope - } - - if ex == 0 { - ex = config.Expiration - } - +func regenerateToken(configName string) { authenticationResponse, err := HTTPRefreshToken(viper.GetString("client_id"), viper.GetString("refresh_token")) - fmt.Println(authenticationResponse) if err != nil { log.Fatalf("%s", err) @@ -74,7 +55,6 @@ func regenerateToken_(configName string) { if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } else { - fmt.Fprintln(os.Stdout, "Token generated successfully") config.WriteToken(configName, authenticationResponse) } } @@ -87,6 +67,18 @@ type PageResult struct { TotalCount int `json:"total_count"` } +type PageResultWE struct { + Data json.RawMessage `json:"_data"` + Pagination Pagination `json:"_pagination"` +} + +type Pagination struct { + Total int `json:"_total"` + Pages int `json:"_pages"` + Page int `json:"_page"` + MaxPerPage int `json:"_max_per_page"` +} + func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { var bodyIO io.Reader = nil if body != nil { @@ -113,6 +105,7 @@ func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { req.Header.Add("Accept", `*/*`) req.Header.Add("Authorization", "Bearer "+viper.GetString("token")) req.Header.Add("Accept-Encoding", `gzip, deflate, br`) + req.Header.Add("Content-Type", "application/json") req.Header.Set("User-Agent", UserAgent) if body != nil { @@ -141,6 +134,8 @@ func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { return nil, err } + //fmt.Println(string(respBody)) + if (resp.StatusCode == 403 || resp.StatusCode == 401) && !counter { counter = true regenerateToken(viper.GetString("current_used_configuration")) @@ -187,3 +182,32 @@ func HTTPGetAllPages[T any](resource string) ([]T, error) { } return results, nil } + +func HTTPGetAllPagesWe[T any](resource string) ([]T, error) { + currentPage := 1 + results := []T{} + for { + respBody, err := HTTPRequest(http.MethodGet, fmt.Sprintf("%s?_page=%d&_max_per_page=100", resource, currentPage), nil) + if err != nil { + return nil, err + } + pageResult := &PageResultWE{} + err = json.Unmarshal(respBody, pageResult) + if err != nil { + return nil, err + } + + typedItems := []T{} + err = json.Unmarshal(pageResult.Data, &typedItems) + if err != nil { + return nil, err + } + results = append(results, typedItems...) + + if len(results) >= pageResult.Pagination.Total || len(pageResult.Data) == 0 { + break + } + currentPage++ + } + return results, nil +} diff --git a/utils/http_request/token.go b/utils/http_request/token.go index da16023..8e3b088 100644 --- a/utils/http_request/token.go +++ b/utils/http_request/token.go @@ -23,7 +23,7 @@ func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expirat return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -48,7 +48,7 @@ func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, er return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostAuth()+"/"+viper.GetString("account_id")+"/token", authRequestJSON) + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -62,5 +62,5 @@ func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, er } func HTTPCheckToken(token string) (models.Token, error) { - return HTTPGetItem[models.Token](utils.GetHostAuth() + "/token?access_token=" + token) + return HTTPGetItem[models.Token](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) } diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go new file mode 100644 index 0000000..2e67896 --- /dev/null +++ b/utils/http_request/web_experimentation/campaign.go @@ -0,0 +1,45 @@ +package web_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListTest() ([]models.Test, error) { + return httprequest.HTTPGetAllPagesWe[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests") +} + +func HTTPGetTest(id string) (models.Test, error) { + return httprequest.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + id) +} + +func HTTPCreateTest(data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) +} + +func HTTPEditTest(id, data string) ([]byte, error) { + return httprequest.HTTPRequest(http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) +} + +/* func HTTPSwitchCampaign(id, state string) error { + campaignSwitchRequest := models.CampaignSwitchRequest{ + State: state, + } + + campaignSwitchRequestJSON, err := json.Marshal(campaignSwitchRequest) + if err != nil { + return err + } + + _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + return err +} */ + +func HTTPDeleteTest(id string) error { + _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) + return err +} diff --git a/utils/http_request/web_experimentation/campaign_test.go b/utils/http_request/web_experimentation/campaign_test.go new file mode 100644 index 0000000..1cede23 --- /dev/null +++ b/utils/http_request/web_experimentation/campaign_test.go @@ -0,0 +1,85 @@ +package web_experimentation + +import ( + "testing" +) + +func TestHTTPGetCampaign(t *testing.T) { + /* + respBody, err := HTTPGetCampaign("testCampaignID") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "testCampaignID", respBody.Id) + assert.Equal(t, "testCampaignName", respBody.Name) + assert.Equal(t, "testProjectID", respBody.ProjectId) + assert.Equal(t, "testCampaignDescription", respBody.Description) + assert.Equal(t, "toggle", respBody.Type) + */ +} + +func TestHTTPListCampaign(t *testing.T) { + + /* + respBody, err := HTTPListCampaign() + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "testCampaignID", respBody[0].Id) + assert.Equal(t, "testCampaignName", respBody[0].Name) + assert.Equal(t, "testProjectID", respBody[0].ProjectId) + assert.Equal(t, "testCampaignDescription", respBody[0].Description) + assert.Equal(t, "toggle", respBody[0].Type) + + assert.Equal(t, "testCampaignID1", respBody[1].Id) + assert.Equal(t, "testCampaignName1", respBody[1].Name) + assert.Equal(t, "testProjectID1", respBody[1].ProjectId) + assert.Equal(t, "testCampaignDescription1", respBody[1].Description) + assert.Equal(t, "toggle", respBody[1].Type) + */ +} + +func TestHTTPCreateCampaign(t *testing.T) { + + /* + dataCampaign := "{\"project_id\":\"testProjectID\",\"name\":\"testCampaignName\",\"description\":\"testCampaignDescription\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" + respBody, err := HTTPCreateCampaign(dataCampaign) + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, []byte("{\"id\":\"testCampaignID\",\"project_id\":\"testProjectID\",\"name\":\"testCampaignName\",\"description\":\"testCampaignDescription\",\"type\":\"toggle\",\"status\":\"\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"reference\":false,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"key\":\"isVIP\",\"operator\":\"CONTAINS\",\"value\":true}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}"), respBody) + */ +} + +func TestHTTPEditCampaign(t *testing.T) { + /* + dataCampaign := "{\"project_id\":\"testProjectID1\",\"name\":\"testCampaignName1\",\"description\":\"testCampaignDescription1\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" + + respBody, err := HTTPEditCampaign("testCampaignID", dataCampaign) + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, []byte("{\"id\":\"testCampaignID\",\"project_id\":\"testProjectID1\",\"name\":\"testCampaignName1\",\"description\":\"testCampaignDescription1\",\"type\":\"toggle\",\"status\":\"\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"reference\":false,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"key\":\"isVIP\",\"operator\":\"CONTAINS\",\"value\":true}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}"), respBody) + */ +} + +func TestHTTPDeleteCampaign(t *testing.T) { + /* + err := HTTPDeleteCampaign("testCampaignID") + + assert.Nil(t, err) + */ +} + +func TestHTTPSwitchCampaign(t *testing.T) { + + /* + err := HTTPSwitchCampaign("testCampaignID", "active") + + assert.Nil(t, err) + */ +} diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go new file mode 100644 index 0000000..dffec40 --- /dev/null +++ b/utils/http_request/web_experimentation/global_code.go @@ -0,0 +1,16 @@ +package web_experimentation + +import ( + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPListGlobalCode() ([]models.GlobalCode, error) { + return httprequest.HTTPGetAllPagesWe[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes") +} + +func HTTPGetGlobalCode(id string) (models.GlobalCode, error) { + return httprequest.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes/" + id) +} diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go new file mode 100644 index 0000000..f676d1e --- /dev/null +++ b/utils/http_request/web_experimentation/variation.go @@ -0,0 +1,14 @@ +package web_experimentation + +import ( + "strconv" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/viper" +) + +func HTTPGetVariation(testID, id int) (models.TestVariation, error) { + return httprequest.HTTPGetItem[models.TestVariation](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) +} diff --git a/utils/mock_function/feature_experimentation/campaign.go b/utils/mock_function/feature_experimentation/campaign.go index f40d864..01a038c 100644 --- a/utils/mock_function/feature_experimentation/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -108,42 +108,42 @@ func APICampaign() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaign) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaign) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaignEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id+"/toggle", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id+"/toggle", func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(200, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/flag.go b/utils/mock_function/feature_experimentation/flag.go index efd61f8..334097a 100644 --- a/utils/mock_function/feature_experimentation/flag.go +++ b/utils/mock_function/feature_experimentation/flag.go @@ -51,35 +51,35 @@ func APIFlag() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlag) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlag) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlagEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/goal.go b/utils/mock_function/feature_experimentation/goal.go index 13059fe..2f63f83 100644 --- a/utils/mock_function/feature_experimentation/goal.go +++ b/utils/mock_function/feature_experimentation/goal.go @@ -51,35 +51,35 @@ func APIGoal() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoal) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoal) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoalEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/panic.go b/utils/mock_function/feature_experimentation/panic.go index 8f421d4..be0c67f 100644 --- a/utils/mock_function/feature_experimentation/panic.go +++ b/utils/mock_function/feature_experimentation/panic.go @@ -12,7 +12,7 @@ import ( func APIPanic() { config.SetViperMock() - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, "") return resp, nil diff --git a/utils/mock_function/feature_experimentation/project.go b/utils/mock_function/feature_experimentation/project.go index 1f9af41..5cad4dc 100644 --- a/utils/mock_function/feature_experimentation/project.go +++ b/utils/mock_function/feature_experimentation/project.go @@ -43,42 +43,42 @@ func APIProject() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProject) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProject) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProjectEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id+"/toggle", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id+"/toggle", func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(200, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/targeting_key.go b/utils/mock_function/feature_experimentation/targeting_key.go index f43b64c..9e22e8f 100644 --- a/utils/mock_function/feature_experimentation/targeting_key.go +++ b/utils/mock_function/feature_experimentation/targeting_key.go @@ -49,35 +49,35 @@ func APITargetingKey() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKey) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKey) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKeyEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/user.go b/utils/mock_function/feature_experimentation/user.go index 637eade..da6c2b9 100644 --- a/utils/mock_function/feature_experimentation/user.go +++ b/utils/mock_function/feature_experimentation/user.go @@ -36,21 +36,21 @@ func APIUser() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("PUT", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", + httpmock.RegisterResponder("PUT", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(204, "") return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(204, "") return resp, nil diff --git a/utils/mock_function/feature_experimentation/variation.go b/utils/mock_function/feature_experimentation/variation.go index 96b5723..d3cea13 100644 --- a/utils/mock_function/feature_experimentation/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -64,35 +64,35 @@ func APIVariation() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariation) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariation) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go index 8c0514b..79a93c3 100644 --- a/utils/mock_function/feature_experimentation/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -79,35 +79,35 @@ func APIVariationGroup() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { mockResp, _ := httpmock.NewJsonResponse(200, TestVariationGroup) return mockResp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", func(req *http.Request) (*http.Response, error) { mockResp, _ := httpmock.NewJsonResponse(200, resp) return mockResp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationGroup) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationGroupEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/token.go b/utils/mock_function/token.go index 967369a..4f5ced2 100644 --- a/utils/mock_function/token.go +++ b/utils/mock_function/token.go @@ -29,14 +29,14 @@ func APIToken() { RefreshToken: "refresh_token", } - httpmock.RegisterResponder("GET", utils.GetHostAuth()+"/token?access_token="+token, + httpmock.RegisterResponder("GET", utils.GetHostFeatureExperimentationAuth()+"/token?access_token="+token, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestToken) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetHostAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(tokenExpiration), + httpmock.RegisterResponder("POST", utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(tokenExpiration), func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, testAuthenticationResponse) return resp, nil From 03d5013b4e47de607aae9f704e4b29d355302236 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 13 Mar 2024 13:04:55 +0100 Subject: [PATCH 06/48] separate web exp and feat exp models --- cmd/feature_experimentation/analyze/flag/create.go | 2 +- cmd/feature_experimentation/analyze/flag/list.go | 2 +- cmd/feature_experimentation/campaign/campaign_test.go | 2 +- cmd/feature_experimentation/flag/create.go | 2 +- cmd/feature_experimentation/flag/flag_test.go | 2 +- cmd/feature_experimentation/goal/goal_test.go | 2 +- cmd/feature_experimentation/project/create.go | 2 +- cmd/feature_experimentation/project/edit.go | 2 +- cmd/feature_experimentation/project/project_test.go | 2 +- cmd/feature_experimentation/resource/load.go | 2 +- cmd/feature_experimentation/targeting_key/targeting_key_test.go | 2 +- cmd/feature_experimentation/user/user_test.go | 2 +- cmd/feature_experimentation/variation/variation_test.go | 2 +- .../variation_group/variation_group_test.go | 2 +- models/{ => feature_experimentation}/analyze.go | 2 +- models/{ => feature_experimentation}/campaign.go | 2 +- models/{ => feature_experimentation}/flag.go | 2 +- models/{ => feature_experimentation}/goal.go | 2 +- models/{ => feature_experimentation}/panic.go | 2 +- models/{ => feature_experimentation}/project.go | 2 +- models/{ => feature_experimentation}/targeting_key.go | 2 +- models/{ => feature_experimentation}/user.go | 2 +- models/{ => feature_experimentation}/variation.go | 2 +- models/{ => feature_experimentation}/variation_group.go | 2 +- models/{ => web_experimentation}/campaign-test.go | 0 models/{ => web_experimentation}/global-code.go | 0 models/{ => web_experimentation}/vatiation-test.go | 0 utils/http_request/feature_experimentation/campaign.go | 2 +- utils/http_request/feature_experimentation/flag.go | 2 +- utils/http_request/feature_experimentation/goal.go | 2 +- utils/http_request/feature_experimentation/panic.go | 2 +- utils/http_request/feature_experimentation/project.go | 2 +- utils/http_request/feature_experimentation/project_test.go | 2 +- utils/http_request/feature_experimentation/targeting_key.go | 2 +- utils/http_request/feature_experimentation/user.go | 2 +- utils/http_request/feature_experimentation/variation.go | 2 +- utils/http_request/feature_experimentation/variation_group.go | 2 +- utils/http_request/web_experimentation/campaign.go | 2 +- utils/http_request/web_experimentation/global_code.go | 2 +- utils/http_request/web_experimentation/variation.go | 2 +- utils/mock_function/feature_experimentation/campaign.go | 2 +- utils/mock_function/feature_experimentation/flag.go | 2 +- utils/mock_function/feature_experimentation/goal.go | 2 +- utils/mock_function/feature_experimentation/project.go | 2 +- utils/mock_function/feature_experimentation/targeting_key.go | 2 +- utils/mock_function/feature_experimentation/user.go | 2 +- utils/mock_function/feature_experimentation/variation.go | 2 +- utils/mock_function/feature_experimentation/variation_group.go | 2 +- 48 files changed, 45 insertions(+), 45 deletions(-) rename models/{ => feature_experimentation}/analyze.go (92%) rename models/{ => feature_experimentation}/campaign.go (95%) rename models/{ => feature_experimentation}/flag.go (94%) rename models/{ => feature_experimentation}/goal.go (85%) rename models/{ => feature_experimentation}/panic.go (64%) rename models/{ => feature_experimentation}/project.go (82%) rename models/{ => feature_experimentation}/targeting_key.go (84%) rename models/{ => feature_experimentation}/user.go (71%) rename models/{ => feature_experimentation}/variation.go (91%) rename models/{ => feature_experimentation}/variation_group.go (94%) rename models/{ => web_experimentation}/campaign-test.go (100%) rename models/{ => web_experimentation}/global-code.go (100%) rename models/{ => web_experimentation}/vatiation-test.go (100%) diff --git a/cmd/feature_experimentation/analyze/flag/create.go b/cmd/feature_experimentation/analyze/flag/create.go index a4d1617..79af794 100644 --- a/cmd/feature_experimentation/analyze/flag/create.go +++ b/cmd/feature_experimentation/analyze/flag/create.go @@ -13,7 +13,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/rodaine/table" "github.com/spf13/cobra" diff --git a/cmd/feature_experimentation/analyze/flag/list.go b/cmd/feature_experimentation/analyze/flag/list.go index 8869728..985ccd5 100644 --- a/cmd/feature_experimentation/analyze/flag/list.go +++ b/cmd/feature_experimentation/analyze/flag/list.go @@ -11,7 +11,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/kyokomi/emoji/v2" "github.com/rodaine/table" diff --git a/cmd/feature_experimentation/campaign/campaign_test.go b/cmd/feature_experimentation/campaign/campaign_test.go index ff2fcb1..4ae1829 100644 --- a/cmd/feature_experimentation/campaign/campaign_test.go +++ b/cmd/feature_experimentation/campaign/campaign_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/flag/create.go b/cmd/feature_experimentation/flag/create.go index 93f917c..c46d66e 100644 --- a/cmd/feature_experimentation/flag/create.go +++ b/cmd/feature_experimentation/flag/create.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/flag/flag_test.go b/cmd/feature_experimentation/flag/flag_test.go index 290edc8..ccb75de 100644 --- a/cmd/feature_experimentation/flag/flag_test.go +++ b/cmd/feature_experimentation/flag/flag_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/goal/goal_test.go b/cmd/feature_experimentation/goal/goal_test.go index 4c2567a..3781295 100644 --- a/cmd/feature_experimentation/goal/goal_test.go +++ b/cmd/feature_experimentation/goal/goal_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/project/create.go b/cmd/feature_experimentation/project/create.go index b07ecbf..f19c18f 100644 --- a/cmd/feature_experimentation/project/create.go +++ b/cmd/feature_experimentation/project/create.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/edit.go b/cmd/feature_experimentation/project/edit.go index ed27963..885250c 100644 --- a/cmd/feature_experimentation/project/edit.go +++ b/cmd/feature_experimentation/project/edit.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/project/project_test.go b/cmd/feature_experimentation/project/project_test.go index e07ed5f..5560658 100644 --- a/cmd/feature_experimentation/project/project_test.go +++ b/cmd/feature_experimentation/project/project_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index b6fc578..e53135c 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -15,7 +15,7 @@ import ( "strings" "github.com/d5/tengo/v2" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" featureexp "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" diff --git a/cmd/feature_experimentation/targeting_key/targeting_key_test.go b/cmd/feature_experimentation/targeting_key/targeting_key_test.go index 3724b04..7dbd394 100644 --- a/cmd/feature_experimentation/targeting_key/targeting_key_test.go +++ b/cmd/feature_experimentation/targeting_key/targeting_key_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/user/user_test.go b/cmd/feature_experimentation/user/user_test.go index d6c6905..7f6a198 100644 --- a/cmd/feature_experimentation/user/user_test.go +++ b/cmd/feature_experimentation/user/user_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go index 8bb8831..fd63505 100644 --- a/cmd/feature_experimentation/variation/variation_test.go +++ b/cmd/feature_experimentation/variation/variation_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/cmd/feature_experimentation/variation_group/variation_group_test.go b/cmd/feature_experimentation/variation_group/variation_group_test.go index a893566..7d96cb7 100644 --- a/cmd/feature_experimentation/variation_group/variation_group_test.go +++ b/cmd/feature_experimentation/variation_group/variation_group_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" diff --git a/models/analyze.go b/models/feature_experimentation/analyze.go similarity index 92% rename from models/analyze.go rename to models/feature_experimentation/analyze.go index 688b02b..56673dc 100644 --- a/models/analyze.go +++ b/models/feature_experimentation/analyze.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type FlagAnalyzed struct { LineNumber int `json:"LineNumber"` diff --git a/models/campaign.go b/models/feature_experimentation/campaign.go similarity index 95% rename from models/campaign.go rename to models/feature_experimentation/campaign.go index 04cbfa6..6edbe73 100644 --- a/models/campaign.go +++ b/models/feature_experimentation/campaign.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type Campaign struct { Id string `json:"id,omitempty"` diff --git a/models/flag.go b/models/feature_experimentation/flag.go similarity index 94% rename from models/flag.go rename to models/feature_experimentation/flag.go index 7983069..0c07bdf 100644 --- a/models/flag.go +++ b/models/feature_experimentation/flag.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type Flag struct { Id string `json:"id,omitempty"` diff --git a/models/goal.go b/models/feature_experimentation/goal.go similarity index 85% rename from models/goal.go rename to models/feature_experimentation/goal.go index 5a58933..da79adc 100644 --- a/models/goal.go +++ b/models/feature_experimentation/goal.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type Goal struct { Id string `json:"id,omitempty"` diff --git a/models/panic.go b/models/feature_experimentation/panic.go similarity index 64% rename from models/panic.go rename to models/feature_experimentation/panic.go index 6868b19..d82a73a 100644 --- a/models/panic.go +++ b/models/feature_experimentation/panic.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type PanicRequest struct { Panic string `json:"panic"` diff --git a/models/project.go b/models/feature_experimentation/project.go similarity index 82% rename from models/project.go rename to models/feature_experimentation/project.go index 55ddbf1..3690c14 100644 --- a/models/project.go +++ b/models/feature_experimentation/project.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type Project struct { Id string `json:"id,omitempty"` diff --git a/models/targeting_key.go b/models/feature_experimentation/targeting_key.go similarity index 84% rename from models/targeting_key.go rename to models/feature_experimentation/targeting_key.go index 1c8fc16..1da8a98 100644 --- a/models/targeting_key.go +++ b/models/feature_experimentation/targeting_key.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type TargetingKey struct { Id string `json:"id,omitempty"` diff --git a/models/user.go b/models/feature_experimentation/user.go similarity index 71% rename from models/user.go rename to models/feature_experimentation/user.go index c695f0e..c35c918 100644 --- a/models/user.go +++ b/models/feature_experimentation/user.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type User struct { Email string `json:"email"` diff --git a/models/variation.go b/models/feature_experimentation/variation.go similarity index 91% rename from models/variation.go rename to models/feature_experimentation/variation.go index 7969924..e159c57 100644 --- a/models/variation.go +++ b/models/feature_experimentation/variation.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type Variation struct { Id string `json:"id,omitempty"` diff --git a/models/variation_group.go b/models/feature_experimentation/variation_group.go similarity index 94% rename from models/variation_group.go rename to models/feature_experimentation/variation_group.go index 8107596..0ad331d 100644 --- a/models/variation_group.go +++ b/models/feature_experimentation/variation_group.go @@ -1,4 +1,4 @@ -package models +package feature_experimentation type VariationGroup struct { Id string `json:"id,omitempty"` diff --git a/models/campaign-test.go b/models/web_experimentation/campaign-test.go similarity index 100% rename from models/campaign-test.go rename to models/web_experimentation/campaign-test.go diff --git a/models/global-code.go b/models/web_experimentation/global-code.go similarity index 100% rename from models/global-code.go rename to models/web_experimentation/global-code.go diff --git a/models/vatiation-test.go b/models/web_experimentation/vatiation-test.go similarity index 100% rename from models/vatiation-test.go rename to models/web_experimentation/vatiation-test.go diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index 341e45d..8622abf 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go index e3f157f..6d1e45a 100644 --- a/utils/http_request/feature_experimentation/flag.go +++ b/utils/http_request/feature_experimentation/flag.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go index 1e7ab86..38916ae 100644 --- a/utils/http_request/feature_experimentation/goal.go +++ b/utils/http_request/feature_experimentation/goal.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/panic.go b/utils/http_request/feature_experimentation/panic.go index 9b5d3cd..bd62511 100644 --- a/utils/http_request/feature_experimentation/panic.go +++ b/utils/http_request/feature_experimentation/panic.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go index b61d343..4286088 100644 --- a/utils/http_request/feature_experimentation/project.go +++ b/utils/http_request/feature_experimentation/project.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/project_test.go b/utils/http_request/feature_experimentation/project_test.go index e191a9d..95c3afd 100644 --- a/utils/http_request/feature_experimentation/project_test.go +++ b/utils/http_request/feature_experimentation/project_test.go @@ -5,7 +5,7 @@ import ( "log" "testing" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/stretchr/testify/assert" ) diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go index 4b8f7d3..a6df319 100644 --- a/utils/http_request/feature_experimentation/targeting_key.go +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go index cab2b32..4ace06a 100644 --- a/utils/http_request/feature_experimentation/user.go +++ b/utils/http_request/feature_experimentation/user.go @@ -4,7 +4,7 @@ import ( "net/http" "net/url" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index 2a9e256..789bce1 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go index 2f67351..85d3a88 100644 --- a/utils/http_request/feature_experimentation/variation_group.go +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index 2e67896..c138998 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -3,7 +3,7 @@ package web_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go index dffec40..644e973 100644 --- a/utils/http_request/web_experimentation/global_code.go +++ b/utils/http_request/web_experimentation/global_code.go @@ -1,7 +1,7 @@ package web_experimentation import ( - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go index f676d1e..71aac56 100644 --- a/utils/http_request/web_experimentation/variation.go +++ b/utils/http_request/web_experimentation/variation.go @@ -3,7 +3,7 @@ package web_experimentation import ( "strconv" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/viper" diff --git a/utils/mock_function/feature_experimentation/campaign.go b/utils/mock_function/feature_experimentation/campaign.go index 01a038c..85be01b 100644 --- a/utils/mock_function/feature_experimentation/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/flag.go b/utils/mock_function/feature_experimentation/flag.go index 334097a..7fe1409 100644 --- a/utils/mock_function/feature_experimentation/flag.go +++ b/utils/mock_function/feature_experimentation/flag.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/goal.go b/utils/mock_function/feature_experimentation/goal.go index 2f63f83..4e82485 100644 --- a/utils/mock_function/feature_experimentation/goal.go +++ b/utils/mock_function/feature_experimentation/goal.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/project.go b/utils/mock_function/feature_experimentation/project.go index 5cad4dc..41e65ca 100644 --- a/utils/mock_function/feature_experimentation/project.go +++ b/utils/mock_function/feature_experimentation/project.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/targeting_key.go b/utils/mock_function/feature_experimentation/targeting_key.go index 9e22e8f..aa0c069 100644 --- a/utils/mock_function/feature_experimentation/targeting_key.go +++ b/utils/mock_function/feature_experimentation/targeting_key.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/user.go b/utils/mock_function/feature_experimentation/user.go index da6c2b9..241cf6f 100644 --- a/utils/mock_function/feature_experimentation/user.go +++ b/utils/mock_function/feature_experimentation/user.go @@ -4,7 +4,7 @@ import ( "net/http" "net/url" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/variation.go b/utils/mock_function/feature_experimentation/variation.go index d3cea13..7bbf2fc 100644 --- a/utils/mock_function/feature_experimentation/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" diff --git a/utils/mock_function/feature_experimentation/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go index 79a93c3..7efa1f3 100644 --- a/utils/mock_function/feature_experimentation/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -3,7 +3,7 @@ package feature_experimentation import ( "net/http" - "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/jarcoal/httpmock" From 8e6b030273ce7fe88e88497f62aa00c0f79a015b Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 25 Mar 2024 12:17:39 +0000 Subject: [PATCH 07/48] reduce viper dependency --- cmd/configuration/configuration.go | 25 --- cmd/configuration/configuration_test.go | 87 --------- cmd/configuration/create.go | 70 ------- cmd/configuration/current.go | 62 ------- cmd/configuration/delete.go | 39 ---- cmd/configuration/edit.go | 87 --------- cmd/configuration/get.go | 56 ------ cmd/configuration/use.go | 69 ------- .../account/account.go | 22 +++ .../account/current.go | 56 ++++++ cmd/feature_experimentation/account/list.go | 34 ++++ cmd/feature_experimentation/account/use.go | 39 ++++ .../analyze/flag/create.go | 8 +- .../analyze/flag/list.go | 4 +- cmd/feature_experimentation/auth/auth.go | 23 +++ cmd/feature_experimentation/auth/get.go | 56 ++++++ .../auth}/list.go | 32 ++-- cmd/feature_experimentation/auth/login.go | 173 ++++++++++++++++++ .../campaign/campaign.go | 1 - .../campaign/create.go | 4 +- .../campaign/delete.go | 4 +- cmd/feature_experimentation/campaign/edit.go | 4 +- cmd/feature_experimentation/campaign/get.go | 4 +- cmd/feature_experimentation/campaign/list.go | 4 +- .../campaign/switch.go | 4 +- .../feature_experimentation.go | 33 ++++ cmd/feature_experimentation/flag/create.go | 4 +- cmd/feature_experimentation/flag/delete.go | 4 +- cmd/feature_experimentation/flag/edit.go | 4 +- cmd/feature_experimentation/flag/get.go | 4 +- cmd/feature_experimentation/flag/list.go | 4 +- cmd/feature_experimentation/goal/create.go | 4 +- cmd/feature_experimentation/goal/delete.go | 4 +- cmd/feature_experimentation/goal/edit.go | 4 +- cmd/feature_experimentation/goal/get.go | 4 +- cmd/feature_experimentation/goal/list.go | 4 +- cmd/feature_experimentation/panic/panic.go | 4 +- cmd/feature_experimentation/project/create.go | 4 +- cmd/feature_experimentation/project/delete.go | 4 +- cmd/feature_experimentation/project/edit.go | 4 +- cmd/feature_experimentation/project/get.go | 4 +- cmd/feature_experimentation/project/list.go | 4 +- cmd/feature_experimentation/project/switch.go | 4 +- cmd/feature_experimentation/resource/load.go | 16 +- .../targeting_key/create.go | 4 +- .../targeting_key/delete.go | 4 +- .../targeting_key/edit.go | 4 +- .../targeting_key/get.go | 4 +- .../targeting_key/list.go | 4 +- cmd/feature_experimentation/user/create.go | 4 +- cmd/feature_experimentation/user/delete.go | 4 +- cmd/feature_experimentation/user/edit.go | 4 +- cmd/feature_experimentation/user/list.go | 4 +- .../variation/create.go | 4 +- .../variation/delete.go | 4 +- cmd/feature_experimentation/variation/edit.go | 4 +- cmd/feature_experimentation/variation/get.go | 4 +- cmd/feature_experimentation/variation/list.go | 4 +- .../variation_group/create.go | 4 +- .../variation_group/delete.go | 4 +- .../variation_group/edit.go | 4 +- .../variation_group/get.go | 4 +- .../variation_group/list.go | 4 +- cmd/root.go | 26 +-- cmd/token/info.go | 4 +- models/configuration.go | 12 ++ models/token.go | 7 + utils/config/config.go | 162 ++++++++++++++-- utils/const.go | 20 +- utils/http_request/{ => common}/request.go | 104 +++++------ .../http_request/{ => common}/request_test.go | 2 +- utils/http_request/common/token.go | 142 ++++++++++++++ utils/http_request/{ => common}/token_test.go | 2 +- .../feature_experimentation/campaign.go | 31 ++-- .../feature_experimentation/campaign_test.go | 14 +- .../feature_experimentation/flag.go | 27 +-- .../feature_experimentation/flag_test.go | 12 +- .../feature_experimentation/goal.go | 27 +-- .../feature_experimentation/goal_test.go | 12 +- .../feature_experimentation/panic.go | 11 +- .../feature_experimentation/panic_test.go | 4 +- .../feature_experimentation/project.go | 31 ++-- .../feature_experimentation/project_test.go | 14 +- .../feature_experimentation/targeting_key.go | 27 +-- .../targeting_key_test.go | 12 +- .../feature_experimentation/user.go | 19 +- .../feature_experimentation/user_test.go | 8 +- .../feature_experimentation/variation.go | 27 +-- .../variation_group.go | 27 +-- .../variation_group_test.go | 11 +- .../feature_experimentation/variation_test.go | 11 +- utils/http_request/main.go | 24 +++ utils/http_request/token.go | 66 ------- .../web_experimentation/campaign.go | 14 +- .../web_experimentation/global_code.go | 6 +- .../web_experimentation/variation.go | 4 +- 96 files changed, 1155 insertions(+), 925 deletions(-) delete mode 100644 cmd/configuration/configuration.go delete mode 100644 cmd/configuration/configuration_test.go delete mode 100644 cmd/configuration/create.go delete mode 100644 cmd/configuration/current.go delete mode 100644 cmd/configuration/delete.go delete mode 100644 cmd/configuration/edit.go delete mode 100644 cmd/configuration/get.go delete mode 100644 cmd/configuration/use.go create mode 100644 cmd/feature_experimentation/account/account.go create mode 100644 cmd/feature_experimentation/account/current.go create mode 100644 cmd/feature_experimentation/account/list.go create mode 100644 cmd/feature_experimentation/account/use.go create mode 100644 cmd/feature_experimentation/auth/auth.go create mode 100644 cmd/feature_experimentation/auth/get.go rename cmd/{configuration => feature_experimentation/auth}/list.go (51%) create mode 100644 cmd/feature_experimentation/auth/login.go rename utils/http_request/{ => common}/request.go (70%) rename utils/http_request/{ => common}/request_test.go (98%) create mode 100644 utils/http_request/common/token.go rename utils/http_request/{ => common}/token_test.go (97%) create mode 100644 utils/http_request/main.go delete mode 100644 utils/http_request/token.go diff --git a/cmd/configuration/configuration.go b/cmd/configuration/configuration.go deleted file mode 100644 index 4f3f554..0000000 --- a/cmd/configuration/configuration.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import "github.com/spf13/cobra" - -var ( - ConfigurationName string - ConfigurationClientID string - ConfigurationClientSecret string - ConfigurationAccountID string - ConfigurationAccountEnvID string -) - -// ConfigurationCmd represents the configuration command -var ConfigurationCmd = &cobra.Command{ - Use: "configuration [create|edit|get|list|delete|use]", - Aliases: []string{"conf"}, - Short: "Manage your CLI configurations", - Long: `Manage your CLI configurations in your account`, - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, -} diff --git a/cmd/configuration/configuration_test.go b/cmd/configuration/configuration_test.go deleted file mode 100644 index 525b9f8..0000000 --- a/cmd/configuration/configuration_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package configuration - -import ( - "encoding/json" - "testing" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" - "github.com/jarcoal/httpmock" - "github.com/stretchr/testify/assert" -) - -func TestMain(m *testing.M) { - - httpmock.Activate() - defer httpmock.DeactivateAndReset() - - mockfunction.InitMockConfiguration() - - m.Run() -} - -var testConfiguration models.Configuration -var testConfigurationList []models.Configuration - -func TestConfigurationCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(ConfigurationCmd) - assert.Contains(t, output, "Manage your CLI configurations in your account") -} - -func TestConfigurationHelpCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(ConfigurationCmd, "--help") - assert.Contains(t, output, "Manage your CLI configurations in your account") -} - -func TestConfigurationCreateCommand(t *testing.T) { - - failOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "create") - - assert.Contains(t, failOutput, "Configuration not created") - - successOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "create", "--name=test_configuration", "-i=testConfigurationClientID", "-s=testConfigurationClientSecret", "-a=testConfigurationAccountID", "-e=testConfigurationAccountEnvID") - assert.Equal(t, "Configuration created successfully\n", successOutput) - -} - -func TestConfigurationDeleteCommand(t *testing.T) { - config.CreateConfigurationFile(mockfunction.TestConfiguration.Name, mockfunction.TestConfiguration.ClientID, mockfunction.TestConfiguration.ClientSecret, mockfunction.TestConfiguration.AccountID, mockfunction.TestConfiguration.AccountEnvironmentID) - - failOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "delete") - assert.Contains(t, failOutput, "Error: required flag(s) \"name\" not set") - - successOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "delete", "--name=test_configuration") - assert.Equal(t, "Configuration deleted successfully\n", successOutput) -} - -func TestConfigurationListCommand(t *testing.T) { - config.CreateConfigurationFile(mockfunction.TestConfiguration.Name, mockfunction.TestConfiguration.ClientID, mockfunction.TestConfiguration.ClientSecret, mockfunction.TestConfiguration.AccountID, mockfunction.TestConfiguration.AccountEnvironmentID) - - output, _ := utils.ExecuteCommand(ConfigurationCmd, "list") - - err := json.Unmarshal([]byte(output), &testConfigurationList) - - assert.Nil(t, err) - - byt, err := json.Marshal(mockfunction.TestConfiguration) - - assert.Nil(t, err) - - assert.Contains(t, output, string(byt)) -} - -func TestConfigurationGetCommand(t *testing.T) { - config.CreateConfigurationFile(mockfunction.TestConfiguration.Name, mockfunction.TestConfiguration.ClientID, mockfunction.TestConfiguration.ClientSecret, mockfunction.TestConfiguration.AccountID, mockfunction.TestConfiguration.AccountEnvironmentID) - - failOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "get") - assert.Contains(t, failOutput, "Error: required flag(s) \"name\" not set") - - successOutput, _ := utils.ExecuteCommand(ConfigurationCmd, "get", "--name=test_configuration") - err := json.Unmarshal([]byte(successOutput), &testConfiguration) - - assert.Nil(t, err) - - assert.Equal(t, mockfunction.TestConfiguration, testConfiguration) -} diff --git a/cmd/configuration/create.go b/cmd/configuration/create.go deleted file mode 100644 index e0dc546..0000000 --- a/cmd/configuration/create.go +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "fmt" - "log" - "slices" - - "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - credentialsFile string -) - -// createCmd represents the create command -var createCmd = &cobra.Command{ - Use: "create [-n | --name=] [-i | --client-id=] [-s | --client-secret=] [-a | --account-id=] [-e | --account-environment-id=]", - Short: "Create a configuration", - Long: `Create a configuration based on the credentials`, - Run: func(cmd *cobra.Command, args []string) { - - existingConfigurationsName, err := config.GetConfigurationsName() - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - if credentialsFile != "" { - config.ReadCredentialsFromFile(credentialsFile) - if slices.Contains(existingConfigurationsName, viper.GetString("name")) { - fmt.Fprintln(cmd.OutOrStdout(), "Configuration name already exists") - return - } - config.CreateConfigurationFile(viper.GetString("name"), viper.GetString("client_id"), viper.GetString("client_secret"), viper.GetString("account_id"), viper.GetString("account_environment_id")) - fmt.Fprintln(cmd.OutOrStdout(), "Configuration created successfully") - return - } - if ConfigurationName != "" && ConfigurationClientID != "" && ConfigurationClientSecret != "" && ConfigurationAccountID != "" && ConfigurationAccountEnvID != "" { - - if slices.Contains(existingConfigurationsName, ConfigurationName) { - fmt.Fprintln(cmd.OutOrStdout(), "Configuration name already exists") - return - } - - config.CreateConfigurationFile(ConfigurationName, ConfigurationClientID, ConfigurationClientSecret, ConfigurationAccountID, ConfigurationAccountEnvID) - fmt.Fprintln(cmd.OutOrStdout(), "Configuration created successfully") - return - } - - fmt.Fprintln(cmd.OutOrStdout(), "Configuration not created, required fields (name, client ID, client secret, account ID, account environment ID)") - - }, -} - -func init() { - - createCmd.Flags().StringVarP(&ConfigurationName, "name", "n", "", "configuration name") - createCmd.Flags().StringVarP(&ConfigurationClientID, "client-id", "i", "", "client ID of a configuration") - createCmd.Flags().StringVarP(&ConfigurationClientSecret, "client-secret", "s", "", "client secret of a configuration") - createCmd.Flags().StringVarP(&ConfigurationAccountID, "account-id", "a", "", "account ID of a configuration") - createCmd.Flags().StringVarP(&ConfigurationAccountEnvID, "account-environment-id", "e", "", "account environment ID of a configuration") - - createCmd.Flags().StringVarP(&credentialsFile, "path", "p", "", "config file to create") - - ConfigurationCmd.AddCommand(createCmd) -} diff --git a/cmd/configuration/current.go b/cmd/configuration/current.go deleted file mode 100644 index 88fb266..0000000 --- a/cmd/configuration/current.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "log" - "os" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "gopkg.in/yaml.v2" -) - -// currentCmd represents current command -var currentCmd = &cobra.Command{ - Use: "current", - Short: "Get current configuration", - Long: `Get current configuration`, - Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.ConfigurationYaml - var configuration models.Configuration - var v = viper.New() - - configFilepath := config.SetPathForConfigName(".cli") - v.SetConfigFile(configFilepath) - - err := v.MergeInConfig() - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - configurationName := v.GetString("current_used_configuration") - - yamlFile, err := os.ReadFile(config.SetPathForConfigName(configurationName)) - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - configuration.Name = configurationYaml.Name - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret - configuration.AccountID = configurationYaml.AccountID - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID - - utils.FormatItem([]string{"Name", "ClientID", "ClientSecret", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) - - }, -} - -func init() { - ConfigurationCmd.AddCommand(currentCmd) -} diff --git a/cmd/configuration/delete.go b/cmd/configuration/delete.go deleted file mode 100644 index 653124a..0000000 --- a/cmd/configuration/delete.go +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "fmt" - "log" - "os" - - "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/cobra" -) - -// deleteCmd represents delete command -var deleteCmd = &cobra.Command{ - Use: "delete [-n | --name=]", - Short: "Delete a configuration", - Long: `Delete a configuration`, - Run: func(cmd *cobra.Command, args []string) { - - config.CheckFlagshipHomeDirectory() - - if err := os.Remove(config.SetPathForConfigName(ConfigurationName)); err != nil { - log.Fatal(err) - } - - fmt.Fprintln(cmd.OutOrStdout(), "Configuration deleted successfully") - }, -} - -func init() { - deleteCmd.Flags().StringVarP(&ConfigurationName, "name", "n", "", "name of the configuration you want to delete") - - if err := deleteCmd.MarkFlagRequired("name"); err != nil { - log.Fatalf("error occurred: %v", err) - } - ConfigurationCmd.AddCommand(deleteCmd) -} diff --git a/cmd/configuration/edit.go b/cmd/configuration/edit.go deleted file mode 100644 index 09d8d15..0000000 --- a/cmd/configuration/edit.go +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "fmt" - "log" - "slices" - - "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - newConfigurationName string -) - -// editCmd represents the edit command -var editCmd = &cobra.Command{ - Use: "edit [-n | --name=] [-i | --client-id=] [-s | --client-secret=] [-a | --account-id=] [-e | --account-environment-id=]", - Short: "Edit a configuration", - Long: `Edit a configuration`, - Run: func(cmd *cobra.Command, args []string) { - existingConfigurationsName, err := config.GetConfigurationsName() - - if err != nil { - log.Fatalf("error occurred : %s", err) - } - - if !slices.Contains(existingConfigurationsName, ConfigurationName) { - fmt.Fprintln(cmd.OutOrStdout(), "Configuration doesn't exists") - return - - } - - if slices.Contains(existingConfigurationsName, newConfigurationName) { - fmt.Fprintln(cmd.OutOrStdout(), "Configuration already exists") - return - } - - config.ReadCredentialsFromFile(config.SetPathForConfigName(ConfigurationName)) - - if newConfigurationName == "" { - newConfigurationName = viper.GetString("name") - } - if ConfigurationClientID == "" { - ConfigurationClientID = viper.GetString("client_id") - } - if ConfigurationClientSecret == "" { - ConfigurationClientSecret = viper.GetString("client_secret") - } - if ConfigurationAccountID == "" { - ConfigurationAccountID = viper.GetString("account_id") - } - if ConfigurationAccountEnvID == "" { - ConfigurationAccountEnvID = viper.GetString("account_environment_id") - } - - if newConfigurationName == "" && ConfigurationClientID == "" && ConfigurationClientSecret == "" && ConfigurationAccountID == "" && ConfigurationAccountEnvID == "" { - log.Fatal("required new name or client-id or client-secret or account-id or account-env-id") - return - } - - config.EditConfigurationFile(ConfigurationName, newConfigurationName, ConfigurationClientID, ConfigurationClientSecret, ConfigurationAccountID, ConfigurationAccountEnvID) - - fmt.Fprintln(cmd.OutOrStdout(), "Configuration edited successfully") - }, -} - -func init() { - - editCmd.Flags().StringVarP(&ConfigurationName, "name", "n", "", "name of the configuration you want to edit") - - editCmd.Flags().StringVarP(&newConfigurationName, "new-name", "", "", "new name for the configuration you want to edit") - editCmd.Flags().StringVarP(&ConfigurationClientID, "client-id", "i", "", "client ID configuration") - editCmd.Flags().StringVarP(&ConfigurationClientSecret, "client-secret", "s", "", "client secret of a configuration") - editCmd.Flags().StringVarP(&ConfigurationAccountID, "account-id", "a", "", "account ID of a configuration") - editCmd.Flags().StringVarP(&ConfigurationAccountEnvID, "account-environment-id", "e", "", "account environment ID of a configuration") - - if err := editCmd.MarkFlagRequired("name"); err != nil { - log.Fatalf("error occurred: %v", err) - } - - ConfigurationCmd.AddCommand(editCmd) -} diff --git a/cmd/configuration/get.go b/cmd/configuration/get.go deleted file mode 100644 index db4b69e..0000000 --- a/cmd/configuration/get.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "log" - "os" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "gopkg.in/yaml.v2" -) - -// getCmd represents get command -var getCmd = &cobra.Command{ - Use: "get [-n | --name=]", - Short: "Get a configuration", - Long: `Get a configuration`, - Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.ConfigurationYaml - var configuration models.Configuration - - yamlFile, err := os.ReadFile(config.SetPathForConfigName(ConfigurationName)) - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) - if err != nil { - log.Fatalf("error occurred: %s", err) - } - - configuration.Name = configurationYaml.Name - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret - configuration.AccountID = configurationYaml.AccountID - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID - - utils.FormatItem([]string{"Name", "ClientID", "ClientSecret", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) - - }, -} - -func init() { - getCmd.Flags().StringVarP(&ConfigurationName, "name", "n", "", "name of the configuration you want to display") - - if err := getCmd.MarkFlagRequired("name"); err != nil { - log.Fatalf("error occurred: %v", err) - } - ConfigurationCmd.AddCommand(getCmd) -} diff --git a/cmd/configuration/use.go b/cmd/configuration/use.go deleted file mode 100644 index 446cf7d..0000000 --- a/cmd/configuration/use.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package configuration - -import ( - "fmt" - "log" - "slices" - - "github.com/flagship-io/flagship/utils/config" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - grantType string - scope string - expiration int -) - -// useCmd represents use command -var useCmd = &cobra.Command{ - Use: "use [-n | --name=] [--grant-type=] [--scope=] [--expiration=]", - Short: "Use a configuration", - Long: `Use an already created configuration`, - Run: func(cmd *cobra.Command, args []string) { - existingConfigurationsName, err := config.GetConfigurationsName() - if err != nil { - log.Fatalf("error occurred: %s", err) - } - if !slices.Contains(existingConfigurationsName, ConfigurationName) { - fmt.Fprintln(cmd.OutOrStdout(), "Configuration doesn't exists") - return - } - - config.SelectConfiguration(ConfigurationName) - config.SetOptionalsDefault(grantType, scope, expiration) - - authenticationResponse, err := httprequest.HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), grantType, scope, expiration) - if err != nil { - log.Fatalf("%s", err) - return - } - - if authenticationResponse.AccessToken == "" { - log.Fatal("client_id or client_secret not valid") - return - } else { - config.WriteToken(ConfigurationName, authenticationResponse) - fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") - } - - fmt.Fprintln(cmd.OutOrStdout(), "Configuration selected successfully") - }, -} - -func init() { - useCmd.Flags().StringVarP(&ConfigurationName, "name", "n", "", "name of the configuration you want to display") - useCmd.Flags().StringVarP(&grantType, "grant-type", "", config.GrantType, "grant type of the token, DEFAULT value is client_credentials") - useCmd.Flags().StringVarP(&scope, "scope", "", config.Scope, "scope of the token, DEFAULT value is *") - useCmd.Flags().IntVarP(&expiration, "expiration", "", config.Expiration, "expiration time in second of the token, DEFAULT value is 86400") - - if err := useCmd.MarkFlagRequired("name"); err != nil { - log.Fatalf("error occurred: %v", err) - } - ConfigurationCmd.AddCommand(useCmd) -} diff --git a/cmd/feature_experimentation/account/account.go b/cmd/feature_experimentation/account/account.go new file mode 100644 index 0000000..d8ba6a4 --- /dev/null +++ b/cmd/feature_experimentation/account/account.go @@ -0,0 +1,22 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import "github.com/spf13/cobra" + +var ( + Username string + AccountID string + AccountEnvironmentID string +) + +// ConfigurationCmd represents the configuration command +var AccountCmd = &cobra.Command{ + Use: "account [use|list|current]", + Short: "Manage your CLI authentication", + Long: `Manage your CLI authentication`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go new file mode 100644 index 0000000..9d2e955 --- /dev/null +++ b/cmd/feature_experimentation/account/current.go @@ -0,0 +1,56 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// getCmd represents the list command +var currentCmd = &cobra.Command{ + Use: "get", + Short: "get an auth credential", + Long: `list an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var configurationYaml models.ConfigurationYaml_new + var configuration models.Configuration_new + + yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, Username)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &configurationYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + configuration.Username = configurationYaml.Username + configuration.ClientID = configurationYaml.ClientID + configuration.ClientSecret = configurationYaml.ClientSecret + + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + currentCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to display") + + if err := currentCmd.MarkFlagRequired("username"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + AccountCmd.AddCommand(currentCmd) +} diff --git a/cmd/feature_experimentation/account/list.go b/cmd/feature_experimentation/account/list.go new file mode 100644 index 0000000..99016ad --- /dev/null +++ b/cmd/feature_experimentation/account/list.go @@ -0,0 +1,34 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "list all auth", + Long: `list all auth from your system`, + Run: func(cmd *cobra.Command, args []string) { + + body, err := httprequest.CampaignRequester.HTTPListCampaign() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "ProjectId", "Name", "Description", "Type", "Status"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + + AccountCmd.AddCommand(listCmd) +} diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go new file mode 100644 index 0000000..44354bc --- /dev/null +++ b/cmd/feature_experimentation/account/use.go @@ -0,0 +1,39 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "fmt" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" +) + +// getCmd represents the list command +var useCmd = &cobra.Command{ + Use: "use", + Short: "get an auth credential", + Long: `list an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + if AccountID == "" && AccountEnvironmentID == "" { + fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id or account-environment-id") + return + } + + if AccountID != "" { + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) + } + if AccountEnvironmentID != "" { + config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) + } + }, +} + +func init() { + useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") + useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-env-id", "e", "", "account env id of the credentials you want to display") + + AccountCmd.AddCommand(useCmd) +} diff --git a/cmd/feature_experimentation/analyze/flag/create.go b/cmd/feature_experimentation/analyze/flag/create.go index 79af794..6de7d6b 100644 --- a/cmd/feature_experimentation/analyze/flag/create.go +++ b/cmd/feature_experimentation/analyze/flag/create.go @@ -14,7 +14,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" models "github.com/flagship-io/flagship/models/feature_experimentation" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/rodaine/table" "github.com/spf13/cobra" "golang.org/x/exp/slices" @@ -117,7 +117,7 @@ func flagCreatedTable(cmd *cobra.Command, listedFlags []models.Flag) error { return err_ } - createdFlags, errCreatedFlags := httprequest.HTTPCreateFlag(string(multipleflagRequestJSON)) + createdFlags, errCreatedFlags := httprequest.FlagRequester.HTTPCreateFlag(string(multipleflagRequestJSON)) if errCreatedFlags != nil { return errCreatedFlags @@ -129,7 +129,7 @@ func flagCreatedTable(cmd *cobra.Command, listedFlags []models.Flag) error { return err_json } - listExistingFlags, errListFlag := httprequest.HTTPListFlag() + listExistingFlags, errListFlag := httprequest.FlagRequester.HTTPListFlag() if errListFlag != nil { log.Fatalf("error occurred when listing existing flag: %s", errListFlag) } @@ -180,7 +180,7 @@ var createCmd = &cobra.Command{ PreRunConfiguration() }, Run: func(cmd *cobra.Command, args []string) { - listedExistingFlags, errListFlag := httprequest.HTTPListFlag() + listedExistingFlags, errListFlag := httprequest.FlagRequester.HTTPListFlag() if errListFlag != nil { log.Fatalf("error occurred when listing existing flag: %s", errListFlag) } diff --git a/cmd/feature_experimentation/analyze/flag/list.go b/cmd/feature_experimentation/analyze/flag/list.go index 985ccd5..54bf520 100644 --- a/cmd/feature_experimentation/analyze/flag/list.go +++ b/cmd/feature_experimentation/analyze/flag/list.go @@ -12,7 +12,7 @@ import ( "github.com/fatih/color" "github.com/flagship-io/codebase-analyzer/pkg/handler" models "github.com/flagship-io/flagship/models/feature_experimentation" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/kyokomi/emoji/v2" "github.com/rodaine/table" "github.com/spf13/cobra" @@ -171,7 +171,7 @@ var listCmd = &cobra.Command{ return } - listExistingFlags, errListFlag := httprequest.HTTPListFlag() + listExistingFlags, errListFlag := httprequest.FlagRequester.HTTPListFlag() if errListFlag != nil { log.Fatalf("error occurred when listing existing flag: %s", errListFlag) } diff --git a/cmd/feature_experimentation/auth/auth.go b/cmd/feature_experimentation/auth/auth.go new file mode 100644 index 0000000..610cfa4 --- /dev/null +++ b/cmd/feature_experimentation/auth/auth.go @@ -0,0 +1,23 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import "github.com/spf13/cobra" + +var ( + Username string + ClientID string + ClientSecret string + AccountId string +) + +// ConfigurationCmd represents the configuration command +var AuthCmd = &cobra.Command{ + Use: "auth [create|edit|get|list|delete|use]", + Short: "Manage your CLI authentication", + Long: `Manage your CLI authentication`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/feature_experimentation/auth/get.go b/cmd/feature_experimentation/auth/get.go new file mode 100644 index 0000000..9c22d54 --- /dev/null +++ b/cmd/feature_experimentation/auth/get.go @@ -0,0 +1,56 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// getCmd represents the list command +var getCmd = &cobra.Command{ + Use: "get", + Short: "get an auth credential", + Long: `list an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var configurationYaml models.ConfigurationYaml_new + var configuration models.Configuration_new + + yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, Username)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &configurationYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + configuration.Username = configurationYaml.Username + configuration.ClientID = configurationYaml.ClientID + configuration.ClientSecret = configurationYaml.ClientSecret + + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + getCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to display") + + if err := getCmd.MarkFlagRequired("username"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + AuthCmd.AddCommand(getCmd) +} diff --git a/cmd/configuration/list.go b/cmd/feature_experimentation/auth/list.go similarity index 51% rename from cmd/configuration/list.go rename to cmd/feature_experimentation/auth/list.go index 01c6828..fa5b45f 100644 --- a/cmd/configuration/list.go +++ b/cmd/feature_experimentation/auth/list.go @@ -1,7 +1,7 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com */ -package configuration +package auth import ( "log" @@ -18,18 +18,21 @@ import ( // listCmd represents the list command var listCmd = &cobra.Command{ Use: "list", - Short: "List all configurations", - Long: `List all configurations`, + Short: "list all auth", + Long: `list all auth from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurations []models.Configuration - existingConfigurationsName, nil := config.GetConfigurationsName() + var configurations []models.Configuration_new + existingCredentials, err := config.GetUsernames(utils.FEATURE_EXPERIMENTATION) + if err != nil { + log.Fatalf("error occurred: %s", err) + } - for _, fileName := range existingConfigurationsName { + for _, fileName := range existingCredentials { if fileName != "" { - var configurationYaml models.ConfigurationYaml - var configuration models.Configuration - yamlFile, err := os.ReadFile(config.SetPathForConfigName(fileName)) + var configurationYaml models.ConfigurationYaml_new + var configuration models.Configuration_new + yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, fileName)) if err != nil { log.Fatalf("error occurred: %s", err) } @@ -39,22 +42,21 @@ var listCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %s", err) } - if configurationYaml.Name != "" { - configuration.Name = configurationYaml.Name + if configurationYaml.Username != "" { + configuration.Username = configurationYaml.Username configuration.ClientID = configurationYaml.ClientID configuration.ClientSecret = configurationYaml.ClientSecret - configuration.AccountID = configurationYaml.AccountID - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID configurations = append(configurations, configuration) } } } - utils.FormatItem([]string{"Name", "ClientID", "ClientSecret", "AccountID", "AccountEnvironmentID"}, configurations, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configurations, viper.GetString("output_format"), cmd.OutOrStdout()) }, } func init() { - ConfigurationCmd.AddCommand(listCmd) + + AuthCmd.AddCommand(listCmd) } diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go new file mode 100644 index 0000000..78eef15 --- /dev/null +++ b/cmd/feature_experimentation/auth/login.go @@ -0,0 +1,173 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "fmt" + "log" + "net/http" + "os" + "os/exec" + "runtime" + "slices" + "time" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/spf13/cobra" +) + +var ( + credentialsFile string + browser bool +) + +var ( + code string +) + +func checkSingleFlag(bool1, bool2, bool3 bool) bool { + return (bool1 && !bool2 && !bool3) || (!bool1 && bool2 && !bool3) || (!bool1 && !bool2 && bool3) +} +func openLink(url string) error { + var cmd *exec.Cmd + switch runtime.GOOS { + case "linux": + cmd = exec.Command("xdg-open", url) + case "darwin": + cmd = exec.Command("open", url) + case "windows": + cmd = exec.Command("cmd", "/c", "start", url) + default: + return fmt.Errorf("unsupported operating system") + } + err := cmd.Run() + return err +} + +// createCmd represents the create command +var loginCmd = &cobra.Command{ + Use: "login [--browser] | [--credential-file] | [--inputs] [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", + Short: "login", + Long: `login`, + Run: func(cmd *cobra.Command, args []string) { + if !checkSingleFlag(browser, credentialsFile != "", Username != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (browser, inputs, credential-file)") + } + + if browser { + clientID := utils.CLIENT_ID + clientSecret := utils.CLIENT_SECRET + + if ClientID != "" { + clientID = ClientID + } + + if ClientSecret != "" { + clientSecret = ClientSecret + } + + var url = fmt.Sprintf("https://auth.abtasty.com/authorize?client_id=%s&client_secret=%s&redirect_uri=http://localhost:8010/auth/callback", clientID, clientSecret) + + if err := openLink(url); err != nil { + log.Fatalf("Error opening link: %s", err) + } + http.HandleFunc("/auth/callback", handleCallback) + if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { + log.Fatalf("Error starting callback server: %s", err) + } + fmt.Println(code) + + authenticationResponse, err := common.HTTPCreateTokenWE(clientID, clientSecret, code) + if err != nil { + log.Fatalf("%s", err) + return + } + + if authenticationResponse.AccessToken == "" { + log.Fatal("client_id or client_secret not valid") + } + + fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") + + } + + if credentialsFile != "" { + authenticationResponse := models.TokenResponse{} + config.ReadCredentialsFromFile(credentialsFile) + config.CreateCredentialsFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) + config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") + return + } + + if Username != "" { + existingCredentials, err := config.GetUsernames(utils.FEATURE_EXPERIMENTATION) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + if slices.Contains(existingCredentials, Username) { + config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + + fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + return + } + + if ClientID == "" && ClientSecret == "" && AccountId == "" { + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") + return + } + authenticationResponse, err := common.HTTPCreateTokenFE(ClientID, ClientSecret, AccountId) + if err != nil { + log.Fatalf("%s", err) + return + } + + if authenticationResponse.AccessToken == "" { + log.Fatal("client_id or client_secret not valid") + } + config.CreateCredentialsFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) + config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") + } + + }, +} + +func init() { + + loginCmd.Flags().StringVarP(&Username, "username", "u", "", "configuration name") + loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of a configuration") + loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of a configuration") + loginCmd.Flags().StringVarP(&AccountId, "account-id", "a", "", "account id of a configuration") + + loginCmd.Flags().StringVarP(&credentialsFile, "credential-file", "p", "", "config file to create") + loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "Generate link for browser") + + AuthCmd.AddCommand(loginCmd) +} + +func handleCallback(w http.ResponseWriter, r *http.Request) { + fmt.Println(r.URL.Query().Get("code")) + code = r.URL.Query().Get("code") + if code == "" { + http.Error(w, "No token found in URL", http.StatusBadRequest) + os.Exit(0) + return + } + + http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) + + fmt.Println("code received:", code) + + go func() { + time.Sleep(5 * time.Second) + os.Exit(0) + }() +} diff --git a/cmd/feature_experimentation/campaign/campaign.go b/cmd/feature_experimentation/campaign/campaign.go index 85c0dce..470216f 100644 --- a/cmd/feature_experimentation/campaign/campaign.go +++ b/cmd/feature_experimentation/campaign/campaign.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package campaign diff --git a/cmd/feature_experimentation/campaign/create.go b/cmd/feature_experimentation/campaign/create.go index a79f642..05dc53a 100644 --- a/cmd/feature_experimentation/campaign/create.go +++ b/cmd/feature_experimentation/campaign/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a campaign", Long: `Create a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPCreateCampaign(DataRaw) + body, err := httprequest.CampaignRequester.HTTPCreateCampaign(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go index f481e0d..793d893 100644 --- a/cmd/feature_experimentation/campaign/delete.go +++ b/cmd/feature_experimentation/campaign/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a campaign", Long: `Delete a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteCampaign(CampaignID) + err := httprequest.CampaignRequester.HTTPDeleteCampaign(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go index 53ec30f..3829fa2 100644 --- a/cmd/feature_experimentation/campaign/edit.go +++ b/cmd/feature_experimentation/campaign/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a campaign", Long: `Edit a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditCampaign(CampaignID, DataRaw) + body, err := httprequest.CampaignRequester.HTTPEditCampaign(CampaignID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/get.go b/cmd/feature_experimentation/campaign/get.go index f9ddc60..f644474 100644 --- a/cmd/feature_experimentation/campaign/get.go +++ b/cmd/feature_experimentation/campaign/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a campaign", Long: `Get a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetCampaign(CampaignID) + body, err := httprequest.CampaignRequester.HTTPGetCampaign(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/list.go b/cmd/feature_experimentation/campaign/list.go index 5f877b6..48533ff 100644 --- a/cmd/feature_experimentation/campaign/list.go +++ b/cmd/feature_experimentation/campaign/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all campaigns", Long: `List all campaigns`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListCampaign() + body, err := httprequest.CampaignRequester.HTTPListCampaign() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go index 219b785..5f428e2 100644 --- a/cmd/feature_experimentation/campaign/switch.go +++ b/cmd/feature_experimentation/campaign/switch.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -20,7 +20,7 @@ var SwitchCmd = &cobra.Command{ if !(Status == "active" || Status == "paused" || Status == "interrupted") { fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 3 values: active or paused or interrupted") } else { - err := httprequest.HTTPSwitchCampaign(CampaignID, Status) + err := httprequest.CampaignRequester.HTTPSwitchCampaign(CampaignID, Status) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 849c666..19bd182 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -4,7 +4,11 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package feature_experimentation import ( + "os" + + "github.com/flagship-io/flagship/cmd/feature_experimentation/account" "github.com/flagship-io/flagship/cmd/feature_experimentation/analyze" + "github.com/flagship-io/flagship/cmd/feature_experimentation/auth" "github.com/flagship-io/flagship/cmd/feature_experimentation/campaign" "github.com/flagship-io/flagship/cmd/feature_experimentation/flag" "github.com/flagship-io/flagship/cmd/feature_experimentation/goal" @@ -15,8 +19,12 @@ import ( "github.com/flagship-io/flagship/cmd/feature_experimentation/user" "github.com/flagship-io/flagship/cmd/feature_experimentation/variation" variationgroup "github.com/flagship-io/flagship/cmd/feature_experimentation/variation_group" + "github.com/flagship-io/flagship/utils/config" + "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // FeatureExperimentationCmd represents the feature experimentation command @@ -42,8 +50,33 @@ func addSubCommandPalettes() { FeatureExperimentationCmd.AddCommand(targetingkey.TargetingKeyCmd) FeatureExperimentationCmd.AddCommand(analyze.AnalyzeCmd) FeatureExperimentationCmd.AddCommand(resource.ResourceCmd) + FeatureExperimentationCmd.AddCommand(auth.AuthCmd) + FeatureExperimentationCmd.AddCommand(account.AccountCmd) } func init() { + cobra.OnInitialize(initConfig) addSubCommandPalettes() } + +func initConfig() { + v := viper.New() + homeDir, _ := os.UserHomeDir() + var requestConfig = common.RequestConfig{Product: "FE"} + + v.SetConfigFile(homeDir + "/.flagship/credentials/fe/.cli.yaml") + v.MergeInConfig() + if v.GetString("current_used_credential") != "" { + + vL := config.ReadConfiguration(v.GetString("current_used_credential")) + v.MergeConfigMap(vL.AllSettings()) + + v.Unmarshal(&requestConfig) + common.Init(requestConfig) + for _, r := range http_request.HTTPResources { + r.Init(&requestConfig) + } + return + } + +} diff --git a/cmd/feature_experimentation/flag/create.go b/cmd/feature_experimentation/flag/create.go index c46d66e..6450f8a 100644 --- a/cmd/feature_experimentation/flag/create.go +++ b/cmd/feature_experimentation/flag/create.go @@ -9,7 +9,7 @@ import ( "log" models "github.com/flagship-io/flagship/models/feature_experimentation" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -47,7 +47,7 @@ var createCmd = &cobra.Command{ data = string(data_) } - body, err := httprequest.HTTPCreateFlag(data) + body, err := httprequest.FlagRequester.HTTPCreateFlag(data) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/flag/delete.go b/cmd/feature_experimentation/flag/delete.go index f588ab7..0223909 100644 --- a/cmd/feature_experimentation/flag/delete.go +++ b/cmd/feature_experimentation/flag/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a flag", Long: `Delete a flag in your account`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteFlag(FlagID) + err := httprequest.FlagRequester.HTTPDeleteFlag(FlagID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/flag/edit.go b/cmd/feature_experimentation/flag/edit.go index ef17017..511482f 100644 --- a/cmd/feature_experimentation/flag/edit.go +++ b/cmd/feature_experimentation/flag/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a flag", Long: `Edit a flag in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditFlag(FlagID, DataRaw) + body, err := httprequest.FlagRequester.HTTPEditFlag(FlagID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/flag/get.go b/cmd/feature_experimentation/flag/get.go index 655749d..a63f590 100644 --- a/cmd/feature_experimentation/flag/get.go +++ b/cmd/feature_experimentation/flag/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a flag", Long: `Get a flag in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetFlag(FlagID) + body, err := httprequest.FlagRequester.HTTPGetFlag(FlagID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/flag/list.go b/cmd/feature_experimentation/flag/list.go index e0fbe8d..38e86f0 100644 --- a/cmd/feature_experimentation/flag/list.go +++ b/cmd/feature_experimentation/flag/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all flags", Long: `List all flags in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListFlag() + body, err := httprequest.FlagRequester.HTTPListFlag() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/goal/create.go b/cmd/feature_experimentation/goal/create.go index 4b8a22d..1542d06 100644 --- a/cmd/feature_experimentation/goal/create.go +++ b/cmd/feature_experimentation/goal/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a goal", Long: `Create a goal in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPCreateGoal(DataRaw) + body, err := httprequest.GoalRequester.HTTPCreateGoal(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/goal/delete.go b/cmd/feature_experimentation/goal/delete.go index 12f0dc7..e9b0599 100644 --- a/cmd/feature_experimentation/goal/delete.go +++ b/cmd/feature_experimentation/goal/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a flag", Long: `Delete a flag in your account`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteGoal(GoalID) + err := httprequest.GoalRequester.HTTPDeleteGoal(GoalID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/goal/edit.go b/cmd/feature_experimentation/goal/edit.go index 68a868d..675dc39 100644 --- a/cmd/feature_experimentation/goal/edit.go +++ b/cmd/feature_experimentation/goal/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a goal", Long: `Edit a goal in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditGoal(GoalID, DataRaw) + body, err := httprequest.GoalRequester.HTTPEditGoal(GoalID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/goal/get.go b/cmd/feature_experimentation/goal/get.go index 80af134..d4c8a5a 100644 --- a/cmd/feature_experimentation/goal/get.go +++ b/cmd/feature_experimentation/goal/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a goal", Long: `Get a goal in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetGoal(GoalID) + body, err := httprequest.GoalRequester.HTTPGetGoal(GoalID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/goal/list.go b/cmd/feature_experimentation/goal/list.go index 2983cf8..5148433 100644 --- a/cmd/feature_experimentation/goal/list.go +++ b/cmd/feature_experimentation/goal/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all goals", Long: `List all goals in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListGoal() + body, err := httprequest.GoalRequester.HTTPListGoal() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/panic/panic.go b/cmd/feature_experimentation/panic/panic.go index 6366be0..9814cdb 100644 --- a/cmd/feature_experimentation/panic/panic.go +++ b/cmd/feature_experimentation/panic/panic.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -23,7 +23,7 @@ var PanicCmd = &cobra.Command{ fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 2 values: on or off ") return } - _, err := httprequest.HTTPUpdatePanic(panicStatus) + _, err := httprequest.PanicRequester.HTTPUpdatePanic(panicStatus) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/create.go b/cmd/feature_experimentation/project/create.go index f19c18f..ffa3d85 100644 --- a/cmd/feature_experimentation/project/create.go +++ b/cmd/feature_experimentation/project/create.go @@ -9,7 +9,7 @@ import ( "log" models "github.com/flagship-io/flagship/models/feature_experimentation" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -28,7 +28,7 @@ var createCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) } - body, err := httprequest.HTTPCreateProject(projectRequestJSON) + body, err := httprequest.ProjectRequester.HTTPCreateProject(projectRequestJSON) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/delete.go b/cmd/feature_experimentation/project/delete.go index 548d2fa..7503d60 100644 --- a/cmd/feature_experimentation/project/delete.go +++ b/cmd/feature_experimentation/project/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a project", Long: `Delete a project in your account`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteProject(ProjectId) + err := httprequest.ProjectRequester.HTTPDeleteProject(ProjectId) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/edit.go b/cmd/feature_experimentation/project/edit.go index 885250c..e82070f 100644 --- a/cmd/feature_experimentation/project/edit.go +++ b/cmd/feature_experimentation/project/edit.go @@ -9,7 +9,7 @@ import ( "log" models "github.com/flagship-io/flagship/models/feature_experimentation" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -28,7 +28,7 @@ var editCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) } - body, err := httprequest.HTTPEditProject(ProjectId, projectRequestJSON) + body, err := httprequest.ProjectRequester.HTTPEditProject(ProjectId, projectRequestJSON) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/get.go b/cmd/feature_experimentation/project/get.go index 203d27a..d67f13b 100644 --- a/cmd/feature_experimentation/project/get.go +++ b/cmd/feature_experimentation/project/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a project", Long: `Get a project in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetProject(ProjectId) + body, err := httprequest.ProjectRequester.HTTPGetProject(ProjectId) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/list.go b/cmd/feature_experimentation/project/list.go index bf769b3..ac6bb0d 100644 --- a/cmd/feature_experimentation/project/list.go +++ b/cmd/feature_experimentation/project/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all projects", Long: `List all projects in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListProject() + body, err := httprequest.ProjectRequester.HTTPListProject() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/project/switch.go b/cmd/feature_experimentation/project/switch.go index 331eadd..edb1bd9 100644 --- a/cmd/feature_experimentation/project/switch.go +++ b/cmd/feature_experimentation/project/switch.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -22,7 +22,7 @@ var switchCmd = &cobra.Command{ return } - err := httprequest.HTTPSwitchProject(ProjectId, ProjectStatus) + err := httprequest.ProjectRequester.HTTPSwitchProject(ProjectId, ProjectStatus) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index e53135c..e994b82 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -18,7 +18,7 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" - featureexp "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -36,7 +36,7 @@ type ResourceData struct { } func (f *ProjectData) Save(data string) ([]byte, error) { - return featureexp.HTTPCreateProject([]byte(data)) + return httprequest.ProjectRequester.HTTPCreateProject([]byte(data)) } type CampaignData struct { @@ -49,7 +49,7 @@ type CampaignData struct { } func (f *CampaignData) Save(data string) ([]byte, error) { - return featureexp.HTTPCreateCampaign(data) + return httprequest.CampaignRequester.HTTPCreateCampaign(data) } type FlagData struct { @@ -57,7 +57,7 @@ type FlagData struct { } func (f *FlagData) Save(data string) ([]byte, error) { - return featureexp.HTTPCreateFlag(data) + return httprequest.FlagRequester.HTTPCreateFlag(data) } type GoalData struct { @@ -65,7 +65,7 @@ type GoalData struct { } func (f *GoalData) Save(data string) ([]byte, error) { - return featureexp.HTTPCreateGoal(data) + return httprequest.GoalRequester.HTTPCreateGoal(data) } type TargetingKeysData struct { @@ -73,7 +73,7 @@ type TargetingKeysData struct { } func (f *TargetingKeysData) Save(data string) ([]byte, error) { - return featureexp.HTTPCreateTargetingKey(data) + return httprequest.TargetingKeyRequester.HTTPCreateTargetingKey(data) } type VariationGroupData struct { @@ -289,11 +289,11 @@ func ScriptResource(resources []Resource) { } if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { - response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+url, dataResource) + response, err = common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+url, dataResource) } if resource.Name == Goal || resource.Name == Campaign { - response, err = httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+url, dataResource) + response, err = common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+url, dataResource) } if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/create.go b/cmd/feature_experimentation/targeting_key/create.go index 0ef4872..b5a629e 100644 --- a/cmd/feature_experimentation/targeting_key/create.go +++ b/cmd/feature_experimentation/targeting_key/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a targeting key", Long: `Create a targeting key in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPCreateTargetingKey(DataRaw) + body, err := httprequest.TargetingKeyRequester.HTTPCreateTargetingKey(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/targeting_key/delete.go b/cmd/feature_experimentation/targeting_key/delete.go index 0805630..d1bea81 100644 --- a/cmd/feature_experimentation/targeting_key/delete.go +++ b/cmd/feature_experimentation/targeting_key/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a targeting key", Long: `Delete a targeting key in your account`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteTargetingKey(TargetingKeyID) + err := httprequest.TargetingKeyRequester.HTTPDeleteTargetingKey(TargetingKeyID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/targeting_key/edit.go b/cmd/feature_experimentation/targeting_key/edit.go index 1e60e08..f80b80a 100644 --- a/cmd/feature_experimentation/targeting_key/edit.go +++ b/cmd/feature_experimentation/targeting_key/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a targeting key", Long: `Edit a targeting key in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditTargetingKey(TargetingKeyID, DataRaw) + body, err := httprequest.TargetingKeyRequester.HTTPEditTargetingKey(TargetingKeyID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/targeting_key/get.go b/cmd/feature_experimentation/targeting_key/get.go index 08f4260..bfd3e18 100644 --- a/cmd/feature_experimentation/targeting_key/get.go +++ b/cmd/feature_experimentation/targeting_key/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a targeting key", Long: `Get a targeting key in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetTargetingKey(TargetingKeyID) + body, err := httprequest.TargetingKeyRequester.HTTPGetTargetingKey(TargetingKeyID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/targeting_key/list.go b/cmd/feature_experimentation/targeting_key/list.go index dc0e321..afd70ac 100644 --- a/cmd/feature_experimentation/targeting_key/list.go +++ b/cmd/feature_experimentation/targeting_key/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all targeting keys", Long: `List all targeting keys in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListTargetingKey() + body, err := httprequest.TargetingKeyRequester.HTTPListTargetingKey() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/user/create.go b/cmd/feature_experimentation/user/create.go index aea2ed6..bd921a4 100644 --- a/cmd/feature_experimentation/user/create.go +++ b/cmd/feature_experimentation/user/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a user with right", Long: `Create a user with right in your account`, Run: func(cmd *cobra.Command, args []string) { - _, err := httprequest.HTTPBatchUpdateUsers(DataRaw) + _, err := httprequest.UserRequester.HTTPBatchUpdateUsers(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/user/delete.go b/cmd/feature_experimentation/user/delete.go index 7d41356..3d6bb4d 100644 --- a/cmd/feature_experimentation/user/delete.go +++ b/cmd/feature_experimentation/user/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a user", Long: `Delete a user in your account`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteUsers(UserEmail) + err := httprequest.UserRequester.HTTPDeleteUsers(UserEmail) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/user/edit.go b/cmd/feature_experimentation/user/edit.go index dcbe16d..0f5c851 100644 --- a/cmd/feature_experimentation/user/edit.go +++ b/cmd/feature_experimentation/user/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a user with right", Long: `Edit a user with right in your account`, Run: func(cmd *cobra.Command, args []string) { - _, err := httprequest.HTTPBatchUpdateUsers(DataRaw) + _, err := httprequest.UserRequester.HTTPBatchUpdateUsers(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/user/list.go b/cmd/feature_experimentation/user/list.go index fe60d3d..0be71e5 100644 --- a/cmd/feature_experimentation/user/list.go +++ b/cmd/feature_experimentation/user/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all users", Long: `List all users in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListUsers() + body, err := httprequest.UserRequester.HTTPListUsers() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/create.go b/cmd/feature_experimentation/variation/create.go index 5f2a146..5fb0d74 100644 --- a/cmd/feature_experimentation/variation/create.go +++ b/cmd/feature_experimentation/variation/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a variation", Long: `Create a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPCreateVariation(CampaignID, VariationGroupID, DataRaw) + body, err := httprequest.VariationRequester.HTTPCreateVariation(CampaignID, VariationGroupID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index b2aff80..a2ab04f 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a variation", Long: `Delete a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteVariation(CampaignID, VariationGroupID, VariationID) + err := httprequest.VariationRequester.HTTPDeleteVariation(CampaignID, VariationGroupID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/edit.go b/cmd/feature_experimentation/variation/edit.go index e966d5a..dd0df0f 100644 --- a/cmd/feature_experimentation/variation/edit.go +++ b/cmd/feature_experimentation/variation/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a variation", Long: `Edit a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditVariation(CampaignID, VariationGroupID, VariationID, DataRaw) + body, err := httprequest.VariationRequester.HTTPEditVariation(CampaignID, VariationGroupID, VariationID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/get.go b/cmd/feature_experimentation/variation/get.go index 6b04d1a..392a87c 100644 --- a/cmd/feature_experimentation/variation/get.go +++ b/cmd/feature_experimentation/variation/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a variation", Long: `Get a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetVariation(CampaignID, VariationGroupID, VariationID) + body, err := httprequest.VariationRequester.HTTPGetVariation(CampaignID, VariationGroupID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/list.go b/cmd/feature_experimentation/variation/list.go index c888113..3e0d58d 100644 --- a/cmd/feature_experimentation/variation/list.go +++ b/cmd/feature_experimentation/variation/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all variations", Long: `List all variations in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListVariation(CampaignID, VariationGroupID) + body, err := httprequest.VariationRequester.HTTPListVariation(CampaignID, VariationGroupID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation_group/create.go b/cmd/feature_experimentation/variation_group/create.go index cb25909..9de2fad 100644 --- a/cmd/feature_experimentation/variation_group/create.go +++ b/cmd/feature_experimentation/variation_group/create.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a variation group", Long: `Create a variation group in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPCreateVariationGroup(CampaignID, DataRaw) + body, err := httprequest.VariationGroupRequester.HTTPCreateVariationGroup(CampaignID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go index f1bf03a..2dbc8ce 100644 --- a/cmd/feature_experimentation/variation_group/delete.go +++ b/cmd/feature_experimentation/variation_group/delete.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a variation group", Long: `Delete a variation group in your campaign`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.HTTPDeleteVariationGroup(CampaignID, VariationGroupID) + err := httprequest.VariationGroupRequester.HTTPDeleteVariationGroup(CampaignID, VariationGroupID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation_group/edit.go b/cmd/feature_experimentation/variation_group/edit.go index db939c5..8357866 100644 --- a/cmd/feature_experimentation/variation_group/edit.go +++ b/cmd/feature_experimentation/variation_group/edit.go @@ -7,7 +7,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a variation group", Long: `Edit a variation group in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPEditVariationGroup(CampaignID, VariationGroupID, DataRaw) + body, err := httprequest.VariationGroupRequester.HTTPEditVariationGroup(CampaignID, VariationGroupID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation_group/get.go b/cmd/feature_experimentation/variation_group/get.go index ca46419..28aed92 100644 --- a/cmd/feature_experimentation/variation_group/get.go +++ b/cmd/feature_experimentation/variation_group/get.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a variation group", Long: `Get a variation group in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetVariationGroup(CampaignID, VariationGroupID) + body, err := httprequest.VariationGroupRequester.HTTPGetVariationGroup(CampaignID, VariationGroupID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation_group/list.go b/cmd/feature_experimentation/variation_group/list.go index 0a7db05..83691ff 100644 --- a/cmd/feature_experimentation/variation_group/list.go +++ b/cmd/feature_experimentation/variation_group/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all variation groups", Long: `List all variation groups in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListVariationGroup(CampaignID) + body, err := httprequest.VariationGroupRequester.HTTPListVariationGroup(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/root.go b/cmd/root.go index 59a5210..bb73573 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -6,7 +6,6 @@ package cmd import ( "os" - "github.com/flagship-io/flagship/cmd/configuration" "github.com/flagship-io/flagship/cmd/feature_experimentation" "github.com/flagship-io/flagship/cmd/info" "github.com/flagship-io/flagship/cmd/token" @@ -14,15 +13,13 @@ import ( "github.com/flagship-io/flagship/cmd/version" "github.com/flagship-io/flagship/utils/config" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( - cfgFile string - cmdToken string outputFormat string ) @@ -51,7 +48,6 @@ func Execute() { } func addSubCommandPalettes() { - rootCmd.AddCommand(configuration.ConfigurationCmd) rootCmd.AddCommand(version.VersionCmd) rootCmd.AddCommand(token.TokenCmd) rootCmd.AddCommand(info.InfoCmd) @@ -62,35 +58,19 @@ func addSubCommandPalettes() { func init() { cobra.OnInitialize(initConfig) - rootCmd.PersistentFlags().StringVarP(&cmdToken, "token", "t", "", "access token to manage flagship resources") rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "f", config.OutputFormat, "output format for the get and list subcommands for flagship resources. Only 3 format are possible: table, json, json-pretty") - rootCmd.PersistentFlags().StringVarP(&httprequest.UserAgent, "user-agent", "u", config.DefaultUserAgent, "custom user agent") + rootCmd.PersistentFlags().StringVarP(&common.UserAgent, "user-agent", "", config.DefaultUserAgent, "custom user agent") viper.BindPFlag("token", rootCmd.PersistentFlags().Lookup("token")) viper.BindPFlag("output_format", rootCmd.PersistentFlags().Lookup("output-format")) - rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file that contains your credentials (default is $HOME/.flagship/credentials.yaml)") - addSubCommandPalettes() } // initConfig reads in config file and ENV variables if set. func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - viper.MergeInConfig() - return - } // Find home directory. - homeDir, err := os.UserHomeDir() + _, err := config.CheckFlagshipHomeDirectory() cobra.CheckErr(err) - // Search config in home directory with name ".flagship" (without extension). - viper.SetConfigFile(homeDir + "/.flagship/configurations/.cli.yaml") - viper.MergeInConfig() - if viper.GetString("current_used_configuration") != "" { - config.ReadConfiguration(viper.GetString("current_used_configuration")) - } - } diff --git a/cmd/token/info.go b/cmd/token/info.go index ca49691..3ae8065 100644 --- a/cmd/token/info.go +++ b/cmd/token/info.go @@ -8,7 +8,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -20,7 +20,7 @@ var infoCmd = &cobra.Command{ Long: `Get the information related to your token`, Run: func(cmd *cobra.Command, args []string) { if viper.GetString("token") != "" { - body, err := httprequest.HTTPCheckToken(viper.GetString("token")) + body, err := common.HTTPCheckToken(viper.GetString("token")) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/models/configuration.go b/models/configuration.go index e17e5d0..889f864 100644 --- a/models/configuration.go +++ b/models/configuration.go @@ -15,3 +15,15 @@ type ConfigurationYaml struct { AccountID string `yaml:"account_id"` AccountEnvironmentID string `yaml:"account_environment_id"` } + +type Configuration_new struct { + Username string `json:"username"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` +} + +type ConfigurationYaml_new struct { + Username string `yaml:"username"` + ClientID string `yaml:"client_id"` + ClientSecret string `yaml:"client_secret"` +} diff --git a/models/token.go b/models/token.go index e343206..07a77e2 100644 --- a/models/token.go +++ b/models/token.go @@ -19,6 +19,13 @@ type ClientCredentialsRequest struct { ClientSecret string `json:"client_secret"` } +type AuthorizationCodeRequest struct { + GrantType string `json:"grant_type"` + Code string `json:"code"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` +} + type RefreshTokenRequest struct { GrantType string `json:"grant_type"` ClientID string `json:"client_id"` diff --git a/utils/config/config.go b/utils/config/config.go index e5d323a..77668da 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -11,7 +11,7 @@ import ( "regexp" "github.com/flagship-io/flagship/models" - "github.com/spf13/cobra" + "github.com/flagship-io/flagship/utils" "github.com/spf13/viper" ) @@ -33,24 +33,40 @@ func Unset(key string) error { return nil } -func CheckFlagshipHomeDirectory() string { +func CheckFlagshipHomeDirectory() (string, error) { homeDir, err := os.UserHomeDir() - cobra.CheckErr(err) - if _, err := os.Stat(homeDir + "/.flagship/configurations"); errors.Is(err, os.ErrNotExist) { - err := os.MkdirAll(homeDir+"/.flagship/configurations", os.ModePerm) + if _, err := os.Stat(homeDir + "/.flagship/credentials/fe"); errors.Is(err, os.ErrNotExist) { + err := os.MkdirAll(homeDir+"/.flagship/credentials/fe", os.ModePerm) if err != nil { log.Fatal(err) } } - return homeDir + if _, err := os.Stat(homeDir + "/.flagship/credentials/we"); errors.Is(err, os.ErrNotExist) { + err := os.MkdirAll(homeDir+"/.flagship/credentials/we", os.ModePerm) + if err != nil { + log.Fatal(err) + } + } + + return homeDir, err } func SetPathForConfigName(fileName string) string { - homeDir := CheckFlagshipHomeDirectory() + homeDir, _ := CheckFlagshipHomeDirectory() + + filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/fe/" + fileName + ".yaml") + if err != nil { + log.Fatalf("error occured: %v", err) + } + + return filepath +} - filepath, err := filepath.Abs(homeDir + "/.flagship/configurations/" + fileName + ".yaml") +func SetPathForCredentials(product, fileName string) string { + homeDir, _ := CheckFlagshipHomeDirectory() + filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/" + product + "/" + fileName + ".yaml") if err != nil { log.Fatalf("error occured: %v", err) } @@ -59,7 +75,7 @@ func SetPathForConfigName(fileName string) string { } func GetConfigurationsName() ([]string, error) { - homeDir := CheckFlagshipHomeDirectory() + homeDir, _ := CheckFlagshipHomeDirectory() r := regexp.MustCompile(`(?P[^/]+)\.yaml`) var fileNames []string @@ -91,20 +107,63 @@ func GetConfigurationsName() ([]string, error) { return fileNames, nil } +func GetUsernames(product string) ([]string, error) { + homeDir, err := CheckFlagshipHomeDirectory() + r := regexp.MustCompile(`(?P[^/]+)\.yaml`) + var fileNames []string + + f, err := os.Open(homeDir + "/.flagship/credentials/" + product) + if err != nil { + fmt.Println(err) + return nil, err + } + + files, err := f.Readdir(0) + if err != nil { + fmt.Println(err) + return nil, err + } + + for _, v := range files { + match := r.FindStringSubmatch(v.Name()) + userName := r.SubexpIndex("UserName") + if len(match) == 0 { + log.Fatalln("Error: File not found") + } + + fileNames = append(fileNames, match[userName]) + } + return fileNames, nil +} + func SetOptionalsDefault(grantType, scope string, expiration int) { viper.Set("grant_type", grantType) viper.Set("scope", scope) viper.Set("expiration", expiration) } -func CreateConfigurationFile(configurationName, clientId, clientSecret, accountId, accountEnvId string) { +func CreateConfigurationFile(configurationName, clientId, clientSecret string) { filepath := SetPathForConfigName(configurationName) v.Set("name", configurationName) v.Set("client_id", clientId) v.Set("client_secret", clientSecret) - v.Set("account_id", accountId) - v.Set("account_environment_id", accountEnvId) + + err := v.WriteConfigAs(filepath) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + +} + +func CreateCredentialsFile(product, username, clientId, clientSecret string, authenticationResponse models.TokenResponse) { + filepath := SetPathForCredentials(product, username) + + v.Set("username", username) + v.Set("client_id", clientId) + v.Set("client_secret", clientSecret) + v.Set("token", authenticationResponse.AccessToken) + v.Set("refresh_token", authenticationResponse.RefreshToken) err := v.WriteConfigAs(filepath) if err != nil { @@ -115,7 +174,7 @@ func CreateConfigurationFile(configurationName, clientId, clientSecret, accountI func SelectConfiguration(configurationName string) { filepath := SetPathForConfigName(".cli") - v.Set("current_used_configuration", configurationName) + v.Set("current_used_credential", configurationName) err := v.WriteConfigAs(filepath) if err != nil { @@ -125,8 +184,30 @@ func SelectConfiguration(configurationName string) { ReadConfiguration(configurationName) } -func ReadConfiguration(configurationName string) { +func ReadConfiguration(configurationName string) *viper.Viper { + v := viper.New() configFilepath := SetPathForConfigName(configurationName) + v.SetConfigFile(configFilepath) + v.MergeInConfig() + return v +} + +func SelectCredentials(product, configurationName string) { + var v = viper.New() + + filepath := SetPathForCredentials(product, utils.HOME_CLI) + v.Set("current_used_credential", configurationName) + + err := v.WriteConfigAs(filepath) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + ReadCredentials(product, configurationName) +} + +func ReadCredentials(product, configurationName string) { + configFilepath := SetPathForCredentials(product, configurationName) viper.SetConfigFile(configFilepath) viper.MergeInConfig() } @@ -151,9 +232,38 @@ func EditConfigurationFile(configurationName, newName, clientId, clientSecret, a } } +func SetAccountID(product, accountID string) { + var v = viper.New() + configFilepath := SetPathForCredentials(product, utils.HOME_CLI) + v.SetConfigFile(configFilepath) + v.MergeInConfig() + + v.Set("account_id", accountID) + + err := v.WriteConfigAs(configFilepath) + if err != nil { + log.Fatalf("error occurred: %v", err) + } +} + +func SetAccountEnvID(product, accountEnvID string) { + var v = viper.New() + configFilepath := SetPathForCredentials(product, utils.HOME_CLI) + v.SetConfigFile(configFilepath) + v.MergeInConfig() + + v.Set("account_environment_id", accountEnvID) + + err := viper.WriteConfigAs(configFilepath) + if err != nil { + log.Fatalf("error occurred: %v", err) + } +} + func ReadCredentialsFromFile(configurationFile string) { viper.SetConfigFile(configurationFile) err := viper.MergeInConfig() + if err != nil { log.Fatalf("error occurred: %v", err) } @@ -170,8 +280,28 @@ func WriteToken(configurationName string, authenticationResponse models.TokenRes viper.Set("token", authenticationResponse.AccessToken) viper.Set("refresh_token", authenticationResponse.RefreshToken) - viper.Set("current_used_configuration", nil) - Unset("current_used_configuration") + viper.Set("current_used_credential", nil) + Unset("current_used_credential") + + err = viper.WriteConfigAs(configFilepath) + if err != nil { + log.Fatalf("error occurred: %v", err) + } +} + +func WriteToken_new(product, username string) { + configFilepath := SetPathForCredentials(product, username) + + viper.SetConfigFile(configFilepath) + err := viper.MergeInConfig() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + viper.Set("token", "token") + viper.Set("refresh_token", "refresh_token") + viper.Set("current_used_credential", nil) + Unset("current_used_credential") err = viper.WriteConfigAs(configFilepath) if err != nil { diff --git a/utils/const.go b/utils/const.go index b8da3b1..5f49d25 100644 --- a/utils/const.go +++ b/utils/const.go @@ -3,7 +3,7 @@ package utils import "os" func GetFeatureExperimentationHost() string { - if os.Getenv("STAGING") == "true" { + if os.Getenv("FS_STAGING") == "true" { return "https://staging-api.flagship.io" } @@ -11,7 +11,7 @@ func GetFeatureExperimentationHost() string { } func GetWebExperimentationHost() string { - if os.Getenv("STAGING") == "true" { + if os.Getenv("FS_STAGING") == "true" { return "https://staging-api.abtasty.com/api" } @@ -19,9 +19,23 @@ func GetWebExperimentationHost() string { } func GetHostFeatureExperimentationAuth() string { - if os.Getenv("STAGING") == "true" { + if os.Getenv("FS_STAGING") == "true" { return "https://staging-auth.flagship.io" } return "https://auth.flagship.io" } + +func GetHostWebExperimentationAuth() string { + if os.Getenv("FS_STAGING") == "true" { + return "https://api-auth.abtasty.com" + } + + return "https://api-auth.abtasty.com" +} + +const FEATURE_EXPERIMENTATION = "fe" +const WEB_EXPERIMENTATION = "we" +const HOME_CLI = ".cli" +const CLIENT_ID = "590_397jchm4asqo04g0ogcggcoo88wo44sg0c0owk0448gkwck8s8" +const CLIENT_SECRET = "5xc41rk3etwc404o8scs0s8c0sogcgc48g4sk0ggc44so4w00c" diff --git a/utils/http_request/request.go b/utils/http_request/common/request.go similarity index 70% rename from utils/http_request/request.go rename to utils/http_request/common/request.go index ef08ad6..7bcd56f 100644 --- a/utils/http_request/request.go +++ b/utils/http_request/common/request.go @@ -1,4 +1,4 @@ -package http_request +package common import ( "bytes" @@ -12,53 +12,10 @@ import ( "time" "github.com/flagship-io/flagship/utils/config" - "github.com/spf13/viper" ) var UserAgent string -func regenerateToken_(configName string) { - gt := viper.GetString("grant_type") - sc := viper.GetString("scope") - ex := viper.GetInt("expiration") - - if gt == "" { - gt = config.GrantType - } - - if sc == "" { - sc = config.Scope - } - - if ex == 0 { - ex = config.Expiration - } - - authenticationResponse, err := HTTPCreateToken(viper.GetString("client_id"), viper.GetString("client_secret"), gt, sc, ex) - - if err != nil { - log.Fatalf("%s", err) - } - if authenticationResponse.AccessToken == "" { - log.Fatal("client_id or client_secret not valid") - } else { - config.WriteToken(configName, authenticationResponse) - } -} - -func regenerateToken(configName string) { - authenticationResponse, err := HTTPRefreshToken(viper.GetString("client_id"), viper.GetString("refresh_token")) - - if err != nil { - log.Fatalf("%s", err) - } - if authenticationResponse.AccessToken == "" { - log.Fatal("client_id or client_secret not valid") - } else { - config.WriteToken(configName, authenticationResponse) - } -} - var c = http.Client{Timeout: time.Duration(10) * time.Second} var counter = false @@ -67,6 +24,16 @@ type PageResult struct { TotalCount int `json:"total_count"` } +type ResourceRequest struct { + AccountID string `mapstructure:"account_id"` + AccountEnvID string `mapstructure:"account_environment_id"` +} + +func (c *ResourceRequest) Init(cL *RequestConfig) { + c.AccountEnvID = cL.AccountEnvID + c.AccountID = cL.AccountID +} + type PageResultWE struct { Data json.RawMessage `json:"_data"` Pagination Pagination `json:"_pagination"` @@ -79,6 +46,40 @@ type Pagination struct { MaxPerPage int `json:"_max_per_page"` } +type RequestConfig struct { + Product string + Username string `mapstructure:"username"` + ClientID string `mapstructure:"client_id"` + ClientSecret string `mapstructure:"client_secret"` + AccountID string `mapstructure:"account_id"` + AccountEnvID string `mapstructure:"account_environment_id"` + Token string `mapstructure:"token"` + RefreshToken string `mapstructure:"refresh_token"` + CurrentUsedCredentials string `mapstructure:"current_used_credentials"` +} + +var cred RequestConfig + +func Init(credL RequestConfig) { + cred = credL +} + +func regenerateToken(configName string) { + authenticationResponse, err := HTTPRefreshToken(cred.ClientID, cred.RefreshToken) + + if err != nil { + log.Fatalf("%s", err) + } + + if authenticationResponse.AccessToken == "" { + log.Fatal("client_id or client_secret not valid") + } else { + cred.RefreshToken = authenticationResponse.RefreshToken + cred.Token = authenticationResponse.AccessToken + config.WriteToken(configName, authenticationResponse) + } +} + func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { var bodyIO io.Reader = nil if body != nil { @@ -90,20 +91,20 @@ func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { log.Panicf("error occurred on request creation: %v", err) } - if !strings.Contains(resource, "token") && viper.GetString("account_id") == "" && viper.GetString("account_environment_id") == "" { + if cred.Product == "FE" && !strings.Contains(resource, "token") && (cred.AccountID == "" || cred.AccountEnvID == "") { log.Fatalf("account_id or account_environment_id required, Please configure your CLI") } - if strings.Contains(resource, "token") && viper.GetString("client_id") == "" && viper.GetString("client_secret") == "" { + if cred.Product == "FE" && strings.Contains(resource, "token") && cred.ClientID == "" && cred.ClientSecret == "" { log.Fatalf("client_id or client_secret required, Please configure your CLI") } - if !strings.Contains(resource, "token") && viper.GetString("token") == "" { - regenerateToken(viper.GetString("current_used_configuration")) + if !strings.Contains(resource, "token") && cred.Token == "" { + regenerateToken(cred.CurrentUsedCredentials) } req.Header.Add("Accept", `*/*`) - req.Header.Add("Authorization", "Bearer "+viper.GetString("token")) + req.Header.Add("Authorization", "Bearer "+cred.Token) req.Header.Add("Accept-Encoding", `gzip, deflate, br`) req.Header.Add("Content-Type", "application/json") req.Header.Set("User-Agent", UserAgent) @@ -134,11 +135,12 @@ func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { return nil, err } - //fmt.Println(string(respBody)) + fmt.Println(cred.AccountID) + fmt.Println(string(respBody)) if (resp.StatusCode == 403 || resp.StatusCode == 401) && !counter { counter = true - regenerateToken(viper.GetString("current_used_configuration")) + regenerateToken(cred.CurrentUsedCredentials) return HTTPRequest(method, resource, body) } return respBody, err diff --git a/utils/http_request/request_test.go b/utils/http_request/common/request_test.go similarity index 98% rename from utils/http_request/request_test.go rename to utils/http_request/common/request_test.go index 8ab7fe8..b462ce4 100644 --- a/utils/http_request/request_test.go +++ b/utils/http_request/common/request_test.go @@ -1,4 +1,4 @@ -package http_request +package common import ( "encoding/json" diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go new file mode 100644 index 0000000..01d321b --- /dev/null +++ b/utils/http_request/common/token.go @@ -0,0 +1,142 @@ +package common + +import ( + "encoding/json" + "net/http" + "strconv" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" +) + +func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expiration int) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.ClientCredentialsRequest{ + ClientID: client_id, + ClientSecret: client_secret, + Scope: scope, + GrantType: "client_credentials", + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + +func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.RefreshTokenRequest{ + ClientID: client_id, + GrantType: "refresh_token", + RefreshToken: refresh_token, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + +func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.ClientCredentialsRequest{ + ClientID: clientId, + ClientSecret: clientSecret, + Scope: "*", + GrantType: "client_credentials", + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+accountId+"/token?expires_in=86400", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + +func HTTPCreateTokenWE(client_id, client_secret, code string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.AuthorizationCodeRequest{ + ClientID: client_id, + ClientSecret: client_secret, + GrantType: "authorization_code", + Code: code, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + +func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.RefreshTokenRequest{ + ClientID: client_id, + GrantType: "refresh_token", + RefreshToken: refresh_token, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + +func HTTPCheckToken(token string) (models.Token, error) { + return HTTPGetItem[models.Token](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) +} diff --git a/utils/http_request/token_test.go b/utils/http_request/common/token_test.go similarity index 97% rename from utils/http_request/token_test.go rename to utils/http_request/common/token_test.go index 88e1d54..e736f62 100644 --- a/utils/http_request/token_test.go +++ b/utils/http_request/common/token_test.go @@ -1,4 +1,4 @@ -package http_request +package common import ( "testing" diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index 8622abf..f536def 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -6,27 +6,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListCampaign() ([]models.Campaign, error) { - return httprequest.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns") +type CampaignRequester struct { + *common.ResourceRequest } -func HTTPGetCampaign(id string) (models.Campaign, error) { - return httprequest.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + id) +func (c *CampaignRequester) HTTPListCampaign() ([]models.Campaign, error) { + return common.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvID + "/campaigns") } -func HTTPCreateCampaign(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", []byte(data)) +func (c *CampaignRequester) HTTPGetCampaign(id string) (models.Campaign, error) { + return common.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvID + "/campaigns/" + id) } -func HTTPEditCampaign(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, []byte(data)) +func (c *CampaignRequester) HTTPCreateCampaign(data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns", []byte(data)) } -func HTTPSwitchCampaign(id, state string) error { +func (c *CampaignRequester) HTTPEditCampaign(id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id, []byte(data)) +} + +func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { campaignSwitchRequest := models.CampaignSwitchRequest{ State: state, } @@ -36,11 +39,11 @@ func HTTPSwitchCampaign(id, state string) error { return err } - _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) return err } -func HTTPDeleteCampaign(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id, nil) +func (c *CampaignRequester) HTTPDeleteCampaign(id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/campaign_test.go b/utils/http_request/feature_experimentation/campaign_test.go index 30c11b8..931a567 100644 --- a/utils/http_request/feature_experimentation/campaign_test.go +++ b/utils/http_request/feature_experimentation/campaign_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var campaignRequester = CampaignRequester{} + func TestHTTPGetCampaign(t *testing.T) { - respBody, err := HTTPGetCampaign("testCampaignID") + respBody, err := campaignRequester.HTTPGetCampaign("testCampaignID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -22,7 +24,7 @@ func TestHTTPGetCampaign(t *testing.T) { func TestHTTPListCampaign(t *testing.T) { - respBody, err := HTTPListCampaign() + respBody, err := campaignRequester.HTTPListCampaign() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -43,7 +45,7 @@ func TestHTTPListCampaign(t *testing.T) { func TestHTTPCreateCampaign(t *testing.T) { dataCampaign := "{\"project_id\":\"testProjectID\",\"name\":\"testCampaignName\",\"description\":\"testCampaignDescription\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" - respBody, err := HTTPCreateCampaign(dataCampaign) + respBody, err := campaignRequester.HTTPCreateCampaign(dataCampaign) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -55,7 +57,7 @@ func TestHTTPEditCampaign(t *testing.T) { dataCampaign := "{\"project_id\":\"testProjectID1\",\"name\":\"testCampaignName1\",\"description\":\"testCampaignDescription1\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" - respBody, err := HTTPEditCampaign("testCampaignID", dataCampaign) + respBody, err := campaignRequester.HTTPEditCampaign("testCampaignID", dataCampaign) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -65,14 +67,14 @@ func TestHTTPEditCampaign(t *testing.T) { func TestHTTPDeleteCampaign(t *testing.T) { - err := HTTPDeleteCampaign("testCampaignID") + err := campaignRequester.HTTPDeleteCampaign("testCampaignID") assert.Nil(t, err) } func TestHTTPSwitchCampaign(t *testing.T) { - err := HTTPSwitchCampaign("testCampaignID", "active") + err := campaignRequester.HTTPSwitchCampaign("testCampaignID", "active") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go index 6d1e45a..968ffb2 100644 --- a/utils/http_request/feature_experimentation/flag.go +++ b/utils/http_request/feature_experimentation/flag.go @@ -5,27 +5,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListFlag() ([]models.Flag, error) { - return httprequest.HTTPGetAllPages[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags") +type FlagRequester struct { + *common.ResourceRequest } -func HTTPGetFlag(id string) (models.Flag, error) { - return httprequest.HTTPGetItem[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/flags/" + id) +func (f *FlagRequester) HTTPListFlag() ([]models.Flag, error) { + return common.HTTPGetAllPages[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + f.AccountID + "/flags") } -func HTTPCreateFlag(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", []byte(data)) +func (f *FlagRequester) HTTPGetFlag(id string) (models.Flag, error) { + return common.HTTPGetItem[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + f.AccountID + "/flags/" + id) } -func HTTPEditFlag(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, []byte(data)) +func (f *FlagRequester) HTTPCreateFlag(data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags", []byte(data)) } -func HTTPDeleteFlag(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+id, nil) +func (f *FlagRequester) HTTPEditFlag(id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, []byte(data)) +} + +func (f *FlagRequester) HTTPDeleteFlag(id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/flag_test.go b/utils/http_request/feature_experimentation/flag_test.go index 7686796..0565c04 100644 --- a/utils/http_request/feature_experimentation/flag_test.go +++ b/utils/http_request/feature_experimentation/flag_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var flagRequester = FlagRequester{} + func TestHTTPGetFlag(t *testing.T) { - respBody, err := HTTPGetFlag("testFlagID") + respBody, err := flagRequester.HTTPGetFlag("testFlagID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -19,7 +21,7 @@ func TestHTTPGetFlag(t *testing.T) { func TestHTTPListFlag(t *testing.T) { - respBody, err := HTTPListFlag() + respBody, err := flagRequester.HTTPListFlag() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -35,7 +37,7 @@ func TestHTTPCreateFlag(t *testing.T) { data := "{\"name\":\"testFlagName\", \"type\":\"string\", \"description\":\"testFlagDescription\", \"source\":\"cli\"}" - respBody, err := HTTPCreateFlag(data) + respBody, err := flagRequester.HTTPCreateFlag(data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -47,7 +49,7 @@ func TestHTTPEditFlag(t *testing.T) { data := "{\"name\":\"testFlagName1\",\"type\":\"string\",\"description\":\"testFlagDescription1\",\"source\":\"cli\"}" - respBody, err := HTTPEditFlag("testFlagID", data) + respBody, err := flagRequester.HTTPEditFlag("testFlagID", data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -57,7 +59,7 @@ func TestHTTPEditFlag(t *testing.T) { func TestHTTPDeleteFlag(t *testing.T) { - err := HTTPDeleteFlag("testFlagID") + err := flagRequester.HTTPDeleteFlag("testFlagID") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go index 38916ae..c6fb39a 100644 --- a/utils/http_request/feature_experimentation/goal.go +++ b/utils/http_request/feature_experimentation/goal.go @@ -5,27 +5,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListGoal() ([]models.Goal, error) { - return httprequest.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals") +type GoalRequester struct { + *common.ResourceRequest } -func HTTPGetGoal(id string) (models.Goal, error) { - return httprequest.HTTPGetItem[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/goals/" + id) +func (g *GoalRequester) HTTPListGoal() ([]models.Goal, error) { + return common.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvID + "/goals") } -func HTTPCreateGoal(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", []byte(data)) +func (g *GoalRequester) HTTPGetGoal(id string) (models.Goal, error) { + return common.HTTPGetItem[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvID + "/goals/" + id) } -func HTTPEditGoal(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, []byte(data)) +func (g *GoalRequester) HTTPCreateGoal(data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals", []byte(data)) } -func HTTPDeleteGoal(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+id, nil) +func (g *GoalRequester) HTTPEditGoal(id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals/"+id, []byte(data)) +} + +func (g *GoalRequester) HTTPDeleteGoal(id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/goal_test.go b/utils/http_request/feature_experimentation/goal_test.go index 497b8a2..d263a96 100644 --- a/utils/http_request/feature_experimentation/goal_test.go +++ b/utils/http_request/feature_experimentation/goal_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var goalRequester = GoalRequester{} + func TestHTTPGetGoal(t *testing.T) { - respBody, err := HTTPGetGoal("testGoalID") + respBody, err := goalRequester.HTTPGetGoal("testGoalID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -19,7 +21,7 @@ func TestHTTPGetGoal(t *testing.T) { func TestHTTPListGoal(t *testing.T) { - respBody, err := HTTPListGoal() + respBody, err := goalRequester.HTTPListGoal() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -35,7 +37,7 @@ func TestHTTPCreateGoal(t *testing.T) { data := "{\"label\":\"testGoalLabel\", \"type\":\"screenview\", \"operator\":\"contains\", \"value\":\"VIP\"}" - respBody, err := HTTPCreateGoal(data) + respBody, err := goalRequester.HTTPCreateGoal(data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -47,7 +49,7 @@ func TestHTTPEditGoal(t *testing.T) { data := "{\"label\":\"testGoalLabel\", \"type\":\"screenview\", \"operator\":\"contains\", \"value\":\"VIP\"}" - respBody, err := HTTPEditGoal("testGoalID", data) + respBody, err := goalRequester.HTTPEditGoal("testGoalID", data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -57,7 +59,7 @@ func TestHTTPEditGoal(t *testing.T) { func TestHTTPDeleteGoal(t *testing.T) { - err := HTTPDeleteGoal("testGoalID") + err := goalRequester.HTTPDeleteGoal("testGoalID") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/panic.go b/utils/http_request/feature_experimentation/panic.go index bd62511..662ef0c 100644 --- a/utils/http_request/feature_experimentation/panic.go +++ b/utils/http_request/feature_experimentation/panic.go @@ -6,15 +6,18 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPUpdatePanic(panicStatus string) ([]byte, error) { +type PanicRequester struct { + *common.ResourceRequest +} + +func (p *PanicRequester) HTTPUpdatePanic(panicStatus string) ([]byte, error) { panicRequestJSON, err := json.Marshal(models.PanicRequest{Panic: panicStatus}) if err != nil { return nil, err } - resp, err := httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", panicRequestJSON) + resp, err := common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/account_environments/"+p.AccountEnvID+"/panic", panicRequestJSON) return resp, err } diff --git a/utils/http_request/feature_experimentation/panic_test.go b/utils/http_request/feature_experimentation/panic_test.go index 15e07c4..ad64efd 100644 --- a/utils/http_request/feature_experimentation/panic_test.go +++ b/utils/http_request/feature_experimentation/panic_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var panicRequester = PanicRequester{} + func TestHTTPUpdatePanic(t *testing.T) { - _, err := HTTPUpdatePanic("active") + _, err := panicRequester.HTTPUpdatePanic("active") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go index 4286088..fd50be0 100644 --- a/utils/http_request/feature_experimentation/project.go +++ b/utils/http_request/feature_experimentation/project.go @@ -6,27 +6,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListProject() ([]models.Project, error) { - return httprequest.HTTPGetAllPages[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects") +type ProjectRequester struct { + *common.ResourceRequest } -func HTTPGetProject(id string) (models.Project, error) { - return httprequest.HTTPGetItem[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/projects/" + id) +func (p *ProjectRequester) HTTPListProject() ([]models.Project, error) { + return common.HTTPGetAllPages[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + p.AccountID + "/projects") } -func HTTPCreateProject(data []byte) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", data) +func (p *ProjectRequester) HTTPGetProject(id string) (models.Project, error) { + return common.HTTPGetItem[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + p.AccountID + "/projects/" + id) } -func HTTPEditProject(id string, data []byte) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, data) +func (p *ProjectRequester) HTTPCreateProject(data []byte) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects", data) } -func HTTPSwitchProject(id, state string) error { +func (p *ProjectRequester) HTTPEditProject(id string, data []byte) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, data) +} + +func (p *ProjectRequester) HTTPSwitchProject(id, state string) error { projectRequest := models.ProjectSwitchRequest{ State: state, } @@ -36,11 +39,11 @@ func HTTPSwitchProject(id, state string) error { return err } - _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id+"/toggle", projectRequestJSON) + _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id+"/toggle", projectRequestJSON) return err } -func HTTPDeleteProject(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+id, nil) +func (p *ProjectRequester) HTTPDeleteProject(id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/project_test.go b/utils/http_request/feature_experimentation/project_test.go index 95c3afd..f44f05d 100644 --- a/utils/http_request/feature_experimentation/project_test.go +++ b/utils/http_request/feature_experimentation/project_test.go @@ -9,9 +9,11 @@ import ( "github.com/stretchr/testify/assert" ) +var projectRequester = ProjectRequester{} + func TestHTTPGetProject(t *testing.T) { - respBody, err := HTTPGetProject("testProjectID") + respBody, err := projectRequester.HTTPGetProject("testProjectID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -22,7 +24,7 @@ func TestHTTPGetProject(t *testing.T) { func TestHTTPListProject(t *testing.T) { - respBody, err := HTTPListProject() + respBody, err := projectRequester.HTTPListProject() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -42,7 +44,7 @@ func TestHTTPCreateProject(t *testing.T) { if err != nil { log.Fatalf("error occurred: %s", err) } - respBody, err := HTTPCreateProject(projectRequestJSON) + respBody, err := projectRequester.HTTPCreateProject(projectRequestJSON) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -58,7 +60,7 @@ func TestHTTPEditProject(t *testing.T) { if err != nil { log.Fatalf("error occurred: %s", err) } - respBody, err := HTTPEditProject("testProjectID", projectRequestJSON) + respBody, err := projectRequester.HTTPEditProject("testProjectID", projectRequestJSON) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -68,14 +70,14 @@ func TestHTTPEditProject(t *testing.T) { func TestHTTPDeleteProject(t *testing.T) { - err := HTTPDeleteProject("testProjectID") + err := projectRequester.HTTPDeleteProject("testProjectID") assert.Nil(t, err) } func TestHTTPSwitchProject(t *testing.T) { - err := HTTPSwitchProject("testProjectID", "active") + err := projectRequester.HTTPSwitchProject("testProjectID", "active") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go index a6df319..0b13139 100644 --- a/utils/http_request/feature_experimentation/targeting_key.go +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -5,27 +5,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListTargetingKey() ([]models.TargetingKey, error) { - return httprequest.HTTPGetAllPages[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys") +type TargetingKeyRequester struct { + *common.ResourceRequest } -func HTTPGetTargetingKey(id string) (models.TargetingKey, error) { - return httprequest.HTTPGetItem[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/targeting_keys/" + id) +func (t *TargetingKeyRequester) HTTPListTargetingKey() ([]models.TargetingKey, error) { + return common.HTTPGetAllPages[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + t.AccountID + "/targeting_keys") } -func HTTPCreateTargetingKey(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", []byte(data)) +func (t *TargetingKeyRequester) HTTPGetTargetingKey(id string) (models.TargetingKey, error) { + return common.HTTPGetItem[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + t.AccountID + "/targeting_keys/" + id) } -func HTTPEditTargetingKey(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, []byte(data)) +func (t *TargetingKeyRequester) HTTPCreateTargetingKey(data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys", []byte(data)) } -func HTTPDeleteTargetingKey(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+id, nil) +func (t *TargetingKeyRequester) HTTPEditTargetingKey(id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, []byte(data)) +} + +func (t *TargetingKeyRequester) HTTPDeleteTargetingKey(id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/targeting_key_test.go b/utils/http_request/feature_experimentation/targeting_key_test.go index 0c268b6..9768c5f 100644 --- a/utils/http_request/feature_experimentation/targeting_key_test.go +++ b/utils/http_request/feature_experimentation/targeting_key_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var targetingKeyRequester = TargetingKeyRequester{} + func TestHTTPGetTargetingKey(t *testing.T) { - respBody, err := HTTPGetTargetingKey("testTargetingKeyID") + respBody, err := targetingKeyRequester.HTTPGetTargetingKey("testTargetingKeyID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -19,7 +21,7 @@ func TestHTTPGetTargetingKey(t *testing.T) { func TestHTTPListTargetingKey(t *testing.T) { - respBody, err := HTTPListTargetingKey() + respBody, err := targetingKeyRequester.HTTPListTargetingKey() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -35,7 +37,7 @@ func TestHTTPCreateTargetingKey(t *testing.T) { data := "{\"name\":\"testTargetingKeyName\", \"type\":\"string\", \"description\":\"testTargetingKeyDescription\"}" - respBody, err := HTTPCreateTargetingKey(data) + respBody, err := targetingKeyRequester.HTTPCreateTargetingKey(data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -45,7 +47,7 @@ func TestHTTPCreateTargetingKey(t *testing.T) { func TestHTTPEditTargetingKey(t *testing.T) { - respBody, err := HTTPEditTargetingKey("testTargetingKeyID", "testTargetingKeyName") + respBody, err := targetingKeyRequester.HTTPEditTargetingKey("testTargetingKeyID", "testTargetingKeyName") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -55,7 +57,7 @@ func TestHTTPEditTargetingKey(t *testing.T) { func TestHTTPDeleteTargetingKey(t *testing.T) { - err := HTTPDeleteTargetingKey("testTargetingKeyID") + err := targetingKeyRequester.HTTPDeleteTargetingKey("testTargetingKeyID") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go index 4ace06a..9ec4402 100644 --- a/utils/http_request/feature_experimentation/user.go +++ b/utils/http_request/feature_experimentation/user.go @@ -6,19 +6,22 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListUsers() ([]models.User, error) { - return httprequest.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/users") +type UserRequester struct { + *common.ResourceRequest } -func HTTPBatchUpdateUsers(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPut, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", []byte(data)) +func (u *UserRequester) HTTPListUsers() ([]models.User, error) { + return common.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + u.AccountID + "/account_environments/" + u.AccountEnvID + "/users") } -func HTTPDeleteUsers(email string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), nil) +func (u *UserRequester) HTTPBatchUpdateUsers(data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPut, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvID+"/users", []byte(data)) +} + +func (u *UserRequester) HTTPDeleteUsers(email string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvID+"/users?emails[]="+url.QueryEscape(email), nil) return err } diff --git a/utils/http_request/feature_experimentation/user_test.go b/utils/http_request/feature_experimentation/user_test.go index a3f7f2f..09fc0bd 100644 --- a/utils/http_request/feature_experimentation/user_test.go +++ b/utils/http_request/feature_experimentation/user_test.go @@ -6,9 +6,11 @@ import ( "github.com/stretchr/testify/assert" ) +var userRequester = UserRequester{} + func TestHTTPListUsers(t *testing.T) { - respBody, err := HTTPListUsers() + respBody, err := userRequester.HTTPListUsers() assert.NotNil(t, respBody) assert.Nil(t, err) @@ -24,14 +26,14 @@ func TestHTTPBatchUpdateUsers(t *testing.T) { data := "[{\"email\":\"example@abtasty.com\",\"role\":\"ADMIN\"},{\"email\":\"example1@abtasty.com\",\"role\":\"VIEWER\"}]" - _, err := HTTPBatchUpdateUsers(data) + _, err := userRequester.HTTPBatchUpdateUsers(data) assert.Nil(t, err) } func TestHTTPDeleteUser(t *testing.T) { - err := HTTPDeleteUsers("example@abtasty.com") + err := userRequester.HTTPDeleteUsers("example@abtasty.com") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index 789bce1..16d3ff3 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -5,27 +5,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return httprequest.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") +type VariationRequester struct { + *common.ResourceRequest } -func HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { - return httprequest.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) +func (v *VariationRequester) HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { + return common.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") } -func HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) +func (v *VariationRequester) HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { + return common.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) } -func HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) +func (v *VariationRequester) HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) } -func HTTPDeleteVariation(campaignID, variationGroupID, id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) +func (v *VariationRequester) HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) +} + +func (v *VariationRequester) HTTPDeleteVariation(campaignID, variationGroupID, id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go index 85d3a88..2cb763b 100644 --- a/utils/http_request/feature_experimentation/variation_group.go +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -5,27 +5,30 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/viper" + "github.com/flagship-io/flagship/utils/http_request/common" ) -func HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { - return httprequest.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups") +type VariationGroupRequester struct { + *common.ResourceRequest } -func HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { - return httprequest.HTTPGetItem[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/account_environments/" + viper.GetString("account_environment_id") + "/campaigns/" + campaignID + "/variation_groups/" + id) +func (vg *VariationGroupRequester) HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { + return common.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups") } -func HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) +func (vg *VariationGroupRequester) HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { + return common.HTTPGetItem[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + id) } -func HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) +func (vg *VariationGroupRequester) HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) } -func HTTPDeleteVariationGroup(campaignID, id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) +func (vg *VariationGroupRequester) HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { + return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) +} + +func (vg *VariationGroupRequester) HTTPDeleteVariationGroup(campaignID, id string) error { + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_group_test.go b/utils/http_request/feature_experimentation/variation_group_test.go index cdf84d4..98ddf74 100644 --- a/utils/http_request/feature_experimentation/variation_group_test.go +++ b/utils/http_request/feature_experimentation/variation_group_test.go @@ -7,10 +7,11 @@ import ( ) var CampaignID = "campaignID" +var variationGroupRequester = VariationGroupRequester{} func TestHTTPGetVariationGroup(t *testing.T) { - respBody, err := HTTPGetVariationGroup(CampaignID, "testVariationGroupID") + respBody, err := variationGroupRequester.HTTPGetVariationGroup(CampaignID, "testVariationGroupID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -21,7 +22,7 @@ func TestHTTPGetVariationGroup(t *testing.T) { func TestHTTPListVariationGroup(t *testing.T) { - respBody, err := HTTPListVariationGroup(CampaignID) + respBody, err := variationGroupRequester.HTTPListVariationGroup(CampaignID) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -37,7 +38,7 @@ func TestHTTPCreateVariationGroup(t *testing.T) { data := "{\"name\":\"testVariationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":\"isVIP\"}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":true}]}]}}" - respBody, err := HTTPCreateVariationGroup(CampaignID, data) + respBody, err := variationGroupRequester.HTTPCreateVariationGroup(CampaignID, data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -49,7 +50,7 @@ func TestHTTPEditVariationGroup(t *testing.T) { data := "{\"name\":\"testVariationGroupName1\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":\"isVIP\"}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":true}]}]}}" - respBody, err := HTTPEditVariationGroup(CampaignID, "testVariationGroupID", data) + respBody, err := variationGroupRequester.HTTPEditVariationGroup(CampaignID, "testVariationGroupID", data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -59,7 +60,7 @@ func TestHTTPEditVariationGroup(t *testing.T) { func TestHTTPDeleteVariationGroup(t *testing.T) { - err := HTTPDeleteVariationGroup(CampaignID, "testVariationGroupID") + err := variationGroupRequester.HTTPDeleteVariationGroup(CampaignID, "testVariationGroupID") assert.Nil(t, err) } diff --git a/utils/http_request/feature_experimentation/variation_test.go b/utils/http_request/feature_experimentation/variation_test.go index aea29f0..dfed6c6 100644 --- a/utils/http_request/feature_experimentation/variation_test.go +++ b/utils/http_request/feature_experimentation/variation_test.go @@ -7,10 +7,11 @@ import ( ) var variationGroupID = "variationGroupID" +var variationRequester = VariationRequester{} func TestHTTPGetVariation(t *testing.T) { - respBody, err := HTTPGetVariation(CampaignID, variationGroupID, "testVariationID") + respBody, err := variationRequester.HTTPGetVariation(CampaignID, variationGroupID, "testVariationID") assert.NotNil(t, respBody) assert.Nil(t, err) @@ -21,7 +22,7 @@ func TestHTTPGetVariation(t *testing.T) { func TestHTTPListVariation(t *testing.T) { - respBody, err := HTTPListVariation(CampaignID, variationGroupID) + respBody, err := variationRequester.HTTPListVariation(CampaignID, variationGroupID) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -41,7 +42,7 @@ func TestHTTPCreateVariation(t *testing.T) { data := "{\"name\":\"testVariationName\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":\"isVIP\"}}" - respBody, err := HTTPCreateVariation(CampaignID, variationGroupID, data) + respBody, err := variationRequester.HTTPCreateVariation(CampaignID, variationGroupID, data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -53,7 +54,7 @@ func TestHTTPEditVariation(t *testing.T) { data := "{\"name\":\"testVariationName1\",\"reference\":false,\"allocation\":80,\"modifications\":{\"type\":\"string\",\"value\":\"isVIP1\"}}" - respBody, err := HTTPEditVariation(CampaignID, variationGroupID, "testVariationID", data) + respBody, err := variationRequester.HTTPEditVariation(CampaignID, variationGroupID, "testVariationID", data) assert.NotNil(t, respBody) assert.Nil(t, err) @@ -63,7 +64,7 @@ func TestHTTPEditVariation(t *testing.T) { func TestHTTPDeleteVariation(t *testing.T) { - err := HTTPDeleteVariation(CampaignID, variationGroupID, "testVariationID") + err := variationRequester.HTTPDeleteVariation(CampaignID, variationGroupID, "testVariationID") assert.Nil(t, err) } diff --git a/utils/http_request/main.go b/utils/http_request/main.go new file mode 100644 index 0000000..42f337c --- /dev/null +++ b/utils/http_request/main.go @@ -0,0 +1,24 @@ +package http_request + +import ( + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" +) + +type HTTPResource interface { + Init(*common.RequestConfig) +} + +var ResourceRequester common.ResourceRequest + +var CampaignRequester feature_experimentation.CampaignRequester = feature_experimentation.CampaignRequester{ResourceRequest: &ResourceRequester} +var FlagRequester feature_experimentation.FlagRequester = feature_experimentation.FlagRequester{ResourceRequest: &ResourceRequester} +var GoalRequester feature_experimentation.GoalRequester = feature_experimentation.GoalRequester{ResourceRequest: &ResourceRequester} +var ProjectRequester feature_experimentation.ProjectRequester = feature_experimentation.ProjectRequester{ResourceRequest: &ResourceRequester} +var UserRequester feature_experimentation.UserRequester = feature_experimentation.UserRequester{ResourceRequest: &ResourceRequester} +var TargetingKeyRequester feature_experimentation.TargetingKeyRequester = feature_experimentation.TargetingKeyRequester{ResourceRequest: &ResourceRequester} +var VariationGroupRequester feature_experimentation.VariationGroupRequester = feature_experimentation.VariationGroupRequester{ResourceRequest: &ResourceRequester} +var VariationRequester feature_experimentation.VariationRequester = feature_experimentation.VariationRequester{ResourceRequest: &ResourceRequester} +var PanicRequester feature_experimentation.PanicRequester = feature_experimentation.PanicRequester{ResourceRequest: &ResourceRequester} + +var HTTPResources = []HTTPResource{&ResourceRequester} diff --git a/utils/http_request/token.go b/utils/http_request/token.go deleted file mode 100644 index 8e3b088..0000000 --- a/utils/http_request/token.go +++ /dev/null @@ -1,66 +0,0 @@ -package http_request - -import ( - "encoding/json" - "net/http" - "strconv" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils" - "github.com/spf13/viper" -) - -func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expiration int) (models.TokenResponse, error) { - var authenticationResponse models.TokenResponse - authRequest := models.ClientCredentialsRequest{ - ClientID: client_id, - ClientSecret: client_secret, - Scope: scope, - GrantType: "client_credentials", - } - authRequestJSON, err := json.Marshal(authRequest) - if err != nil { - return models.TokenResponse{}, err - } - - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) - if err != nil { - return models.TokenResponse{}, err - } - - err = json.Unmarshal(respBody, &authenticationResponse) - if err != nil { - return models.TokenResponse{}, err - } - - return authenticationResponse, err -} - -func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, error) { - var authenticationResponse models.TokenResponse - authRequest := models.RefreshTokenRequest{ - ClientID: client_id, - GrantType: "refresh_token", - RefreshToken: refresh_token, - } - authRequestJSON, err := json.Marshal(authRequest) - if err != nil { - return models.TokenResponse{}, err - } - - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token", authRequestJSON) - if err != nil { - return models.TokenResponse{}, err - } - - err = json.Unmarshal(respBody, &authenticationResponse) - if err != nil { - return models.TokenResponse{}, err - } - - return authenticationResponse, err -} - -func HTTPCheckToken(token string) (models.Token, error) { - return HTTPGetItem[models.Token](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) -} diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index c138998..4841634 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -5,24 +5,24 @@ import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/viper" ) func HTTPListTest() ([]models.Test, error) { - return httprequest.HTTPGetAllPagesWe[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests") + return common.HTTPGetAllPagesWe[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests") } func HTTPGetTest(id string) (models.Test, error) { - return httprequest.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + id) + return common.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + id) } func HTTPCreateTest(data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) + return common.HTTPRequest(http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) } func HTTPEditTest(id, data string) ([]byte, error) { - return httprequest.HTTPRequest(http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) + return common.HTTPRequest(http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) } /* func HTTPSwitchCampaign(id, state string) error { @@ -35,11 +35,11 @@ func HTTPEditTest(id, data string) ([]byte, error) { return err } - _, err = httprequest.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) return err } */ func HTTPDeleteTest(id string) error { - _, err := httprequest.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) + _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) return err } diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go index 644e973..e22db1e 100644 --- a/utils/http_request/web_experimentation/global_code.go +++ b/utils/http_request/web_experimentation/global_code.go @@ -3,14 +3,14 @@ package web_experimentation import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/viper" ) func HTTPListGlobalCode() ([]models.GlobalCode, error) { - return httprequest.HTTPGetAllPagesWe[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes") + return common.HTTPGetAllPagesWe[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes") } func HTTPGetGlobalCode(id string) (models.GlobalCode, error) { - return httprequest.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes/" + id) + return common.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes/" + id) } diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go index 71aac56..15c173a 100644 --- a/utils/http_request/web_experimentation/variation.go +++ b/utils/http_request/web_experimentation/variation.go @@ -5,10 +5,10 @@ import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/viper" ) func HTTPGetVariation(testID, id int) (models.TestVariation, error) { - return httprequest.HTTPGetItem[models.TestVariation](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) + return common.HTTPGetItem[models.TestVariation](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) } From fe7e111648c196a54230847c1351d1ae65e8f454 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 2 Apr 2024 07:37:54 +0000 Subject: [PATCH 08/48] add auth command and fix test --- .../account/current.go | 26 +-- cmd/feature_experimentation/account/list.go | 5 +- cmd/feature_experimentation/account/use.go | 3 +- cmd/feature_experimentation/auth/auth.go | 7 +- cmd/feature_experimentation/auth/auth_test.go | 73 +++++++ cmd/feature_experimentation/auth/get.go | 20 +- cmd/feature_experimentation/auth/list.go | 16 +- cmd/feature_experimentation/auth/login.go | 24 ++- .../campaign/campaign_test.go | 17 +- .../feature_experimentation.go | 16 +- cmd/feature_experimentation/flag/flag_test.go | 16 +- cmd/feature_experimentation/goal/goal_test.go | 17 +- .../info/info.go | 0 .../panic/panic_test.go | 7 +- .../project/project_test.go | 16 +- cmd/feature_experimentation/resource/load.go | 152 ++++++++++--- .../resource/loadResource.json | 63 ++++++ .../resource/resource.go | 4 - .../targeting_key/targeting_key_test.go | 16 +- .../token/info.go | 0 .../token/token.go | 0 .../token/token_test.go | 5 +- cmd/feature_experimentation/user/user_test.go | 11 +- .../variation/variation_test.go | 16 +- .../variation_group/variation_group_test.go | 16 +- cmd/root.go | 11 +- go.mod | 5 +- models/auth.go | 25 +++ models/configuration.go | 29 --- .../account_environment.go | 9 + models/token.go | 9 +- utils/config/config.go | 202 +++--------------- utils/config/default.go | 2 +- utils/http_request/common/request.go | 80 ++++--- utils/http_request/common/request_test.go | 64 ------ utils/http_request/common/token.go | 39 +--- utils/http_request/common/token_test.go | 30 --- .../account_environment.go | 19 ++ .../feature_experimentation/campaign.go | 12 +- .../feature_experimentation/campaign_test.go | 5 +- .../feature_experimentation/flag.go | 6 +- .../feature_experimentation/flag_test.go | 3 +- .../feature_experimentation/goal.go | 10 +- .../feature_experimentation/goal_test.go | 3 +- .../feature_experimentation/main_test.go | 7 + .../feature_experimentation/panic.go | 2 +- .../feature_experimentation/panic_test.go | 3 +- .../feature_experimentation/project.go | 8 +- .../feature_experimentation/project_test.go | 3 +- .../feature_experimentation/targeting_key.go | 6 +- .../targeting_key_test.go | 3 +- .../feature_experimentation/user.go | 6 +- .../feature_experimentation/user_test.go | 3 +- .../feature_experimentation/variation.go | 10 +- .../variation_group.go | 10 +- .../variation_group_test.go | 3 +- .../feature_experimentation/variation_test.go | 3 +- utils/http_request/main.go | 5 +- utils/http_request/main_test.go | 4 +- .../web_experimentation/campaign.go | 6 +- utils/mock_function/configuration.go | 11 +- .../feature_experimentation/auth.go | 12 ++ .../feature_experimentation/campaign.go | 16 +- .../feature_experimentation/flag.go | 14 +- .../feature_experimentation/goal.go | 14 +- .../feature_experimentation/panic.go | 6 +- .../feature_experimentation/project.go | 18 +- .../feature_experimentation/targeting_key.go | 15 +- .../{ => feature_experimentation}/token.go | 12 +- .../feature_experimentation/user.go | 10 +- .../feature_experimentation/variation.go | 15 +- .../variation_group.go | 15 +- utils/mock_function/request.go | 21 +- 73 files changed, 717 insertions(+), 653 deletions(-) create mode 100644 cmd/feature_experimentation/auth/auth_test.go rename cmd/{ => feature_experimentation}/info/info.go (100%) rename cmd/{ => feature_experimentation}/token/info.go (100%) rename cmd/{ => feature_experimentation}/token/token.go (100%) rename cmd/{ => feature_experimentation}/token/token_test.go (82%) create mode 100644 models/auth.go delete mode 100644 models/configuration.go create mode 100644 models/feature_experimentation/account_environment.go delete mode 100644 utils/http_request/common/request_test.go delete mode 100644 utils/http_request/common/token_test.go create mode 100644 utils/http_request/feature_experimentation/account_environment.go create mode 100644 utils/mock_function/feature_experimentation/auth.go rename utils/mock_function/{ => feature_experimentation}/token.go (74%) diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index 9d2e955..150a139 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -17,15 +17,15 @@ import ( // getCmd represents the list command var currentCmd = &cobra.Command{ - Use: "get", - Short: "get an auth credential", - Long: `list an auth credential from your system`, + Use: "current", + Short: "current an auth credential", + Long: `current an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.ConfigurationYaml_new - var configuration models.Configuration_new + var configurationYaml models.AccountYaml + var configuration models.AccountJSON - yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, Username)) + yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) if err != nil { log.Fatalf("error occurred: %s", err) } @@ -36,21 +36,15 @@ var currentCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) } - configuration.Username = configurationYaml.Username - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret + configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential + configuration.AccountID = configurationYaml.AccountID + configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) }, } func init() { - currentCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to display") - - if err := currentCmd.MarkFlagRequired("username"); err != nil { - log.Fatalf("error occurred: %v", err) - } - AccountCmd.AddCommand(currentCmd) } diff --git a/cmd/feature_experimentation/account/list.go b/cmd/feature_experimentation/account/list.go index 99016ad..f7d8cf5 100644 --- a/cmd/feature_experimentation/account/list.go +++ b/cmd/feature_experimentation/account/list.go @@ -19,12 +19,11 @@ var listCmd = &cobra.Command{ Long: `list all auth from your system`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignRequester.HTTPListCampaign() + body, err := httprequest.AccountEnvironmentRequester.HTTPListAccountEnvironment() if err != nil { log.Fatalf("error occurred: %v", err) } - utils.FormatItem([]string{"Id", "ProjectId", "Name", "Description", "Type", "Status"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) - + utils.FormatItem([]string{"Id", "Environment", "IsMain", "Panic", "SingleAssignment"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index 44354bc..a7577c5 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -25,6 +25,7 @@ var useCmd = &cobra.Command{ if AccountID != "" { config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) } + if AccountEnvironmentID != "" { config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) } @@ -33,7 +34,7 @@ var useCmd = &cobra.Command{ func init() { useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") - useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-env-id", "e", "", "account env id of the credentials you want to display") + useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to display") AccountCmd.AddCommand(useCmd) } diff --git a/cmd/feature_experimentation/auth/auth.go b/cmd/feature_experimentation/auth/auth.go index 610cfa4..2cb0eaf 100644 --- a/cmd/feature_experimentation/auth/auth.go +++ b/cmd/feature_experimentation/auth/auth.go @@ -14,9 +14,10 @@ var ( // ConfigurationCmd represents the configuration command var AuthCmd = &cobra.Command{ - Use: "auth [create|edit|get|list|delete|use]", - Short: "Manage your CLI authentication", - Long: `Manage your CLI authentication`, + Use: "authentication [login|get|list]", + Aliases: []string{"auth"}, + Short: "Manage your CLI authentication for feature experimentation", + Long: `Manage your CLI authentication for feature experimentation`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/feature_experimentation/auth/auth_test.go b/cmd/feature_experimentation/auth/auth_test.go new file mode 100644 index 0000000..932448b --- /dev/null +++ b/cmd/feature_experimentation/auth/auth_test.go @@ -0,0 +1,73 @@ +package auth + +import ( + "encoding/json" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_fe.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_fe.APIToken() + + m.Run() +} + +var testConfiguration models.Auth +var testConfigurationList []models.Auth + +func TestAuthCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AuthCmd) + assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list]") +} + +func TestAuthHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AuthCmd, "--help") + assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list]") +} + +func TestAuthLoginCommand(t *testing.T) { + successOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_configuration", "-i=testConfigurationClientID", "-s=testConfigurationClientSecret", "-a=account_id") + assert.Equal(t, "Credential created successfully\n", successOutput) +} + +func TestAuthListCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AuthCmd, "list") + + err := json.Unmarshal([]byte(output), &testConfigurationList) + + assert.Nil(t, err) + + //byt, err := json.Marshal(mockfunction.TestConfiguration) + + assert.Nil(t, err) + + //assert.Contains(t, output, string(byt)) +} + +func TestAuthGetCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AuthCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"username\" not set") + + successOutput, _ := utils.ExecuteCommand(AuthCmd, "get", "--username=test_configuration") + err := json.Unmarshal([]byte(successOutput), &testConfiguration) + + assert.Nil(t, err) + + //assert.Equal(t, mockfunction.TestConfiguration, testConfiguration) +} diff --git a/cmd/feature_experimentation/auth/get.go b/cmd/feature_experimentation/auth/get.go index 9c22d54..56c40cf 100644 --- a/cmd/feature_experimentation/auth/get.go +++ b/cmd/feature_experimentation/auth/get.go @@ -18,29 +18,29 @@ import ( // getCmd represents the list command var getCmd = &cobra.Command{ Use: "get", - Short: "get an auth credential", - Long: `list an auth credential from your system`, + Short: "get an auth credential for feature experimentation", + Long: `get an auth credential for feature experimentation from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.ConfigurationYaml_new - var configuration models.Configuration_new + var authYaml models.AuthYaml + var auth models.Auth - yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, Username)) + yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username)) if err != nil { log.Fatalf("error occurred: %s", err) } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &authYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - configuration.Username = configurationYaml.Username - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret + auth.Username = authYaml.Username + auth.ClientID = authYaml.ClientID + auth.ClientSecret = authYaml.ClientSecret - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/auth/list.go b/cmd/feature_experimentation/auth/list.go index fa5b45f..341fbf9 100644 --- a/cmd/feature_experimentation/auth/list.go +++ b/cmd/feature_experimentation/auth/list.go @@ -22,17 +22,17 @@ var listCmd = &cobra.Command{ Long: `list all auth from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurations []models.Configuration_new - existingCredentials, err := config.GetUsernames(utils.FEATURE_EXPERIMENTATION) + var auths []models.Auth + existingAuths, err := config.GetUsernames(utils.FEATURE_EXPERIMENTATION) if err != nil { log.Fatalf("error occurred: %s", err) } - for _, fileName := range existingCredentials { + for _, fileName := range existingAuths { if fileName != "" { - var configurationYaml models.ConfigurationYaml_new - var configuration models.Configuration_new - yamlFile, err := os.ReadFile(config.SetPathForCredentials(utils.FEATURE_EXPERIMENTATION, fileName)) + var configurationYaml models.AuthYaml + var configuration models.Auth + yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, fileName)) if err != nil { log.Fatalf("error occurred: %s", err) } @@ -46,12 +46,12 @@ var listCmd = &cobra.Command{ configuration.Username = configurationYaml.Username configuration.ClientID = configurationYaml.ClientID configuration.ClientSecret = configurationYaml.ClientSecret - configurations = append(configurations, configuration) + auths = append(auths, configuration) } } } - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, configurations, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 78eef15..2fb22a7 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -13,7 +13,6 @@ import ( "slices" "time" - "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/flagship-io/flagship/utils/http_request/common" @@ -50,12 +49,12 @@ func openLink(url string) error { // createCmd represents the create command var loginCmd = &cobra.Command{ - Use: "login [--browser] | [--credential-file] | [--inputs] [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", + Use: "login [--browser] | [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", Short: "login", Long: `login`, Run: func(cmd *cobra.Command, args []string) { if !checkSingleFlag(browser, credentialsFile != "", Username != "") { - log.Fatalf("error occurred: %s", "1 flag is required. (browser, inputs, credential-file)") + log.Fatalf("error occurred: %s", "1 flag is required. (browser, username, credential-file)") } if browser { @@ -79,7 +78,6 @@ var loginCmd = &cobra.Command{ if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { log.Fatalf("Error starting callback server: %s", err) } - fmt.Println(code) authenticationResponse, err := common.HTTPCreateTokenWE(clientID, clientSecret, code) if err != nil { @@ -96,10 +94,14 @@ var loginCmd = &cobra.Command{ } if credentialsFile != "" { - authenticationResponse := models.TokenResponse{} - config.ReadCredentialsFromFile(credentialsFile) - config.CreateCredentialsFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) - config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + v := config.ReadCredentialsFromFile(credentialsFile) + authenticationResponse, err := common.HTTPCreateTokenFE(v.GetString("client_id"), v.GetString("client_secret"), v.GetString("account_id")) + if err != nil { + log.Fatalf("%s", err) + return + } + config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) + config.SelectAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("username")) fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") return } @@ -110,7 +112,7 @@ var loginCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) } if slices.Contains(existingCredentials, Username) { - config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) @@ -130,8 +132,8 @@ var loginCmd = &cobra.Command{ if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } - config.CreateCredentialsFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) - config.SelectCredentials(utils.FEATURE_EXPERIMENTATION, Username) + config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) + config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") diff --git a/cmd/feature_experimentation/campaign/campaign_test.go b/cmd/feature_experimentation/campaign/campaign_test.go index 4ae1829..b712dc1 100644 --- a/cmd/feature_experimentation/campaign/campaign_test.go +++ b/cmd/feature_experimentation/campaign/campaign_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,9 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APICampaign() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APICampaign() + m.Run() } @@ -44,7 +49,7 @@ func TestCampaignGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestCampaign, testCampaign) + assert.Equal(t, mockfunction_fe.TestCampaign, testCampaign) } func TestCampaignListCommand(t *testing.T) { @@ -55,7 +60,7 @@ func TestCampaignListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestCampaignlist, testCampaignList) + assert.Equal(t, mockfunction_fe.TestCampaignlist, testCampaignList) } func TestCampaignCreateCommand(t *testing.T) { @@ -69,7 +74,7 @@ func TestCampaignCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestCampaign, testCampaign) + assert.Equal(t, mockfunction_fe.TestCampaign, testCampaign) } func TestCampaignEditCommand(t *testing.T) { @@ -83,7 +88,7 @@ func TestCampaignEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestCampaignEdit, testCampaign) + assert.Equal(t, mockfunction_fe.TestCampaignEdit, testCampaign) } func TestCampaignDeleteCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 19bd182..9757894 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -19,6 +19,7 @@ import ( "github.com/flagship-io/flagship/cmd/feature_experimentation/user" "github.com/flagship-io/flagship/cmd/feature_experimentation/variation" variationgroup "github.com/flagship-io/flagship/cmd/feature_experimentation/variation_group" + "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/flagship-io/flagship/utils/http_request" "github.com/flagship-io/flagship/utils/http_request/common" @@ -62,20 +63,23 @@ func init() { func initConfig() { v := viper.New() homeDir, _ := os.UserHomeDir() - var requestConfig = common.RequestConfig{Product: "FE"} + var requestConfig = common.RequestConfig{Product: utils.FEATURE_EXPERIMENTATION} - v.SetConfigFile(homeDir + "/.flagship/credentials/fe/.cli.yaml") + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION + "/.cli.yaml") v.MergeInConfig() if v.GetString("current_used_credential") != "" { - vL := config.ReadConfiguration(v.GetString("current_used_credential")) + vL := config.ReadAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("current_used_credential")) v.MergeConfigMap(vL.AllSettings()) v.Unmarshal(&requestConfig) common.Init(requestConfig) - for _, r := range http_request.HTTPResources { - r.Init(&requestConfig) - } + resource.Init(requestConfig) + + r := &http_request.ResourceRequester + + r.Init(&requestConfig) + return } diff --git a/cmd/feature_experimentation/flag/flag_test.go b/cmd/feature_experimentation/flag/flag_test.go index ccb75de..e2fd743 100644 --- a/cmd/feature_experimentation/flag/flag_test.go +++ b/cmd/feature_experimentation/flag/flag_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIFlag() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIFlag() m.Run() } @@ -44,7 +48,7 @@ func TestFlagGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestFlag, testFlag) + assert.Equal(t, mockfunction_fe.TestFlag, testFlag) } func TestFlagListCommand(t *testing.T) { @@ -55,7 +59,7 @@ func TestFlagListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestFlagList, testFlagList) + assert.Equal(t, mockfunction_fe.TestFlagList, testFlagList) } func TestFlagCreateCommand(t *testing.T) { @@ -66,7 +70,7 @@ func TestFlagCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestFlag, testFlag) + assert.Equal(t, mockfunction_fe.TestFlag, testFlag) } func TestFlagEditCommand(t *testing.T) { @@ -80,7 +84,7 @@ func TestFlagEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestFlagEdit, testFlag) + assert.Equal(t, mockfunction_fe.TestFlagEdit, testFlag) } func TestFlagDeleteCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/goal/goal_test.go b/cmd/feature_experimentation/goal/goal_test.go index 3781295..c9652e4 100644 --- a/cmd/feature_experimentation/goal/goal_test.go +++ b/cmd/feature_experimentation/goal/goal_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,9 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIGoal() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIGoal() + m.Run() } @@ -44,7 +49,7 @@ func TestGoalGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestGoal, testGoal) + assert.Equal(t, mockfunction_fe.TestGoal, testGoal) } func TestGoalListCommand(t *testing.T) { @@ -55,7 +60,7 @@ func TestGoalListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestGoalList, testGoalList) + assert.Equal(t, mockfunction_fe.TestGoalList, testGoalList) } func TestGoalCreateCommand(t *testing.T) { @@ -70,7 +75,7 @@ func TestGoalCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestGoal, testGoal) + assert.Equal(t, mockfunction_fe.TestGoal, testGoal) } func TestGoalEditCommand(t *testing.T) { @@ -84,7 +89,7 @@ func TestGoalEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestGoalEdit, testGoal) + assert.Equal(t, mockfunction_fe.TestGoalEdit, testGoal) } func TestGoalDeleteCommand(t *testing.T) { diff --git a/cmd/info/info.go b/cmd/feature_experimentation/info/info.go similarity index 100% rename from cmd/info/info.go rename to cmd/feature_experimentation/info/info.go diff --git a/cmd/feature_experimentation/panic/panic_test.go b/cmd/feature_experimentation/panic/panic_test.go index 45a566e..fcea42e 100644 --- a/cmd/feature_experimentation/panic/panic_test.go +++ b/cmd/feature_experimentation/panic/panic_test.go @@ -4,7 +4,9 @@ import ( "testing" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -14,7 +16,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIPanic() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIPanic() m.Run() } diff --git a/cmd/feature_experimentation/project/project_test.go b/cmd/feature_experimentation/project/project_test.go index 5560658..7242801 100644 --- a/cmd/feature_experimentation/project/project_test.go +++ b/cmd/feature_experimentation/project/project_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIProject() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIProject() m.Run() } @@ -45,7 +49,7 @@ func TestProjectGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestProject, testProject) + assert.Equal(t, mockfunction_fe.TestProject, testProject) } func TestProjectListCommand(t *testing.T) { @@ -56,7 +60,7 @@ func TestProjectListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestProjectList, testProjectList) + assert.Equal(t, mockfunction_fe.TestProjectList, testProjectList) } func TestProjectCreateCommand(t *testing.T) { @@ -70,7 +74,7 @@ func TestProjectCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestProject, testProject) + assert.Equal(t, mockfunction_fe.TestProject, testProject) } func TestProjectEditCommand(t *testing.T) { @@ -84,7 +88,7 @@ func TestProjectEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestProjectEdit, testProject) + assert.Equal(t, mockfunction_fe.TestProjectEdit, testProject) } func TestProjectDeleteCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index e994b82..4843826 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -10,21 +10,26 @@ import ( "encoding/json" "fmt" "log" - "net/http" "os" "strings" "github.com/d5/tengo/v2" models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request" "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" "github.com/spf13/viper" ) +var ( + resourceFile string + outputFile string +) + type Data interface { Save(data string) ([]byte, error) + Delete(id string) error } type ProjectData struct { @@ -36,7 +41,11 @@ type ResourceData struct { } func (f *ProjectData) Save(data string) ([]byte, error) { - return httprequest.ProjectRequester.HTTPCreateProject([]byte(data)) + return http_request.ProjectRequester.HTTPCreateProject([]byte(data)) +} + +func (f *ProjectData) Delete(id string) error { + return http_request.ProjectRequester.HTTPDeleteProject(id) } type CampaignData struct { @@ -44,12 +53,16 @@ type CampaignData struct { ProjectId string `json:"project_id"` Name string `json:"name"` Description string `json:"description"` - Type string `json:"type"` + Type string `json:"type,omitempty"` VariationGroups []VariationGroupData `json:"variation_groups"` } func (f *CampaignData) Save(data string) ([]byte, error) { - return httprequest.CampaignRequester.HTTPCreateCampaign(data) + return http_request.CampaignRequester.HTTPCreateCampaign(data) +} + +func (f *CampaignData) Delete(id string) error { + return http_request.CampaignRequester.HTTPDeleteCampaign(id) } type FlagData struct { @@ -57,7 +70,11 @@ type FlagData struct { } func (f *FlagData) Save(data string) ([]byte, error) { - return httprequest.FlagRequester.HTTPCreateFlag(data) + return http_request.FlagRequester.HTTPCreateFlag(data) +} + +func (f *FlagData) Delete(id string) error { + return http_request.FlagRequester.HTTPDeleteFlag(id) } type GoalData struct { @@ -65,7 +82,11 @@ type GoalData struct { } func (f *GoalData) Save(data string) ([]byte, error) { - return httprequest.GoalRequester.HTTPCreateGoal(data) + return http_request.GoalRequester.HTTPCreateGoal(data) +} + +func (f *GoalData) Delete(id string) error { + return http_request.GoalRequester.HTTPDeleteGoal(id) } type TargetingKeysData struct { @@ -73,7 +94,11 @@ type TargetingKeysData struct { } func (f *TargetingKeysData) Save(data string) ([]byte, error) { - return httprequest.TargetingKeyRequester.HTTPCreateTargetingKey(data) + return http_request.TargetingKeyRequester.HTTPCreateTargetingKey(data) +} + +func (f *TargetingKeysData) Delete(id string) error { + return http_request.TargetingKeyRequester.HTTPDeleteTargetingKey(id) } type VariationGroupData struct { @@ -110,6 +135,18 @@ type Resource struct { Name ResourceType Data Data ResourceVariable string + Method string +} + +var cred common.RequestConfig + +func Init(credL common.RequestConfig) { + cred = credL +} + +type ResourceCmdStruct struct { + Name string `json:"name,omitempty"` + Data string `json:"data,omitempty"` } func UnmarshalConfig(filePath string) ([]Resource, error) { @@ -118,6 +155,7 @@ func UnmarshalConfig(filePath string) ([]Resource, error) { Name string Data json.RawMessage ResourceVariable string + Method string } } @@ -173,7 +211,7 @@ func UnmarshalConfig(filePath string) ([]Resource, error) { return nil, err } - resources = append(resources, Resource{Name: name, Data: data, ResourceVariable: r.ResourceVariable}) + resources = append(resources, Resource{Name: name, Data: data, ResourceVariable: r.ResourceVariable, Method: r.Method}) } return resources, nil @@ -187,7 +225,14 @@ var loadCmd = &cobra.Command{ Short: "Load your resources", Long: `Load your resources`, Run: func(cmd *cobra.Command, args []string) { - ScriptResource(gResources) + jsonBytes := ScriptResource(cmd, gResources) + if outputFile != "" { + os.WriteFile(outputFile, jsonBytes, os.ModePerm) + fmt.Fprintf(cmd.OutOrStdout(), "File created at %s\n", outputFile) + return + } + + fmt.Fprintf(cmd.OutOrStdout(), "%s", string(jsonBytes)) }, } @@ -200,6 +245,8 @@ func init() { log.Fatalf("error occurred: %v", err) } + loadCmd.Flags().StringVarP(&outputFile, "output-file", "", "", "result of the command that contains all resource informations") + ResourceCmd.AddCommand(loadCmd) } @@ -215,12 +262,15 @@ func initResource() { } } -func ScriptResource(resources []Resource) { +func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { resourceVariables := make(map[string]interface{}) + var loadResultJSON []string + var loadResultOutputFile []ResourceCmdStruct for _, resource := range resources { var response []byte + var resultOutputFile ResourceCmdStruct var resourceData map[string]interface{} var responseData interface{} var url = "" @@ -233,6 +283,12 @@ func ScriptResource(resources []Resource) { fmt.Printf("error occurred marshal data: %v\n", err) } + var httpMethod string = "POST" + + if resource.Method == "delete" { + httpMethod = "DELETE" + } + switch resource.Name { case Project: url = "/projects" @@ -278,9 +334,7 @@ func ScriptResource(resources []Resource) { resourceData[k] = script.(string) } } - } - } dataResource, err := json.Marshal(resourceData) @@ -288,31 +342,77 @@ func ScriptResource(resources []Resource) { log.Fatalf("error occurred http call: %v\n", err) } - if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { - response, err = common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+url, dataResource) + if httpMethod == "POST" { + if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { + response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+url, dataResource) + } + + if resource.Name == Goal || resource.Name == Campaign { + response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+"/account_environments/"+cred.AccountEnvironmentID+url, dataResource) + } + + resultOutputFile = ResourceCmdStruct{ + Name: resourceName, + Data: string(response), + } + loadResultOutputFile = append(loadResultOutputFile, resultOutputFile) + } - if resource.Name == Goal || resource.Name == Campaign { - response, err = common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+url, dataResource) + if httpMethod == "DELETE" { + if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { + response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+url+"/"+fmt.Sprintf("%v", resourceData["id"]), nil) + } + + if resource.Name == Goal || resource.Name == Campaign { + response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+"/account_environments/"+cred.AccountEnvironmentID+url+"/"+fmt.Sprintf("%v", resourceData["id"]), nil) + } + + if err == nil && viper.GetString("output_format") != "json" { + response = []byte("The id: " + fmt.Sprintf("%v", resourceData["id"]) + " deleted successfully") + } } if err != nil { log.Fatalf("error occurred http call: %v\n", err) } - fmt.Fprintf(os.Stdout, "%s - %s: %s %s\n", color, resourceName, colorNone, string(response)) + if viper.GetString("output_format") != "json" { + fmt.Fprintf(cmd.OutOrStdout(), "%s - %s: %s %s\n", color, resourceName, colorNone, string(response)) + } - err = json.Unmarshal(response, &responseData) + if httpMethod != "DELETE" { + err = json.Unmarshal(response, &responseData) - if err != nil { - fmt.Printf("error occurred unmarshal responseData: %v\n", err) - } + if err != nil { + fmt.Printf("error occurred unmarshal responseData: %v\n", err) + } + + if responseData == nil { + fmt.Println("error occurred not response data: " + string(response)) + continue + } - if responseData == nil { - fmt.Println("error occurred not response data: " + string(response)) - continue + resourceVariables[resource.ResourceVariable] = responseData } - resourceVariables[resource.ResourceVariable] = responseData + loadResultJSON = append(loadResultJSON, string(response)) + } + + var jsonBytes []byte + var jsonString any + + if outputFile != "" { + jsonString = loadResultOutputFile + } else { + jsonString = loadResultJSON + } + + jsonBytes, err := json.Marshal(jsonString) + + if err != nil { + log.Fatalf("Error marshaling struct: %v", err) } + + return jsonBytes } diff --git a/cmd/feature_experimentation/resource/loadResource.json b/cmd/feature_experimentation/resource/loadResource.json index a11ad46..80a1fef 100644 --- a/cmd/feature_experimentation/resource/loadResource.json +++ b/cmd/feature_experimentation/resource/loadResource.json @@ -60,8 +60,61 @@ ] } }, + { + "name": "campaign", + "resourceVariable": "c2", + "method": "create", + "data": { + "project_id": "$p1.id", + "name": "Resource loader Campaign to delete", + "description": "Loaded from resource loader", + "type": "ab", + "variation_groups": [ + { + "variations": [ + { + "name": "Original", + "reference": true, + "allocation": 50, + "modifications": { + "type": "FLAG", + "value": { + "color": "red" + } + } + }, + { + "name": "Variation 1", + "reference": false, + "allocation": 50, + "modifications": { + "type": "FLAG", + "value": { + "color": "blue" + } + } + } + ], + "targeting": { + "targeting_groups": [ + { + "targetings": [ + { + "operator": "EQUALS", + "key": "device", + "value": "firefox" + } + ] + } + ] + } + } + ] + } + }, { "name": "flag", + "method": "create", "resourceVariable": "f1", "data": { "name": "flag_created_with_resource_loader", @@ -72,6 +125,7 @@ }, { "name": "goal", + "method": "create", "resourceVariable": "g1", "data": { "type": "screenview", @@ -82,12 +136,21 @@ }, { "name": "targeting_key", + "method": "create", "resourceVariable": "t1", "data": { "type": "string", "name": "targeting_key_created_with_resource_loader", "description": "Loaded from resource loader" } + }, + { + "name": "campaign", + "resourceVariable": "c8", + "method": "delete", + "data": { + "id": "$c2.id" + } } ] } \ No newline at end of file diff --git a/cmd/feature_experimentation/resource/resource.go b/cmd/feature_experimentation/resource/resource.go index 82566d5..6534ecb 100644 --- a/cmd/feature_experimentation/resource/resource.go +++ b/cmd/feature_experimentation/resource/resource.go @@ -9,10 +9,6 @@ import ( "github.com/spf13/cobra" ) -var ( - resourceFile string -) - // ResourceCmd represents the resource command var ResourceCmd = &cobra.Command{ Use: "resource [load]", diff --git a/cmd/feature_experimentation/targeting_key/targeting_key_test.go b/cmd/feature_experimentation/targeting_key/targeting_key_test.go index 7dbd394..057e21e 100644 --- a/cmd/feature_experimentation/targeting_key/targeting_key_test.go +++ b/cmd/feature_experimentation/targeting_key/targeting_key_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APITargetingKey() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APITargetingKey() m.Run() } @@ -45,7 +49,7 @@ func TestTargetingKeyGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestTargetingKey, testTargetingKey) + assert.Equal(t, mockfunction_fe.TestTargetingKey, testTargetingKey) } func TestTargetingKeyListCommand(t *testing.T) { @@ -56,7 +60,7 @@ func TestTargetingKeyListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestTargetingKeyList, testTargetingKeyList) + assert.Equal(t, mockfunction_fe.TestTargetingKeyList, testTargetingKeyList) } func TestTargetingKeyCreateCommand(t *testing.T) { @@ -70,7 +74,7 @@ func TestTargetingKeyCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestTargetingKey, testTargetingKey) + assert.Equal(t, mockfunction_fe.TestTargetingKey, testTargetingKey) } func TestTargetingKeyEditCommand(t *testing.T) { @@ -84,7 +88,7 @@ func TestTargetingKeyEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestTargetingKeyEdit, testTargetingKey) + assert.Equal(t, mockfunction_fe.TestTargetingKeyEdit, testTargetingKey) } func TestTargetingKeyDeleteCommand(t *testing.T) { diff --git a/cmd/token/info.go b/cmd/feature_experimentation/token/info.go similarity index 100% rename from cmd/token/info.go rename to cmd/feature_experimentation/token/info.go diff --git a/cmd/token/token.go b/cmd/feature_experimentation/token/token.go similarity index 100% rename from cmd/token/token.go rename to cmd/feature_experimentation/token/token.go diff --git a/cmd/token/token_test.go b/cmd/feature_experimentation/token/token_test.go similarity index 82% rename from cmd/token/token_test.go rename to cmd/feature_experimentation/token/token_test.go index d43e33e..0626673 100644 --- a/cmd/token/token_test.go +++ b/cmd/feature_experimentation/token/token_test.go @@ -5,19 +5,20 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) -var testToken models.Token +var testToken models.TokenWE func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIToken() + mockfunction.SetMock(&http_request.ResourceRequester) m.Run() } diff --git a/cmd/feature_experimentation/user/user_test.go b/cmd/feature_experimentation/user/user_test.go index 7f6a198..0639efc 100644 --- a/cmd/feature_experimentation/user/user_test.go +++ b/cmd/feature_experimentation/user/user_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,9 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIUser() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIUser() + m.Run() } @@ -40,7 +45,7 @@ func TestUserListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestUserList, testUserList) + assert.Equal(t, mockfunction_fe.TestUserList, testUserList) } func TestUserCreateCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go index fd63505..19d436b 100644 --- a/cmd/feature_experimentation/variation/variation_test.go +++ b/cmd/feature_experimentation/variation/variation_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIVariation() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIVariation() m.Run() } @@ -48,7 +52,7 @@ func TestVariationGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariation, testVariation) + assert.Equal(t, mockfunction_fe.TestVariation, testVariation) } func TestVariationListCommand(t *testing.T) { @@ -59,7 +63,7 @@ func TestVariationListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationList, testVariationList) + assert.Equal(t, mockfunction_fe.TestVariationList, testVariationList) } func TestVariationCreateCommand(t *testing.T) { @@ -73,7 +77,7 @@ func TestVariationCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariation, testVariation) + assert.Equal(t, mockfunction_fe.TestVariation, testVariation) } func TestVariationEditCommand(t *testing.T) { @@ -87,7 +91,7 @@ func TestVariationEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationEdit, testVariation) + assert.Equal(t, mockfunction_fe.TestVariationEdit, testVariation) } func TestVariationDeleteCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/variation_group/variation_group_test.go b/cmd/feature_experimentation/variation_group/variation_group_test.go index 7d96cb7..1324147 100644 --- a/cmd/feature_experimentation/variation_group/variation_group_test.go +++ b/cmd/feature_experimentation/variation_group/variation_group_test.go @@ -6,7 +6,10 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -16,7 +19,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIVariationGroup() + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIVariationGroup() m.Run() } @@ -48,7 +52,7 @@ func TestVariationGroupGetCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationGroup, testVariationGroup) + assert.Equal(t, mockfunction_fe.TestVariationGroup, testVariationGroup) } func TestVariationGroupListCommand(t *testing.T) { @@ -59,7 +63,7 @@ func TestVariationGroupListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationGroupList, testVariationGroupList) + assert.Equal(t, mockfunction_fe.TestVariationGroupList, testVariationGroupList) } func TestVariationGroupCreateCommand(t *testing.T) { @@ -73,7 +77,7 @@ func TestVariationGroupCreateCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationGroup, testVariationGroup) + assert.Equal(t, mockfunction_fe.TestVariationGroup, testVariationGroup) } func TestVariationGroupEditCommand(t *testing.T) { @@ -87,7 +91,7 @@ func TestVariationGroupEditCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction.TestVariationGroupEdit, testVariationGroup) + assert.Equal(t, mockfunction_fe.TestVariationGroupEdit, testVariationGroup) } func TestVariationGroupDeleteCommand(t *testing.T) { diff --git a/cmd/root.go b/cmd/root.go index bb73573..810e631 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -7,8 +7,6 @@ import ( "os" "github.com/flagship-io/flagship/cmd/feature_experimentation" - "github.com/flagship-io/flagship/cmd/info" - "github.com/flagship-io/flagship/cmd/token" "github.com/flagship-io/flagship/cmd/web_experimentation" "github.com/flagship-io/flagship/cmd/version" @@ -19,9 +17,7 @@ import ( "github.com/spf13/viper" ) -var ( - outputFormat string -) +var outputFormat string // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ @@ -49,8 +45,6 @@ func Execute() { func addSubCommandPalettes() { rootCmd.AddCommand(version.VersionCmd) - rootCmd.AddCommand(token.TokenCmd) - rootCmd.AddCommand(info.InfoCmd) rootCmd.AddCommand(feature_experimentation.FeatureExperimentationCmd) rootCmd.AddCommand(web_experimentation.WebExperimentationCmd) } @@ -61,7 +55,6 @@ func init() { rootCmd.PersistentFlags().StringVarP(&outputFormat, "output-format", "f", config.OutputFormat, "output format for the get and list subcommands for flagship resources. Only 3 format are possible: table, json, json-pretty") rootCmd.PersistentFlags().StringVarP(&common.UserAgent, "user-agent", "", config.DefaultUserAgent, "custom user agent") - viper.BindPFlag("token", rootCmd.PersistentFlags().Lookup("token")) viper.BindPFlag("output_format", rootCmd.PersistentFlags().Lookup("output-format")) addSubCommandPalettes() @@ -71,6 +64,6 @@ func init() { func initConfig() { // Find home directory. - _, err := config.CheckFlagshipHomeDirectory() + _, err := config.CheckABTastyHomeDirectory() cobra.CheckErr(err) } diff --git a/go.mod b/go.mod index 609459c..c2f5bfa 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,11 @@ module github.com/flagship-io/flagship go 1.18 require ( + github.com/d5/tengo/v2 v2.13.0 github.com/flagship-io/codebase-analyzer v0.8.0 github.com/kyokomi/emoji/v2 v2.2.12 - github.com/d5/tengo/v2 v2.13.0 github.com/rodaine/table v1.1.0 github.com/sirupsen/logrus v1.9.0 - github.com/spf13/cobra v1.5.0 github.com/spf13/viper v1.12.0 github.com/stretchr/testify v1.8.1 @@ -43,6 +42,6 @@ require ( golang.org/x/sys v0.3.0 // indirect golang.org/x/text v0.5.0 // indirect gopkg.in/ini.v1 v1.66.4 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/models/auth.go b/models/auth.go new file mode 100644 index 0000000..73ee665 --- /dev/null +++ b/models/auth.go @@ -0,0 +1,25 @@ +package models + +type Auth struct { + Username string `json:"username"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` +} + +type AuthYaml struct { + Username string `yaml:"username"` + ClientID string `yaml:"client_id"` + ClientSecret string `yaml:"client_secret"` +} + +type AccountYaml struct { + CurrentUsedCredential string `yaml:"current_used_credential"` + AccountID string `yaml:"account_id"` + AccountEnvironmentID string `yaml:"account_environment_id"` +} + +type AccountJSON struct { + CurrentUsedCredential string `json:"current_used_credential"` + AccountID string `json:"account_id"` + AccountEnvironmentID string `json:"account_environment_id"` +} diff --git a/models/configuration.go b/models/configuration.go deleted file mode 100644 index 889f864..0000000 --- a/models/configuration.go +++ /dev/null @@ -1,29 +0,0 @@ -package models - -type Configuration struct { - Name string `json:"name"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - AccountID string `json:"account_id"` - AccountEnvironmentID string `json:"account_environment_id"` -} - -type ConfigurationYaml struct { - Name string `yaml:"name"` - ClientID string `yaml:"client_id"` - ClientSecret string `yaml:"client_secret"` - AccountID string `yaml:"account_id"` - AccountEnvironmentID string `yaml:"account_environment_id"` -} - -type Configuration_new struct { - Username string `json:"username"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` -} - -type ConfigurationYaml_new struct { - Username string `yaml:"username"` - ClientID string `yaml:"client_id"` - ClientSecret string `yaml:"client_secret"` -} diff --git a/models/feature_experimentation/account_environment.go b/models/feature_experimentation/account_environment.go new file mode 100644 index 0000000..7bda79e --- /dev/null +++ b/models/feature_experimentation/account_environment.go @@ -0,0 +1,9 @@ +package feature_experimentation + +type AccountEnvironment struct { + Id string `json:"id,omitempty"` + Environment string `json:"environment"` + IsMain bool `json:"is_main"` + Panic bool `json:"panic"` + SingleAssignment bool `json:"single_assignment"` +} diff --git a/models/token.go b/models/token.go index 07a77e2..4c060e8 100644 --- a/models/token.go +++ b/models/token.go @@ -1,6 +1,13 @@ package models -type Token struct { +type TokenWE struct { + ClientID string `json:"client_id"` + AccountID string `json:"account"` + ExpiresIn int `json:"expires_in"` + Scope string `json:"scope"` +} + +type TokenFE struct { ClientID string `json:"client_id"` AccountID string `json:"account"` ExpiresIn int `json:"expires_in"` diff --git a/utils/config/config.go b/utils/config/config.go index 77668da..be87b13 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -33,18 +33,18 @@ func Unset(key string) error { return nil } -func CheckFlagshipHomeDirectory() (string, error) { +func CheckABTastyHomeDirectory() (string, error) { homeDir, err := os.UserHomeDir() - if _, err := os.Stat(homeDir + "/.flagship/credentials/fe"); errors.Is(err, os.ErrNotExist) { - err := os.MkdirAll(homeDir+"/.flagship/credentials/fe", os.ModePerm) + if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { + err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.FEATURE_EXPERIMENTATION, os.ModePerm) if err != nil { log.Fatal(err) } } - if _, err := os.Stat(homeDir + "/.flagship/credentials/we"); errors.Is(err, os.ErrNotExist) { - err := os.MkdirAll(homeDir+"/.flagship/credentials/we", os.ModePerm) + if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { + err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.WEB_EXPERIMENTATION, os.ModePerm) if err != nil { log.Fatal(err) } @@ -53,20 +53,9 @@ func CheckFlagshipHomeDirectory() (string, error) { return homeDir, err } -func SetPathForConfigName(fileName string) string { - homeDir, _ := CheckFlagshipHomeDirectory() - - filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/fe/" + fileName + ".yaml") - if err != nil { - log.Fatalf("error occured: %v", err) - } - - return filepath -} - -func SetPathForCredentials(product, fileName string) string { - homeDir, _ := CheckFlagshipHomeDirectory() - filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/" + product + "/" + fileName + ".yaml") +func CredentialPath(product, username string) string { + homeDir, _ := CheckABTastyHomeDirectory() + filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml") if err != nil { log.Fatalf("error occured: %v", err) } @@ -74,42 +63,9 @@ func SetPathForCredentials(product, fileName string) string { return filepath } -func GetConfigurationsName() ([]string, error) { - homeDir, _ := CheckFlagshipHomeDirectory() - r := regexp.MustCompile(`(?P[^/]+)\.yaml`) - var fileNames []string - - f, err := os.Open(homeDir + "/.flagship/configurations") - if err != nil { - fmt.Println(err) - return nil, err - } - - files, err := f.Readdir(0) - if err != nil { - fmt.Println(err) - return nil, err - } - - for _, v := range files { - match := r.FindStringSubmatch(v.Name()) - configurationName := r.SubexpIndex("ConfigurationName") - if len(match) == 0 { - log.Fatalln("Error: File not found") - } - - if match[configurationName] == ".cli" { - continue - } - - fileNames = append(fileNames, match[configurationName]) - } - return fileNames, nil -} - func GetUsernames(product string) ([]string, error) { - homeDir, err := CheckFlagshipHomeDirectory() - r := regexp.MustCompile(`(?P[^/]+)\.yaml`) + homeDir, err := CheckABTastyHomeDirectory() + r := regexp.MustCompile(`(?P[^/]+)\.yaml`) var fileNames []string f, err := os.Open(homeDir + "/.flagship/credentials/" + product) @@ -126,7 +82,7 @@ func GetUsernames(product string) ([]string, error) { for _, v := range files { match := r.FindStringSubmatch(v.Name()) - userName := r.SubexpIndex("UserName") + userName := r.SubexpIndex("Username") if len(match) == 0 { log.Fatalln("Error: File not found") } @@ -136,28 +92,9 @@ func GetUsernames(product string) ([]string, error) { return fileNames, nil } -func SetOptionalsDefault(grantType, scope string, expiration int) { - viper.Set("grant_type", grantType) - viper.Set("scope", scope) - viper.Set("expiration", expiration) -} - -func CreateConfigurationFile(configurationName, clientId, clientSecret string) { - filepath := SetPathForConfigName(configurationName) - - v.Set("name", configurationName) - v.Set("client_id", clientId) - v.Set("client_secret", clientSecret) - - err := v.WriteConfigAs(filepath) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - -} - -func CreateCredentialsFile(product, username, clientId, clientSecret string, authenticationResponse models.TokenResponse) { - filepath := SetPathForCredentials(product, username) +func CreateAuthFile(product, username, clientId, clientSecret string, authenticationResponse models.TokenResponse) { + v := viper.New() + filepath := CredentialPath(product, username) v.Set("username", username) v.Set("client_id", clientId) @@ -169,33 +106,20 @@ func CreateCredentialsFile(product, username, clientId, clientSecret string, aut if err != nil { log.Fatalf("error occurred: %v", err) } - } -func SelectConfiguration(configurationName string) { - filepath := SetPathForConfigName(".cli") - v.Set("current_used_credential", configurationName) - - err := v.WriteConfigAs(filepath) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - ReadConfiguration(configurationName) -} - -func ReadConfiguration(configurationName string) *viper.Viper { +func ReadAuth(product, configurationName string) *viper.Viper { v := viper.New() - configFilepath := SetPathForConfigName(configurationName) + configFilepath := CredentialPath(product, configurationName) v.SetConfigFile(configFilepath) v.MergeInConfig() return v } -func SelectCredentials(product, configurationName string) { +func SelectAuth(product, configurationName string) { var v = viper.New() - filepath := SetPathForCredentials(product, utils.HOME_CLI) + filepath := CredentialPath(product, utils.HOME_CLI) v.Set("current_used_credential", configurationName) err := v.WriteConfigAs(filepath) @@ -203,38 +127,11 @@ func SelectCredentials(product, configurationName string) { log.Fatalf("error occurred: %v", err) } - ReadCredentials(product, configurationName) -} - -func ReadCredentials(product, configurationName string) { - configFilepath := SetPathForCredentials(product, configurationName) - viper.SetConfigFile(configFilepath) - viper.MergeInConfig() -} - -func EditConfigurationFile(configurationName, newName, clientId, clientSecret, accountId, accountEnvId string) { - filepath := SetPathForConfigName(configurationName) - - v.Set("name", newName) - v.Set("client_id", clientId) - v.Set("client_secret", clientSecret) - v.Set("account_id", accountId) - v.Set("account_environment_id", accountEnvId) - - err := v.WriteConfigAs(filepath) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - e := os.Rename(filepath, SetPathForConfigName(newName)) - if e != nil { - log.Fatal(e) - } } func SetAccountID(product, accountID string) { var v = viper.New() - configFilepath := SetPathForCredentials(product, utils.HOME_CLI) + configFilepath := CredentialPath(product, utils.HOME_CLI) v.SetConfigFile(configFilepath) v.MergeInConfig() @@ -248,73 +145,40 @@ func SetAccountID(product, accountID string) { func SetAccountEnvID(product, accountEnvID string) { var v = viper.New() - configFilepath := SetPathForCredentials(product, utils.HOME_CLI) + configFilepath := CredentialPath(product, utils.HOME_CLI) v.SetConfigFile(configFilepath) v.MergeInConfig() v.Set("account_environment_id", accountEnvID) - err := viper.WriteConfigAs(configFilepath) - if err != nil { - log.Fatalf("error occurred: %v", err) - } -} - -func ReadCredentialsFromFile(configurationFile string) { - viper.SetConfigFile(configurationFile) - err := viper.MergeInConfig() - + err := v.WriteConfigAs(configFilepath) if err != nil { log.Fatalf("error occurred: %v", err) } } -func WriteToken(configurationName string, authenticationResponse models.TokenResponse) { - configFilepath := SetPathForConfigName(configurationName) - - viper.SetConfigFile(configFilepath) - err := viper.MergeInConfig() +func ReadCredentialsFromFile(configurationFile string) *viper.Viper { + var v = viper.New() + v.SetConfigFile(configurationFile) + err := v.MergeInConfig() if err != nil { log.Fatalf("error occurred: %v", err) } - viper.Set("token", authenticationResponse.AccessToken) - viper.Set("refresh_token", authenticationResponse.RefreshToken) - viper.Set("current_used_credential", nil) - Unset("current_used_credential") - - err = viper.WriteConfigAs(configFilepath) - if err != nil { - log.Fatalf("error occurred: %v", err) - } + return v } -func WriteToken_new(product, username string) { - configFilepath := SetPathForCredentials(product, username) +func WriteToken(product, configurationName string, authenticationResponse models.TokenResponse) { + v := viper.New() + configFilepath := CredentialPath(product, configurationName) - viper.SetConfigFile(configFilepath) - err := viper.MergeInConfig() - if err != nil { - log.Fatalf("error occurred: %v", err) - } + v.SetConfigFile(configFilepath) - viper.Set("token", "token") - viper.Set("refresh_token", "refresh_token") - viper.Set("current_used_credential", nil) - Unset("current_used_credential") + v.Set("token", authenticationResponse.AccessToken) + v.Set("refresh_token", authenticationResponse.RefreshToken) - err = viper.WriteConfigAs(configFilepath) + err := v.WriteConfigAs(configFilepath) if err != nil { log.Fatalf("error occurred: %v", err) } } - -func SetViperMock() { - viper.GetViper().Set("account_id", "account_id") - viper.GetViper().Set("account_environment_id", "account_environment_id") - viper.GetViper().Set("client_id", "client_id") - viper.GetViper().Set("client_secret", "client_secret") - viper.GetViper().Set("token", "access_token") - viper.GetViper().Set("refresh_token", "refresh_token") - viper.GetViper().Set("output_format", "json") -} diff --git a/utils/config/default.go b/utils/config/default.go index ff2791f..aaac0e9 100644 --- a/utils/config/default.go +++ b/utils/config/default.go @@ -3,7 +3,7 @@ package config import "github.com/flagship-io/flagship/cmd/version" const ( - OutputFormat = "table" + OutputFormat = "json" GrantType = "client_credentials" Expiration = 86400 Scope = "*" diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 7bcd56f..7eed674 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -8,9 +8,11 @@ import ( "io" "log" "net/http" + "reflect" "strings" "time" + "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" ) @@ -25,12 +27,12 @@ type PageResult struct { } type ResourceRequest struct { - AccountID string `mapstructure:"account_id"` - AccountEnvID string `mapstructure:"account_environment_id"` + AccountID string `mapstructure:"account_id"` + AccountEnvironmentID string `mapstructure:"account_environment_id"` } func (c *ResourceRequest) Init(cL *RequestConfig) { - c.AccountEnvID = cL.AccountEnvID + c.AccountEnvironmentID = cL.AccountEnvironmentID c.AccountID = cL.AccountID } @@ -47,15 +49,15 @@ type Pagination struct { } type RequestConfig struct { - Product string - Username string `mapstructure:"username"` - ClientID string `mapstructure:"client_id"` - ClientSecret string `mapstructure:"client_secret"` - AccountID string `mapstructure:"account_id"` - AccountEnvID string `mapstructure:"account_environment_id"` - Token string `mapstructure:"token"` - RefreshToken string `mapstructure:"refresh_token"` - CurrentUsedCredentials string `mapstructure:"current_used_credentials"` + Product string + Username string `mapstructure:"username"` + ClientID string `mapstructure:"client_id"` + ClientSecret string `mapstructure:"client_secret"` + AccountID string `mapstructure:"account_id"` + AccountEnvironmentID string `mapstructure:"account_environment_id"` + Token string `mapstructure:"token"` + RefreshToken string `mapstructure:"refresh_token"` + CurrentUsedCredential string `mapstructure:"current_used_credential"` } var cred RequestConfig @@ -64,7 +66,7 @@ func Init(credL RequestConfig) { cred = credL } -func regenerateToken(configName string) { +func regenerateToken(product, configName string) { authenticationResponse, err := HTTPRefreshToken(cred.ClientID, cred.RefreshToken) if err != nil { @@ -76,31 +78,48 @@ func regenerateToken(configName string) { } else { cred.RefreshToken = authenticationResponse.RefreshToken cred.Token = authenticationResponse.AccessToken - config.WriteToken(configName, authenticationResponse) + config.WriteToken(product, configName, authenticationResponse) } } -func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { +func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) { var bodyIO io.Reader = nil if body != nil { bodyIO = bytes.NewBuffer(body) } - req, err := http.NewRequest(method, resource, bodyIO) + //fmt.Println(method, url) + var resource T + + resourceType := reflect.TypeOf(resource).String() + + if resourceType == "feature_experimentation.Campaign" || resourceType == "feature_experimentation.Goal" { + if cred.AccountID == "" || cred.AccountEnvironmentID == "" { + log.Fatalf("account_id or account_environment_id required, Please configure your CLI") + } + } + + req, err := http.NewRequest(method, url, bodyIO) if err != nil { log.Panicf("error occurred on request creation: %v", err) } - if cred.Product == "FE" && !strings.Contains(resource, "token") && (cred.AccountID == "" || cred.AccountEnvID == "") { - log.Fatalf("account_id or account_environment_id required, Please configure your CLI") - } + if cred.Product == utils.FEATURE_EXPERIMENTATION { + if cred.AccountID == "" { + log.Fatalf("account_id required, Please configure your CLI") + } + // for resource loader + if resourceType == "resource.ResourceData" && !strings.Contains(url, "token") && (cred.AccountID == "" || cred.AccountEnvironmentID == "") { + log.Fatalf("account_id or account_environment_id required, Please configure your CLI") + } - if cred.Product == "FE" && strings.Contains(resource, "token") && cred.ClientID == "" && cred.ClientSecret == "" { - log.Fatalf("client_id or client_secret required, Please configure your CLI") + if strings.Contains(url, "token") && cred.ClientID == "" && cred.ClientSecret == "" { + log.Fatalf("client_id or client_secret required, Please configure your CLI") + } } - if !strings.Contains(resource, "token") && cred.Token == "" { - regenerateToken(cred.CurrentUsedCredentials) + if !strings.Contains(url, "token") && cred.Token == "" { + regenerateToken(cred.Product, cred.CurrentUsedCredential) } req.Header.Add("Accept", `*/*`) @@ -135,20 +154,17 @@ func HTTPRequest(method string, resource string, body []byte) ([]byte, error) { return nil, err } - fmt.Println(cred.AccountID) - fmt.Println(string(respBody)) - - if (resp.StatusCode == 403 || resp.StatusCode == 401) && !counter { + if (resp.StatusCode == 401) && !counter { counter = true - regenerateToken(cred.CurrentUsedCredentials) - return HTTPRequest(method, resource, body) + regenerateToken(cred.Product, cred.CurrentUsedCredential) + return HTTPRequest[T](method, url, body) } return respBody, err } func HTTPGetItem[T any](resource string) (T, error) { var result T - respBody, err := HTTPRequest(http.MethodGet, resource, nil) + respBody, err := HTTPRequest[T](http.MethodGet, resource, nil) if err != nil { return result, err } @@ -160,7 +176,7 @@ func HTTPGetAllPages[T any](resource string) ([]T, error) { currentPage := 1 results := []T{} for { - respBody, err := HTTPRequest(http.MethodGet, fmt.Sprintf("%s?_page=%d&_max_per_page=100", resource, currentPage), nil) + respBody, err := HTTPRequest[T](http.MethodGet, fmt.Sprintf("%s?_page=%d&_max_per_page=100", resource, currentPage), nil) if err != nil { return nil, err } @@ -189,7 +205,7 @@ func HTTPGetAllPagesWe[T any](resource string) ([]T, error) { currentPage := 1 results := []T{} for { - respBody, err := HTTPRequest(http.MethodGet, fmt.Sprintf("%s?_page=%d&_max_per_page=100", resource, currentPage), nil) + respBody, err := HTTPRequest[T](http.MethodGet, fmt.Sprintf("%s?_page=%d&_max_per_page=100", resource, currentPage), nil) if err != nil { return nil, err } diff --git a/utils/http_request/common/request_test.go b/utils/http_request/common/request_test.go deleted file mode 100644 index b462ce4..0000000 --- a/utils/http_request/common/request_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package common - -import ( - "encoding/json" - "net/http" - "testing" - - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" -) - -type TestRequest struct { - Name string `json:"name"` -} - -func TestHTTPRequestGet(t *testing.T) { - - var result TestRequest - - testRequest := TestRequest{ - Name: "TestName", - } - testRequestJson, _ := json.Marshal(testRequest) - - respBody, err := HTTPRequest(http.MethodGet, "serverURLGet", testRequestJson) - - assert.NotNil(t, respBody) - assert.Nil(t, err) - - json.Unmarshal(respBody, &result) - - assert.Equal(t, "TestName", result.Name) -} - -func TestHTTPGetItem(t *testing.T) { - - result, err := HTTPGetItem[TestRequest]("serverURLGet") - - assert.Nil(t, err) - assert.NotNil(t, result) - - assert.Equal(t, "TestName", result.Name) -} - -func TestHTTPGetAllPages(t *testing.T) { - - result, err := HTTPGetAllPages[TestRequest]("serverURLList") - - assert.Nil(t, err) - assert.NotNil(t, result) - - assert.Equal(t, "TestName", result[0].Name) - assert.Equal(t, "TestName1", result[1].Name) -} - -func TestRegenerateToken(t *testing.T) { - - regenerateToken("test_configuration") - - assert.Equal(t, viper.IsSet("token"), true) - assert.Equal(t, viper.IsSet("refresh_token"), true) - assert.Equal(t, viper.GetString("token"), "access_token") - assert.Equal(t, viper.GetString("refresh_token"), "refresh_token") -} diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 01d321b..51daa1c 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -3,38 +3,11 @@ package common import ( "encoding/json" "net/http" - "strconv" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" ) -func HTTPCreateToken(client_id, client_secret, grant_type, scope string, expiration int) (models.TokenResponse, error) { - var authenticationResponse models.TokenResponse - authRequest := models.ClientCredentialsRequest{ - ClientID: client_id, - ClientSecret: client_secret, - Scope: scope, - GrantType: "client_credentials", - } - authRequestJSON, err := json.Marshal(authRequest) - if err != nil { - return models.TokenResponse{}, err - } - - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token?expires_in="+strconv.Itoa(expiration), authRequestJSON) - if err != nil { - return models.TokenResponse{}, err - } - - err = json.Unmarshal(respBody, &authenticationResponse) - if err != nil { - return models.TokenResponse{}, err - } - - return authenticationResponse, err -} - func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.RefreshTokenRequest{ @@ -47,7 +20,7 @@ func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, er return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) + respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -73,7 +46,7 @@ func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenRe return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+accountId+"/token?expires_in=86400", authRequestJSON) + respBody, err := HTTPRequest[models.TokenFE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+accountId+"/token?expires_in=86400", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -99,7 +72,7 @@ func HTTPCreateTokenWE(client_id, client_secret, code string) (models.TokenRespo return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) + respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -124,7 +97,7 @@ func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenRe return models.TokenResponse{}, err } - respBody, err := HTTPRequest(http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) + respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -137,6 +110,6 @@ func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenRe return authenticationResponse, err } -func HTTPCheckToken(token string) (models.Token, error) { - return HTTPGetItem[models.Token](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) +func HTTPCheckToken(token string) (models.TokenFE, error) { + return HTTPGetItem[models.TokenFE](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) } diff --git a/utils/http_request/common/token_test.go b/utils/http_request/common/token_test.go deleted file mode 100644 index e736f62..0000000 --- a/utils/http_request/common/token_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package common - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestHTTPCheckToken(t *testing.T) { - - respBody, err := HTTPCheckToken("token") - - assert.NotNil(t, respBody) - assert.Nil(t, err) - - assert.Equal(t, "client_id", respBody.ClientID) - assert.Equal(t, "account_id", respBody.AccountID) - assert.Equal(t, 0, respBody.ExpiresIn) - assert.Equal(t, "*", respBody.Scope) -} - -func TestHTTPCreateToken(t *testing.T) { - respBody, err := HTTPCreateToken("client_id", "client_secret", "client_credentials", "*", 86400) - - assert.NotNil(t, respBody) - assert.Nil(t, err) - - assert.Equal(t, "access_token", respBody.AccessToken) - assert.Equal(t, "refresh_token", respBody.RefreshToken) -} diff --git a/utils/http_request/feature_experimentation/account_environment.go b/utils/http_request/feature_experimentation/account_environment.go new file mode 100644 index 0000000..65a1cb9 --- /dev/null +++ b/utils/http_request/feature_experimentation/account_environment.go @@ -0,0 +1,19 @@ +package feature_experimentation + +import ( + models "github.com/flagship-io/flagship/models/feature_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request/common" +) + +type AccountEnvironmentRequester struct { + *common.ResourceRequest +} + +func (a *AccountEnvironmentRequester) HTTPListAccountEnvironment() ([]models.AccountEnvironment, error) { + return common.HTTPGetAllPages[models.AccountEnvironment](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments") +} + +func (a *AccountEnvironmentRequester) HTTPGetAccountEnvironment(id string) (models.AccountEnvironment, error) { + return common.HTTPGetItem[models.AccountEnvironment](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments/" + id) +} diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index f536def..b903f13 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -14,19 +14,19 @@ type CampaignRequester struct { } func (c *CampaignRequester) HTTPListCampaign() ([]models.Campaign, error) { - return common.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvID + "/campaigns") + return common.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") } func (c *CampaignRequester) HTTPGetCampaign(id string) (models.Campaign, error) { - return common.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvID + "/campaigns/" + id) + return common.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns/" + id) } func (c *CampaignRequester) HTTPCreateCampaign(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns", []byte(data)) + return common.HTTPRequest[models.Campaign](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns", []byte(data)) } func (c *CampaignRequester) HTTPEditCampaign(id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id, []byte(data)) + return common.HTTPRequest[models.Campaign](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, []byte(data)) } func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { @@ -39,11 +39,11 @@ func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { return err } - _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + _, err = common.HTTPRequest[models.Campaign](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) return err } func (c *CampaignRequester) HTTPDeleteCampaign(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvID+"/campaigns/"+id, nil) + _, err := common.HTTPRequest[models.Campaign](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/campaign_test.go b/utils/http_request/feature_experimentation/campaign_test.go index 931a567..65fbe13 100644 --- a/utils/http_request/feature_experimentation/campaign_test.go +++ b/utils/http_request/feature_experimentation/campaign_test.go @@ -3,13 +3,13 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var campaignRequester = CampaignRequester{} +var campaignRequester = CampaignRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetCampaign(t *testing.T) { - respBody, err := campaignRequester.HTTPGetCampaign("testCampaignID") assert.NotNil(t, respBody) @@ -23,7 +23,6 @@ func TestHTTPGetCampaign(t *testing.T) { } func TestHTTPListCampaign(t *testing.T) { - respBody, err := campaignRequester.HTTPListCampaign() assert.NotNil(t, respBody) diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go index 968ffb2..5411ffc 100644 --- a/utils/http_request/feature_experimentation/flag.go +++ b/utils/http_request/feature_experimentation/flag.go @@ -21,14 +21,14 @@ func (f *FlagRequester) HTTPGetFlag(id string) (models.Flag, error) { } func (f *FlagRequester) HTTPCreateFlag(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags", []byte(data)) + return common.HTTPRequest[models.Flag](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags", []byte(data)) } func (f *FlagRequester) HTTPEditFlag(id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, []byte(data)) + return common.HTTPRequest[models.Flag](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, []byte(data)) } func (f *FlagRequester) HTTPDeleteFlag(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, nil) + _, err := common.HTTPRequest[models.Flag](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+f.AccountID+"/flags/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/flag_test.go b/utils/http_request/feature_experimentation/flag_test.go index 0565c04..ad26314 100644 --- a/utils/http_request/feature_experimentation/flag_test.go +++ b/utils/http_request/feature_experimentation/flag_test.go @@ -3,10 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var flagRequester = FlagRequester{} +var flagRequester = FlagRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetFlag(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go index c6fb39a..8281126 100644 --- a/utils/http_request/feature_experimentation/goal.go +++ b/utils/http_request/feature_experimentation/goal.go @@ -13,22 +13,22 @@ type GoalRequester struct { } func (g *GoalRequester) HTTPListGoal() ([]models.Goal, error) { - return common.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvID + "/goals") + return common.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvironmentID + "/goals") } func (g *GoalRequester) HTTPGetGoal(id string) (models.Goal, error) { - return common.HTTPGetItem[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvID + "/goals/" + id) + return common.HTTPGetItem[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvironmentID + "/goals/" + id) } func (g *GoalRequester) HTTPCreateGoal(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals", []byte(data)) + return common.HTTPRequest[models.Flag](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvironmentID+"/goals", []byte(data)) } func (g *GoalRequester) HTTPEditGoal(id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals/"+id, []byte(data)) + return common.HTTPRequest[models.Flag](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvironmentID+"/goals/"+id, []byte(data)) } func (g *GoalRequester) HTTPDeleteGoal(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvID+"/goals/"+id, nil) + _, err := common.HTTPRequest[models.Flag](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+g.AccountID+"/account_environments/"+g.AccountEnvironmentID+"/goals/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/goal_test.go b/utils/http_request/feature_experimentation/goal_test.go index d263a96..bb0752b 100644 --- a/utils/http_request/feature_experimentation/goal_test.go +++ b/utils/http_request/feature_experimentation/goal_test.go @@ -3,10 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var goalRequester = GoalRequester{} +var goalRequester = GoalRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetGoal(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/main_test.go b/utils/http_request/feature_experimentation/main_test.go index fa626a1..40068eb 100644 --- a/utils/http_request/feature_experimentation/main_test.go +++ b/utils/http_request/feature_experimentation/main_test.go @@ -3,8 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" mockfunction "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + mockfunction_ "github.com/flagship-io/flagship/utils/mock_function" + "github.com/jarcoal/httpmock" ) @@ -13,6 +16,8 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() + common.Init(mockfunction_.Auth) + mockfunction.APIProject() mockfunction.APICampaign() mockfunction.APIFlag() @@ -22,5 +27,7 @@ func TestMain(m *testing.M) { mockfunction.APIVariation() mockfunction.APIUser() mockfunction.APIPanic() + mockfunction.APIToken() + m.Run() } diff --git a/utils/http_request/feature_experimentation/panic.go b/utils/http_request/feature_experimentation/panic.go index 662ef0c..79ce6f4 100644 --- a/utils/http_request/feature_experimentation/panic.go +++ b/utils/http_request/feature_experimentation/panic.go @@ -18,6 +18,6 @@ func (p *PanicRequester) HTTPUpdatePanic(panicStatus string) ([]byte, error) { if err != nil { return nil, err } - resp, err := common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/account_environments/"+p.AccountEnvID+"/panic", panicRequestJSON) + resp, err := common.HTTPRequest[models.PanicRequest](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/account_environments/"+p.AccountEnvironmentID+"/panic", panicRequestJSON) return resp, err } diff --git a/utils/http_request/feature_experimentation/panic_test.go b/utils/http_request/feature_experimentation/panic_test.go index ad64efd..3f725d7 100644 --- a/utils/http_request/feature_experimentation/panic_test.go +++ b/utils/http_request/feature_experimentation/panic_test.go @@ -3,10 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var panicRequester = PanicRequester{} +var panicRequester = PanicRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPUpdatePanic(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go index fd50be0..2a027e6 100644 --- a/utils/http_request/feature_experimentation/project.go +++ b/utils/http_request/feature_experimentation/project.go @@ -22,11 +22,11 @@ func (p *ProjectRequester) HTTPGetProject(id string) (models.Project, error) { } func (p *ProjectRequester) HTTPCreateProject(data []byte) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects", data) + return common.HTTPRequest[models.Project](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects", data) } func (p *ProjectRequester) HTTPEditProject(id string, data []byte) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, data) + return common.HTTPRequest[models.Project](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, data) } func (p *ProjectRequester) HTTPSwitchProject(id, state string) error { @@ -39,11 +39,11 @@ func (p *ProjectRequester) HTTPSwitchProject(id, state string) error { return err } - _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id+"/toggle", projectRequestJSON) + _, err = common.HTTPRequest[models.Project](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id+"/toggle", projectRequestJSON) return err } func (p *ProjectRequester) HTTPDeleteProject(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, nil) + _, err := common.HTTPRequest[models.Project](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+p.AccountID+"/projects/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/project_test.go b/utils/http_request/feature_experimentation/project_test.go index f44f05d..c8b8348 100644 --- a/utils/http_request/feature_experimentation/project_test.go +++ b/utils/http_request/feature_experimentation/project_test.go @@ -6,10 +6,11 @@ import ( "testing" models "github.com/flagship-io/flagship/models/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var projectRequester = ProjectRequester{} +var projectRequester = ProjectRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetProject(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go index 0b13139..5b0f571 100644 --- a/utils/http_request/feature_experimentation/targeting_key.go +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -21,14 +21,14 @@ func (t *TargetingKeyRequester) HTTPGetTargetingKey(id string) (models.Targeting } func (t *TargetingKeyRequester) HTTPCreateTargetingKey(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys", []byte(data)) + return common.HTTPRequest[models.TargetingKey](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys", []byte(data)) } func (t *TargetingKeyRequester) HTTPEditTargetingKey(id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, []byte(data)) + return common.HTTPRequest[models.TargetingKey](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, []byte(data)) } func (t *TargetingKeyRequester) HTTPDeleteTargetingKey(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, nil) + _, err := common.HTTPRequest[models.TargetingKey](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/targeting_keys/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/targeting_key_test.go b/utils/http_request/feature_experimentation/targeting_key_test.go index 9768c5f..81e0c52 100644 --- a/utils/http_request/feature_experimentation/targeting_key_test.go +++ b/utils/http_request/feature_experimentation/targeting_key_test.go @@ -3,10 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var targetingKeyRequester = TargetingKeyRequester{} +var targetingKeyRequester = TargetingKeyRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetTargetingKey(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go index 9ec4402..d47a581 100644 --- a/utils/http_request/feature_experimentation/user.go +++ b/utils/http_request/feature_experimentation/user.go @@ -14,14 +14,14 @@ type UserRequester struct { } func (u *UserRequester) HTTPListUsers() ([]models.User, error) { - return common.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + u.AccountID + "/account_environments/" + u.AccountEnvID + "/users") + return common.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + u.AccountID + "/account_environments/" + u.AccountEnvironmentID + "/users") } func (u *UserRequester) HTTPBatchUpdateUsers(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPut, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvID+"/users", []byte(data)) + return common.HTTPRequest[models.User](http.MethodPut, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvironmentID+"/users", []byte(data)) } func (u *UserRequester) HTTPDeleteUsers(email string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvID+"/users?emails[]="+url.QueryEscape(email), nil) + _, err := common.HTTPRequest[models.User](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+u.AccountID+"/account_environments/"+u.AccountEnvironmentID+"/users?emails[]="+url.QueryEscape(email), nil) return err } diff --git a/utils/http_request/feature_experimentation/user_test.go b/utils/http_request/feature_experimentation/user_test.go index 09fc0bd..983fc91 100644 --- a/utils/http_request/feature_experimentation/user_test.go +++ b/utils/http_request/feature_experimentation/user_test.go @@ -3,10 +3,11 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) -var userRequester = UserRequester{} +var userRequester = UserRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPListUsers(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index 16d3ff3..8a6ce0f 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -13,22 +13,22 @@ type VariationRequester struct { } func (v *VariationRequester) HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return common.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") + return common.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") } func (v *VariationRequester) HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { - return common.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) + return common.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) } func (v *VariationRequester) HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) + return common.HTTPRequest[models.Variation](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) } func (v *VariationRequester) HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) + return common.HTTPRequest[models.Variation](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) } func (v *VariationRequester) HTTPDeleteVariation(campaignID, variationGroupID, id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) + _, err := common.HTTPRequest[models.Variation](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go index 2cb763b..fa4c3e7 100644 --- a/utils/http_request/feature_experimentation/variation_group.go +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -13,22 +13,22 @@ type VariationGroupRequester struct { } func (vg *VariationGroupRequester) HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { - return common.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups") + return common.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups") } func (vg *VariationGroupRequester) HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { - return common.HTTPGetItem[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvID + "/campaigns/" + campaignID + "/variation_groups/" + id) + return common.HTTPGetItem[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + id) } func (vg *VariationGroupRequester) HTTPCreateVariationGroup(campaignID, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) + return common.HTTPRequest[models.VariationGroup](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups", []byte(data)) } func (vg *VariationGroupRequester) HTTPEditVariationGroup(campaignID, id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) + return common.HTTPRequest[models.VariationGroup](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+id, []byte(data)) } func (vg *VariationGroupRequester) HTTPDeleteVariationGroup(campaignID, id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvID+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) + _, err := common.HTTPRequest[models.VariationGroup](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+vg.AccountID+"/account_environments/"+vg.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_group_test.go b/utils/http_request/feature_experimentation/variation_group_test.go index 98ddf74..36ef802 100644 --- a/utils/http_request/feature_experimentation/variation_group_test.go +++ b/utils/http_request/feature_experimentation/variation_group_test.go @@ -3,11 +3,12 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) var CampaignID = "campaignID" -var variationGroupRequester = VariationGroupRequester{} +var variationGroupRequester = VariationGroupRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetVariationGroup(t *testing.T) { diff --git a/utils/http_request/feature_experimentation/variation_test.go b/utils/http_request/feature_experimentation/variation_test.go index dfed6c6..66b0464 100644 --- a/utils/http_request/feature_experimentation/variation_test.go +++ b/utils/http_request/feature_experimentation/variation_test.go @@ -3,11 +3,12 @@ package feature_experimentation import ( "testing" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/stretchr/testify/assert" ) var variationGroupID = "variationGroupID" -var variationRequester = VariationRequester{} +var variationRequester = VariationRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetVariation(t *testing.T) { diff --git a/utils/http_request/main.go b/utils/http_request/main.go index 42f337c..fc522f7 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -11,7 +11,10 @@ type HTTPResource interface { var ResourceRequester common.ResourceRequest +var HTTPResources = []HTTPResource{&ResourceRequester} + var CampaignRequester feature_experimentation.CampaignRequester = feature_experimentation.CampaignRequester{ResourceRequest: &ResourceRequester} +var AccountEnvironmentRequester feature_experimentation.AccountEnvironmentRequester = feature_experimentation.AccountEnvironmentRequester{ResourceRequest: &ResourceRequester} var FlagRequester feature_experimentation.FlagRequester = feature_experimentation.FlagRequester{ResourceRequest: &ResourceRequester} var GoalRequester feature_experimentation.GoalRequester = feature_experimentation.GoalRequester{ResourceRequest: &ResourceRequester} var ProjectRequester feature_experimentation.ProjectRequester = feature_experimentation.ProjectRequester{ResourceRequest: &ResourceRequester} @@ -20,5 +23,3 @@ var TargetingKeyRequester feature_experimentation.TargetingKeyRequester = featur var VariationGroupRequester feature_experimentation.VariationGroupRequester = feature_experimentation.VariationGroupRequester{ResourceRequest: &ResourceRequester} var VariationRequester feature_experimentation.VariationRequester = feature_experimentation.VariationRequester{ResourceRequest: &ResourceRequester} var PanicRequester feature_experimentation.PanicRequester = feature_experimentation.PanicRequester{ResourceRequest: &ResourceRequester} - -var HTTPResources = []HTTPResource{&ResourceRequester} diff --git a/utils/http_request/main_test.go b/utils/http_request/main_test.go index 0d933af..124c595 100644 --- a/utils/http_request/main_test.go +++ b/utils/http_request/main_test.go @@ -4,7 +4,7 @@ import ( "testing" mockfunction "github.com/flagship-io/flagship/utils/mock_function" - + "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" ) @@ -13,7 +13,7 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - mockfunction.APIToken() + feature_experimentation.APIToken() mockfunction.Request() m.Run() } diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index 4841634..42ef979 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -18,11 +18,11 @@ func HTTPGetTest(id string) (models.Test, error) { } func HTTPCreateTest(data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) + return common.HTTPRequest[models.Test](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) } func HTTPEditTest(id, data string) ([]byte, error) { - return common.HTTPRequest(http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) + return common.HTTPRequest[models.Test](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) } /* func HTTPSwitchCampaign(id, state string) error { @@ -40,6 +40,6 @@ func HTTPEditTest(id, data string) ([]byte, error) { } */ func HTTPDeleteTest(id string) error { - _, err := common.HTTPRequest(http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) + _, err := common.HTTPRequest[models.Test](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) return err } diff --git a/utils/mock_function/configuration.go b/utils/mock_function/configuration.go index eb5aba4..3b6fe52 100644 --- a/utils/mock_function/configuration.go +++ b/utils/mock_function/configuration.go @@ -1,13 +1,6 @@ package mockfunction -import ( - "os" - - "github.com/flagship-io/flagship/models" - "github.com/flagship-io/flagship/utils/config" -) - -var TestConfiguration = models.Configuration{ +/* var TestConfiguration = models.Configuration{ Name: "test_configuration", ClientID: "testConfigurationClientID", ClientSecret: "testConfigurationClientSecret", @@ -18,4 +11,4 @@ var TestConfiguration = models.Configuration{ func InitMockConfiguration() { config.SetViperMock() os.Remove(config.SetPathForConfigName("test_configuration")) -} +} */ diff --git a/utils/mock_function/feature_experimentation/auth.go b/utils/mock_function/feature_experimentation/auth.go new file mode 100644 index 0000000..5070ec6 --- /dev/null +++ b/utils/mock_function/feature_experimentation/auth.go @@ -0,0 +1,12 @@ +package feature_experimentation + +import ( + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" +) + +func InitMockAuth() { + os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, "test_configuration")) +} diff --git a/utils/mock_function/feature_experimentation/campaign.go b/utils/mock_function/feature_experimentation/campaign.go index 85be01b..d61b7a7 100644 --- a/utils/mock_function/feature_experimentation/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var scheduler = models.Scheduler{ @@ -97,7 +96,6 @@ var TestCampaignlist = []models.Campaign{ } func APICampaign() { - config.SetViperMock() resp := utils.HTTPListResponse[models.Campaign]{ Items: TestCampaignlist, @@ -108,42 +106,42 @@ func APICampaign() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaign) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaign) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestCampaignEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+TestCampaign.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+TestCampaign.Id+"/toggle", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+TestCampaign.Id+"/toggle", func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(200, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/flag.go b/utils/mock_function/feature_experimentation/flag.go index 7fe1409..64a3330 100644 --- a/utils/mock_function/feature_experimentation/flag.go +++ b/utils/mock_function/feature_experimentation/flag.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestFlag = models.Flag{ @@ -40,7 +39,6 @@ var TestFlagList = []models.Flag{ } func APIFlag() { - config.SetViperMock() resp := utils.HTTPListResponse[models.Flag]{ Items: TestFlagList, @@ -51,35 +49,35 @@ func APIFlag() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlag) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/flags", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/flags", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlag) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestFlagEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/flags/"+TestFlag.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/flags/"+TestFlag.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/goal.go b/utils/mock_function/feature_experimentation/goal.go index 4e82485..adb905e 100644 --- a/utils/mock_function/feature_experimentation/goal.go +++ b/utils/mock_function/feature_experimentation/goal.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestGoal = models.Goal{ @@ -40,7 +39,6 @@ var TestGoalList = []models.Goal{ } func APIGoal() { - config.SetViperMock() resp := utils.HTTPListResponse[models.Goal]{ Items: TestGoalList, @@ -51,35 +49,35 @@ func APIGoal() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoal) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/goals", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/goals", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoal) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestGoalEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/goals/"+TestGoal.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/goals/"+TestGoal.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/panic.go b/utils/mock_function/feature_experimentation/panic.go index be0c67f..0854c26 100644 --- a/utils/mock_function/feature_experimentation/panic.go +++ b/utils/mock_function/feature_experimentation/panic.go @@ -4,15 +4,13 @@ import ( "net/http" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) func APIPanic() { - config.SetViperMock() - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/panic", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/panic", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, "") return resp, nil diff --git a/utils/mock_function/feature_experimentation/project.go b/utils/mock_function/feature_experimentation/project.go index 41e65ca..4be44e3 100644 --- a/utils/mock_function/feature_experimentation/project.go +++ b/utils/mock_function/feature_experimentation/project.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestProject = models.Project{ @@ -31,9 +30,6 @@ var TestProjectList = []models.Project{ } func APIProject() { - - config.SetViperMock() - resp := utils.HTTPListResponse[models.Project]{ Items: TestProjectList, CurrentItemsCount: 2, @@ -43,42 +39,42 @@ func APIProject() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProject) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProject) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestProjectEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects/"+TestProject.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/projects/"+TestProject.Id+"/toggle", + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/projects/"+TestProject.Id+"/toggle", func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(200, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/targeting_key.go b/utils/mock_function/feature_experimentation/targeting_key.go index aa0c069..ebc9b05 100644 --- a/utils/mock_function/feature_experimentation/targeting_key.go +++ b/utils/mock_function/feature_experimentation/targeting_key.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestTargetingKey = models.TargetingKey{ @@ -38,8 +37,6 @@ var TestTargetingKeyList = []models.TargetingKey{ func APITargetingKey() { - config.SetViperMock() - resp := utils.HTTPListResponse[models.TargetingKey]{ Items: TestTargetingKeyList, CurrentItemsCount: 2, @@ -49,35 +46,35 @@ func APITargetingKey() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKey) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/targeting_keys", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/targeting_keys", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKey) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestTargetingKeyEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/targeting_keys/"+TestTargetingKey.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/targeting_keys/"+TestTargetingKey.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/token.go b/utils/mock_function/feature_experimentation/token.go similarity index 74% rename from utils/mock_function/token.go rename to utils/mock_function/feature_experimentation/token.go index 4f5ced2..84ac9ec 100644 --- a/utils/mock_function/token.go +++ b/utils/mock_function/feature_experimentation/token.go @@ -1,17 +1,15 @@ -package mockfunction +package feature_experimentation import ( "net/http" - "strconv" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) -var TestToken = models.Token{ +var TestToken = models.TokenFE{ ClientID: "client_id", AccountID: "account_id", ExpiresIn: 0, @@ -19,10 +17,8 @@ var TestToken = models.Token{ } func APIToken() { - config.SetViperMock() token := "token" - tokenExpiration := 86400 testAuthenticationResponse := models.TokenResponse{ AccessToken: "access_token", @@ -36,7 +32,7 @@ func APIToken() { }, ) - httpmock.RegisterResponder("POST", utils.GetHostFeatureExperimentationAuth()+"/"+viper.GetString("account_id")+"/token?expires_in="+strconv.Itoa(tokenExpiration), + httpmock.RegisterResponder("POST", utils.GetHostFeatureExperimentationAuth()+"/"+mockfunction.Auth.AccountID+"/token?expires_in=86400", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, testAuthenticationResponse) return resp, nil diff --git a/utils/mock_function/feature_experimentation/user.go b/utils/mock_function/feature_experimentation/user.go index 241cf6f..a0c7817 100644 --- a/utils/mock_function/feature_experimentation/user.go +++ b/utils/mock_function/feature_experimentation/user.go @@ -6,9 +6,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestUserList = []models.User{ @@ -23,7 +22,6 @@ var TestUserList = []models.User{ } func APIUser() { - config.SetViperMock() email := "example@abtasty.com" @@ -36,21 +34,21 @@ func APIUser() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/users", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("PUT", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users", + httpmock.RegisterResponder("PUT", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/users", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(204, "") return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/users?emails[]="+url.QueryEscape(email), + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/users?emails[]="+url.QueryEscape(email), func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(204, "") return resp, nil diff --git a/utils/mock_function/feature_experimentation/variation.go b/utils/mock_function/feature_experimentation/variation.go index 7bbf2fc..9672b68 100644 --- a/utils/mock_function/feature_experimentation/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var TestVariation = models.Variation{ @@ -50,8 +49,6 @@ var TestVariationList = []models.Variation{ func APIVariation() { - config.SetViperMock() - campaignID := "campaignID" variationGroupID := "variationGroupID" @@ -64,35 +61,35 @@ func APIVariation() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariation) return resp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, resp) return resp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariation) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+TestVariation.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/feature_experimentation/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go index 7efa1f3..60f55fd 100644 --- a/utils/mock_function/feature_experimentation/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -5,9 +5,8 @@ import ( models "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/jarcoal/httpmock" - "github.com/spf13/viper" ) var targetingGroups = []models.TargetingGroup{ @@ -66,8 +65,6 @@ var TestVariationGroupList = []models.VariationGroup{ func APIVariationGroup() { - config.SetViperMock() - campaignID := "campaignID" resp := utils.HTTPListResponse[models.VariationGroup]{ @@ -79,35 +76,35 @@ func APIVariationGroup() { LastPage: 1, } - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { mockResp, _ := httpmock.NewJsonResponse(200, TestVariationGroup) return mockResp, nil }, ) - httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups", func(req *http.Request) (*http.Response, error) { mockResp, _ := httpmock.NewJsonResponse(200, resp) return mockResp, nil }, ) - httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups", + httpmock.RegisterResponder("POST", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationGroup) return resp, nil }, ) - httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("PATCH", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestVariationGroupEdit) return resp, nil }, ) - httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, + httpmock.RegisterResponder("DELETE", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+mockfunction.Auth.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+TestVariationGroup.Id, func(req *http.Request) (*http.Response, error) { return httpmock.NewStringResponse(204, ""), nil }, diff --git a/utils/mock_function/request.go b/utils/mock_function/request.go index c5f26a3..cda6738 100644 --- a/utils/mock_function/request.go +++ b/utils/mock_function/request.go @@ -4,16 +4,33 @@ import ( "net/http" "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/config" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/jarcoal/httpmock" + "github.com/spf13/viper" ) type TestRequest struct { Name string `json:"name"` } +var Auth = common.RequestConfig{ + Username: "test_configuration", + ClientID: "client_id", + ClientSecret: "client_secret", + AccountID: "account_id", + AccountEnvironmentID: "account_environment_id", + Token: "access_token", +} + +func SetMock(c *common.ResourceRequest) { + viper.GetViper().Set("output_format", "json") + common.Init(Auth) + + r := c + r.Init(&Auth) +} + func Request() { - config.SetViperMock() testRequest := TestRequest{ Name: "TestName", From b586ca11f28198bbe5c5edac0d04981039e1588c Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 2 Apr 2024 14:54:04 +0000 Subject: [PATCH 09/48] finalize fe auth and we auth --- cmd/feature_experimentation/account/list.go | 2 +- cmd/feature_experimentation/auth/login.go | 106 ++--------- .../feature_experimentation.go | 14 +- cmd/web_experimentation/account/account.go | 22 +++ cmd/web_experimentation/account/current.go | 50 ++++++ cmd/web_experimentation/account/list.go | 33 ++++ cmd/web_experimentation/account/use.go | 40 +++++ cmd/web_experimentation/auth/auth.go | 23 +++ cmd/web_experimentation/auth/get.go | 56 ++++++ cmd/web_experimentation/auth/list.go | 62 +++++++ cmd/web_experimentation/auth/login.go | 167 ++++++++++++++++++ cmd/web_experimentation/campaign/get.go | 4 +- cmd/web_experimentation/campaign/list.go | 4 +- cmd/web_experimentation/global_code/list.go | 4 +- .../web_experimentation.go | 33 ++++ .../account_environment.go | 2 +- models/token.go | 32 ++++ models/web_experimentation/account.go | 8 + .../account_environment.go | 9 + .../{campaign-test.go => campaign.go} | 2 +- models/web_experimentation/global-code.go | 2 +- models/web_experimentation/vatiation-test.go | 2 +- utils/http_request/common/request.go | 16 +- utils/http_request/common/token.go | 82 ++++++++- .../account_environment.go | 10 +- .../feature_experimentation/campaign.go | 2 +- .../feature_experimentation/flag.go | 2 +- .../feature_experimentation/goal.go | 2 +- .../feature_experimentation/project.go | 2 +- .../feature_experimentation/targeting_key.go | 2 +- .../feature_experimentation/user.go | 2 +- .../feature_experimentation/variation.go | 2 +- .../variation_group.go | 2 +- utils/http_request/main.go | 9 +- .../web_experimentation/campaign.go | 25 +-- .../web_experimentation/global_code.go | 13 +- 36 files changed, 699 insertions(+), 149 deletions(-) create mode 100644 cmd/web_experimentation/account/account.go create mode 100644 cmd/web_experimentation/account/current.go create mode 100644 cmd/web_experimentation/account/list.go create mode 100644 cmd/web_experimentation/account/use.go create mode 100644 cmd/web_experimentation/auth/auth.go create mode 100644 cmd/web_experimentation/auth/get.go create mode 100644 cmd/web_experimentation/auth/list.go create mode 100644 cmd/web_experimentation/auth/login.go create mode 100644 models/web_experimentation/account.go create mode 100644 models/web_experimentation/account_environment.go rename models/web_experimentation/{campaign-test.go => campaign.go} (96%) diff --git a/cmd/feature_experimentation/account/list.go b/cmd/feature_experimentation/account/list.go index f7d8cf5..847a873 100644 --- a/cmd/feature_experimentation/account/list.go +++ b/cmd/feature_experimentation/account/list.go @@ -19,7 +19,7 @@ var listCmd = &cobra.Command{ Long: `list all auth from your system`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.AccountEnvironmentRequester.HTTPListAccountEnvironment() + body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 2fb22a7..4aaeaed 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -6,12 +6,7 @@ package auth import ( "fmt" "log" - "net/http" - "os" - "os/exec" - "runtime" "slices" - "time" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" @@ -21,76 +16,28 @@ import ( var ( credentialsFile string - browser bool ) -var ( - code string -) - -func checkSingleFlag(bool1, bool2, bool3 bool) bool { - return (bool1 && !bool2 && !bool3) || (!bool1 && bool2 && !bool3) || (!bool1 && !bool2 && bool3) -} -func openLink(url string) error { - var cmd *exec.Cmd - switch runtime.GOOS { - case "linux": - cmd = exec.Command("xdg-open", url) - case "darwin": - cmd = exec.Command("open", url) - case "windows": - cmd = exec.Command("cmd", "/c", "start", url) - default: - return fmt.Errorf("unsupported operating system") +func checkSingleFlag(bool1, bool2 bool) bool { + count := 0 + if bool1 { + count++ + } + if bool2 { + count++ } - err := cmd.Run() - return err + + return count == 1 } // createCmd represents the create command var loginCmd = &cobra.Command{ - Use: "login [--browser] | [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", + Use: "login [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", Short: "login", Long: `login`, Run: func(cmd *cobra.Command, args []string) { - if !checkSingleFlag(browser, credentialsFile != "", Username != "") { - log.Fatalf("error occurred: %s", "1 flag is required. (browser, username, credential-file)") - } - - if browser { - clientID := utils.CLIENT_ID - clientSecret := utils.CLIENT_SECRET - - if ClientID != "" { - clientID = ClientID - } - - if ClientSecret != "" { - clientSecret = ClientSecret - } - - var url = fmt.Sprintf("https://auth.abtasty.com/authorize?client_id=%s&client_secret=%s&redirect_uri=http://localhost:8010/auth/callback", clientID, clientSecret) - - if err := openLink(url); err != nil { - log.Fatalf("Error opening link: %s", err) - } - http.HandleFunc("/auth/callback", handleCallback) - if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { - log.Fatalf("Error starting callback server: %s", err) - } - - authenticationResponse, err := common.HTTPCreateTokenWE(clientID, clientSecret, code) - if err != nil { - log.Fatalf("%s", err) - return - } - - if authenticationResponse.AccessToken == "" { - log.Fatal("client_id or client_secret not valid") - } - - fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") - + if !checkSingleFlag(credentialsFile != "", Username != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (browser, username, credential-file, email)") } if credentialsFile != "" { @@ -144,32 +91,11 @@ var loginCmd = &cobra.Command{ func init() { - loginCmd.Flags().StringVarP(&Username, "username", "u", "", "configuration name") - loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of a configuration") - loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of a configuration") - loginCmd.Flags().StringVarP(&AccountId, "account-id", "a", "", "account id of a configuration") + loginCmd.Flags().StringVarP(&Username, "username", "u", "", "auth username") + loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of an auth") + loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of an auth") + loginCmd.Flags().StringVarP(&AccountId, "account-id", "a", "", "account id of an auth") loginCmd.Flags().StringVarP(&credentialsFile, "credential-file", "p", "", "config file to create") - loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "Generate link for browser") - AuthCmd.AddCommand(loginCmd) } - -func handleCallback(w http.ResponseWriter, r *http.Request) { - fmt.Println(r.URL.Query().Get("code")) - code = r.URL.Query().Get("code") - if code == "" { - http.Error(w, "No token found in URL", http.StatusBadRequest) - os.Exit(0) - return - } - - http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) - - fmt.Println("code received:", code) - - go func() { - time.Sleep(5 * time.Second) - os.Exit(0) - }() -} diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 9757894..2ffc22a 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -71,16 +71,16 @@ func initConfig() { vL := config.ReadAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("current_used_credential")) v.MergeConfigMap(vL.AllSettings()) + } - v.Unmarshal(&requestConfig) - common.Init(requestConfig) - resource.Init(requestConfig) + v.Unmarshal(&requestConfig) + common.Init(requestConfig) + resource.Init(requestConfig) - r := &http_request.ResourceRequester + r := &http_request.ResourceRequester - r.Init(&requestConfig) + r.Init(&requestConfig) - return - } + return } diff --git a/cmd/web_experimentation/account/account.go b/cmd/web_experimentation/account/account.go new file mode 100644 index 0000000..d8ba6a4 --- /dev/null +++ b/cmd/web_experimentation/account/account.go @@ -0,0 +1,22 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import "github.com/spf13/cobra" + +var ( + Username string + AccountID string + AccountEnvironmentID string +) + +// ConfigurationCmd represents the configuration command +var AccountCmd = &cobra.Command{ + Use: "account [use|list|current]", + Short: "Manage your CLI authentication", + Long: `Manage your CLI authentication`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/account/current.go b/cmd/web_experimentation/account/current.go new file mode 100644 index 0000000..e1e0015 --- /dev/null +++ b/cmd/web_experimentation/account/current.go @@ -0,0 +1,50 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// getCmd represents the list command +var currentCmd = &cobra.Command{ + Use: "current", + Short: "current an auth credential", + Long: `current an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var configurationYaml models.AccountYaml + var configuration models.AccountJSON + + yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &configurationYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential + configuration.AccountID = configurationYaml.AccountID + configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID + + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + AccountCmd.AddCommand(currentCmd) +} diff --git a/cmd/web_experimentation/account/list.go b/cmd/web_experimentation/account/list.go new file mode 100644 index 0000000..847a873 --- /dev/null +++ b/cmd/web_experimentation/account/list.go @@ -0,0 +1,33 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "list all auth", + Long: `list all auth from your system`, + Run: func(cmd *cobra.Command, args []string) { + + body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "Environment", "IsMain", "Panic", "SingleAssignment"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + + AccountCmd.AddCommand(listCmd) +} diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go new file mode 100644 index 0000000..62b91b6 --- /dev/null +++ b/cmd/web_experimentation/account/use.go @@ -0,0 +1,40 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account + +import ( + "fmt" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" +) + +// getCmd represents the list command +var useCmd = &cobra.Command{ + Use: "use", + Short: "get an auth credential", + Long: `list an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + if AccountID == "" && AccountEnvironmentID == "" { + fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id or account-environment-id") + return + } + + if AccountID != "" { + config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) + } + + if AccountEnvironmentID != "" { + config.SetAccountEnvID(utils.WEB_EXPERIMENTATION, AccountEnvironmentID) + } + }, +} + +func init() { + useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") + useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to display") + + AccountCmd.AddCommand(useCmd) +} diff --git a/cmd/web_experimentation/auth/auth.go b/cmd/web_experimentation/auth/auth.go new file mode 100644 index 0000000..5a0a880 --- /dev/null +++ b/cmd/web_experimentation/auth/auth.go @@ -0,0 +1,23 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import "github.com/spf13/cobra" + +var ( + ClientID string + ClientSecret string + Username string +) + +// ConfigurationCmd represents the configuration command +var AuthCmd = &cobra.Command{ + Use: "authentication [login|get|list]", + Aliases: []string{"auth"}, + Short: "Manage your CLI authentication for web experimentation", + Long: `Manage your CLI authentication for web experimentation`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/auth/get.go b/cmd/web_experimentation/auth/get.go new file mode 100644 index 0000000..faabf80 --- /dev/null +++ b/cmd/web_experimentation/auth/get.go @@ -0,0 +1,56 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// getCmd represents the list command +var getCmd = &cobra.Command{ + Use: "get", + Short: "get an auth credential for web experimentation", + Long: `get an auth credential for web experimentation from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var authYaml models.AuthYaml + var auth models.Auth + + yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, Username)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &authYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + auth.Username = authYaml.Username + auth.ClientID = authYaml.ClientID + auth.ClientSecret = authYaml.ClientSecret + + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + getCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to display") + + if err := getCmd.MarkFlagRequired("username"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + AuthCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/auth/list.go b/cmd/web_experimentation/auth/list.go new file mode 100644 index 0000000..0d1df26 --- /dev/null +++ b/cmd/web_experimentation/auth/list.go @@ -0,0 +1,62 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "list all auth", + Long: `list all auth from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var auths []models.Auth + existingAuths, err := config.GetUsernames(utils.WEB_EXPERIMENTATION) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + for _, fileName := range existingAuths { + if fileName != "" { + var configurationYaml models.AuthYaml + var configuration models.Auth + yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, fileName)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &configurationYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + if configurationYaml.Username != "" { + configuration.Username = configurationYaml.Username + configuration.ClientID = configurationYaml.ClientID + configuration.ClientSecret = configurationYaml.ClientSecret + auths = append(auths, configuration) + } + } + } + + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + + AuthCmd.AddCommand(listCmd) +} diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go new file mode 100644 index 0000000..0311617 --- /dev/null +++ b/cmd/web_experimentation/auth/login.go @@ -0,0 +1,167 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "fmt" + "log" + "net/http" + "os" + "os/exec" + "runtime" + "slices" + "time" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/spf13/cobra" +) + +var ( + browser bool + password string + totp string + code string +) + +func checkSingleFlag(bool1, bool2 bool) bool { + count := 0 + if bool1 { + count++ + } + if bool2 { + count++ + } + + return count == 1 +} + +func openLink(url string) error { + var cmd *exec.Cmd + switch runtime.GOOS { + case "linux": + cmd = exec.Command("xdg-open", url) + case "darwin": + cmd = exec.Command("open", url) + case "windows": + cmd = exec.Command("cmd", "/c", "start", url) + default: + return fmt.Errorf("unsupported operating system") + } + err := cmd.Run() + return err +} + +// createCmd represents the create command +var loginCmd = &cobra.Command{ + Use: "login [--browser] [-i | --client-id=] [-s | --client-secret=] | [-u | --username=] [--password ]", + Short: "login", + Long: `login`, + Run: func(cmd *cobra.Command, args []string) { + if !checkSingleFlag(browser, Username != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (browser, username)") + } + + if browser { + clientID := utils.CLIENT_ID + clientSecret := utils.CLIENT_SECRET + + if ClientID != "" { + clientID = ClientID + } + + if ClientSecret != "" { + clientSecret = ClientSecret + } + + var url = fmt.Sprintf("https://auth.abtasty.com/authorize?client_id=%s&client_secret=%s&redirect_uri=http://localhost:8010/auth/callback", clientID, clientSecret) + + if err := openLink(url); err != nil { + log.Fatalf("Error opening link: %s", err) + } + http.HandleFunc("/auth/callback", handleCallback) + if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { + log.Fatalf("Error starting callback server: %s", err) + } + + authenticationResponse, err := common.HTTPCreateTokenWEAuthorizationCode(clientID, clientSecret, code) + if err != nil { + log.Fatalf("%s", err) + return + } + + if authenticationResponse.AccessToken == "" { + log.Fatal("Credentials not valid.") + } + + fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") + + } + + if Username != "" { + existingCredentials, err := config.GetUsernames(utils.WEB_EXPERIMENTATION) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + if slices.Contains(existingCredentials, Username) { + config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + + fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + return + } + + if password == "" && totp == "" { + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (password, totp)") + return + } + authenticationResponse, err := common.HTTPCreateTokenWEPassword(utils.CLIENT_ID, utils.CLIENT_SECRET, Username, password, totp) + if err != nil { + log.Fatalf("%s", err) + return + } + + if authenticationResponse.AccessToken == "" { + log.Fatal("Credentials not valid.") + } + config.CreateAuthFile(utils.WEB_EXPERIMENTATION, Username, "", "", authenticationResponse) + config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") + } + + }, +} + +func init() { + + loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of an auth") + loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of an auth") + + loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "Generate link for browser") + loginCmd.Flags().StringVarP(&Username, "username", "u", "", "configuration name") + loginCmd.Flags().StringVarP(&password, "password", "", "", "configuration name") + loginCmd.Flags().StringVarP(&totp, "totp", "", "", "configuration name") + + AuthCmd.AddCommand(loginCmd) +} + +func handleCallback(w http.ResponseWriter, r *http.Request) { + fmt.Println(r.URL.Query().Get("code")) + code = r.URL.Query().Get("code") + if code == "" { + http.Error(w, "No token found in URL", http.StatusBadRequest) + os.Exit(0) + return + } + + http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) + + fmt.Println("code received:", code) + + go func() { + time.Sleep(5 * time.Second) + os.Exit(0) + }() +} diff --git a/cmd/web_experimentation/campaign/get.go b/cmd/web_experimentation/campaign/get.go index 356421a..c573840 100644 --- a/cmd/web_experimentation/campaign/get.go +++ b/cmd/web_experimentation/campaign/get.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a test", Long: `Get a test in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetTest(CampaignID) + body, err := httprequest.TestRequester.HTTPGetTest(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/campaign/list.go b/cmd/web_experimentation/campaign/list.go index b64e5cb..adad5e8 100644 --- a/cmd/web_experimentation/campaign/list.go +++ b/cmd/web_experimentation/campaign/list.go @@ -7,7 +7,7 @@ import ( "log" "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" "github.com/spf13/viper" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all campaigns", Long: `List all campaigns`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListTest() + body, err := httprequest.TestRequester.HTTPListTest() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/global_code/list.go b/cmd/web_experimentation/global_code/list.go index c33a876..cdb9e4a 100644 --- a/cmd/web_experimentation/global_code/list.go +++ b/cmd/web_experimentation/global_code/list.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all global code", Long: `List all global code`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPListGlobalCode() + body, err := httprequest.GlobalCodeRequester.HTTPListGlobalCode() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 0c18b85..b62217e 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -4,11 +4,19 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package web_experimentation import ( + "os" + + "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" "github.com/flagship-io/flagship/cmd/web_experimentation/global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/flagship-io/flagship/utils/http_request" + "github.com/flagship-io/flagship/utils/http_request/common" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // WebExperimentationCmd represents the web experimentation command @@ -26,8 +34,33 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(campaign.CampaignCmd) WebExperimentationCmd.AddCommand(global_code.GlobalCodeCmd) WebExperimentationCmd.AddCommand(variation.VariationCmd) + WebExperimentationCmd.AddCommand(auth.AuthCmd) } func init() { + cobra.OnInitialize(initConfig) addSubCommandPalettes() } + +func initConfig() { + v := viper.New() + homeDir, _ := os.UserHomeDir() + var requestConfig = common.RequestConfig{Product: utils.WEB_EXPERIMENTATION} + + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") + v.MergeInConfig() + if v.GetString("current_used_credential") != "" { + vL := config.ReadAuth(utils.WEB_EXPERIMENTATION, v.GetString("current_used_credential")) + v.MergeConfigMap(vL.AllSettings()) + } + + v.Unmarshal(&requestConfig) + common.Init(requestConfig) + + r := &http_request.ResourceRequester + + r.Init(&requestConfig) + + return + +} diff --git a/models/feature_experimentation/account_environment.go b/models/feature_experimentation/account_environment.go index 7bda79e..3579380 100644 --- a/models/feature_experimentation/account_environment.go +++ b/models/feature_experimentation/account_environment.go @@ -1,6 +1,6 @@ package feature_experimentation -type AccountEnvironment struct { +type AccountEnvironmentFE struct { Id string `json:"id,omitempty"` Environment string `json:"environment"` IsMain bool `json:"is_main"` diff --git a/models/token.go b/models/token.go index 4c060e8..f65150b 100644 --- a/models/token.go +++ b/models/token.go @@ -7,6 +7,30 @@ type TokenWE struct { Scope string `json:"scope"` } +type MfaRequestWE struct { + MfaToken string `json:"mfa_token"` + MfaMethods []string `json:"mfa_methods"` +} + +type MultiFactorMethodRequestWE struct { + MfaToken string `json:"token"` + MfaMethod string `json:"mfa_method"` + GrantType string `json:"grant_type"` +} + +type MultiFactorRequestWE struct { + MfaToken string `json:"token"` + MfaMethod string `json:"mfa_method"` + GrantType string `json:"grant_type"` + Code string `json:"code"` +} + +type MultiFactorMethodResponseWE struct { + MfaToken string `json:"token"` + MfaMethod string `json:"mfa_method"` + GrantType string `json:"grant_type"` +} + type TokenFE struct { ClientID string `json:"client_id"` AccountID string `json:"account"` @@ -33,6 +57,14 @@ type AuthorizationCodeRequest struct { ClientSecret string `json:"client_secret"` } +type PasswordRequest struct { + GrantType string `json:"grant_type"` + Username string `json:"username"` + Password string `json:"password"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` +} + type RefreshTokenRequest struct { GrantType string `json:"grant_type"` ClientID string `json:"client_id"` diff --git a/models/web_experimentation/account.go b/models/web_experimentation/account.go new file mode 100644 index 0000000..897b438 --- /dev/null +++ b/models/web_experimentation/account.go @@ -0,0 +1,8 @@ +package web_experimentation + +type AccountWE struct { + Id string `json:"id,omitempty"` + Name string `json:"name"` + Identifier bool `json:"identifier"` + Role bool `json:"role"` +} diff --git a/models/web_experimentation/account_environment.go b/models/web_experimentation/account_environment.go new file mode 100644 index 0000000..890cc33 --- /dev/null +++ b/models/web_experimentation/account_environment.go @@ -0,0 +1,9 @@ +package web_experimentation + +type AccountEnvironmentWE struct { + Id string `json:"id,omitempty"` + Environment string `json:"environment"` + IsMain bool `json:"is_main"` + Panic bool `json:"panic"` + SingleAssignment bool `json:"single_assignment"` +} diff --git a/models/web_experimentation/campaign-test.go b/models/web_experimentation/campaign.go similarity index 96% rename from models/web_experimentation/campaign-test.go rename to models/web_experimentation/campaign.go index a3e4d38..2aaaaf0 100644 --- a/models/web_experimentation/campaign-test.go +++ b/models/web_experimentation/campaign.go @@ -1,4 +1,4 @@ -package models +package web_experimentation type Test struct { Id int `json:"id,omitempty"` diff --git a/models/web_experimentation/global-code.go b/models/web_experimentation/global-code.go index 9fcb46b..bc4236d 100644 --- a/models/web_experimentation/global-code.go +++ b/models/web_experimentation/global-code.go @@ -1,4 +1,4 @@ -package models +package web_experimentation type GlobalCode struct { Id int `json:"id,omitempty"` diff --git a/models/web_experimentation/vatiation-test.go b/models/web_experimentation/vatiation-test.go index 6436dbf..691ce99 100644 --- a/models/web_experimentation/vatiation-test.go +++ b/models/web_experimentation/vatiation-test.go @@ -1,4 +1,4 @@ -package models +package web_experimentation type TestVariation struct { Id int `json:"id,omitempty"` diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 7eed674..a40af92 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -21,7 +21,7 @@ var UserAgent string var c = http.Client{Timeout: time.Duration(10) * time.Second} var counter = false -type PageResult struct { +type PageResultFE struct { Items json.RawMessage `json:"items"` TotalCount int `json:"total_count"` } @@ -38,10 +38,10 @@ func (c *ResourceRequest) Init(cL *RequestConfig) { type PageResultWE struct { Data json.RawMessage `json:"_data"` - Pagination Pagination `json:"_pagination"` + Pagination PaginationWE `json:"_pagination"` } -type Pagination struct { +type PaginationWE struct { Total int `json:"_total"` Pages int `json:"_pages"` Page int `json:"_page"` @@ -128,10 +128,6 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) req.Header.Add("Content-Type", "application/json") req.Header.Set("User-Agent", UserAgent) - if body != nil { - req.Header.Add("Content-Type", `application/json`) - } - resp, err := c.Do(req) if err != nil { return nil, err @@ -172,7 +168,7 @@ func HTTPGetItem[T any](resource string) (T, error) { return result, err } -func HTTPGetAllPages[T any](resource string) ([]T, error) { +func HTTPGetAllPagesFE[T any](resource string) ([]T, error) { currentPage := 1 results := []T{} for { @@ -180,7 +176,7 @@ func HTTPGetAllPages[T any](resource string) ([]T, error) { if err != nil { return nil, err } - pageResult := &PageResult{} + pageResult := &PageResultFE{} err = json.Unmarshal(respBody, pageResult) if err != nil { return nil, err @@ -201,7 +197,7 @@ func HTTPGetAllPages[T any](resource string) ([]T, error) { return results, nil } -func HTTPGetAllPagesWe[T any](resource string) ([]T, error) { +func HTTPGetAllPagesWE[T any](resource string) ([]T, error) { currentPage := 1 results := []T{} for { diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 51daa1c..61d01c2 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -2,6 +2,7 @@ package common import ( "encoding/json" + "fmt" "net/http" "github.com/flagship-io/flagship/models" @@ -59,7 +60,7 @@ func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenRe return authenticationResponse, err } -func HTTPCreateTokenWE(client_id, client_secret, code string) (models.TokenResponse, error) { +func HTTPCreateTokenWEAuthorizationCode(client_id, client_secret, code string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.AuthorizationCodeRequest{ ClientID: client_id, @@ -85,6 +86,85 @@ func HTTPCreateTokenWE(client_id, client_secret, code string) (models.TokenRespo return authenticationResponse, err } +func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfaCode string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + var mfaResponse models.MfaRequestWE + var mfmResponse models.MfaRequestWE + + authRequest := models.PasswordRequest{ + ClientID: client_id, + ClientSecret: client_secret, + GrantType: "password", + Username: username, + Password: password, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + mfaRespBody, err := HTTPRequest[models.MfaRequestWE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(mfaRespBody, &mfaResponse) + if err != nil { + return models.TokenResponse{}, err + } + + fmt.Println(string(mfaRespBody)) + + mfmRequest := models.MultiFactorMethodRequestWE{ + GrantType: "multi_factor_methods", + MfaToken: mfaResponse.MfaToken, + MfaMethod: "totp", + } + + mfmRequestJSON, err := json.Marshal(mfmRequest) + if err != nil { + return models.TokenResponse{}, err + } + + mfmRespBody, err := HTTPRequest[models.MfaRequestWE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", mfmRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(mfmRespBody, &mfmResponse) + if err != nil { + return models.TokenResponse{}, err + } + + fmt.Println(string(mfmRespBody)) + + mfRequest := models.MultiFactorRequestWE{ + GrantType: "multi_factor", + MfaToken: mfmResponse.MfaToken, + MfaMethod: "totp", + Code: mfaCode, + } + + mfRequestJSON, err := json.Marshal(mfRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest[models.MfaRequestWE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", mfRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + fmt.Println(authenticationResponse) + + return authenticationResponse, err +} + func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.RefreshTokenRequest{ diff --git a/utils/http_request/feature_experimentation/account_environment.go b/utils/http_request/feature_experimentation/account_environment.go index 65a1cb9..0ac0348 100644 --- a/utils/http_request/feature_experimentation/account_environment.go +++ b/utils/http_request/feature_experimentation/account_environment.go @@ -6,14 +6,14 @@ import ( "github.com/flagship-io/flagship/utils/http_request/common" ) -type AccountEnvironmentRequester struct { +type AccountEnvironmentFERequester struct { *common.ResourceRequest } -func (a *AccountEnvironmentRequester) HTTPListAccountEnvironment() ([]models.AccountEnvironment, error) { - return common.HTTPGetAllPages[models.AccountEnvironment](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments") +func (a *AccountEnvironmentFERequester) HTTPListAccountEnvironment() ([]models.AccountEnvironmentFE, error) { + return common.HTTPGetAllPagesFE[models.AccountEnvironmentFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments") } -func (a *AccountEnvironmentRequester) HTTPGetAccountEnvironment(id string) (models.AccountEnvironment, error) { - return common.HTTPGetItem[models.AccountEnvironment](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments/" + id) +func (a *AccountEnvironmentFERequester) HTTPGetAccountEnvironment(id string) (models.AccountEnvironmentFE, error) { + return common.HTTPGetItem[models.AccountEnvironmentFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments/" + id) } diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index b903f13..eed228b 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -14,7 +14,7 @@ type CampaignRequester struct { } func (c *CampaignRequester) HTTPListCampaign() ([]models.Campaign, error) { - return common.HTTPGetAllPages[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") + return common.HTTPGetAllPagesFE[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") } func (c *CampaignRequester) HTTPGetCampaign(id string) (models.Campaign, error) { diff --git a/utils/http_request/feature_experimentation/flag.go b/utils/http_request/feature_experimentation/flag.go index 5411ffc..e42e979 100644 --- a/utils/http_request/feature_experimentation/flag.go +++ b/utils/http_request/feature_experimentation/flag.go @@ -13,7 +13,7 @@ type FlagRequester struct { } func (f *FlagRequester) HTTPListFlag() ([]models.Flag, error) { - return common.HTTPGetAllPages[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + f.AccountID + "/flags") + return common.HTTPGetAllPagesFE[models.Flag](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + f.AccountID + "/flags") } func (f *FlagRequester) HTTPGetFlag(id string) (models.Flag, error) { diff --git a/utils/http_request/feature_experimentation/goal.go b/utils/http_request/feature_experimentation/goal.go index 8281126..6e301ec 100644 --- a/utils/http_request/feature_experimentation/goal.go +++ b/utils/http_request/feature_experimentation/goal.go @@ -13,7 +13,7 @@ type GoalRequester struct { } func (g *GoalRequester) HTTPListGoal() ([]models.Goal, error) { - return common.HTTPGetAllPages[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvironmentID + "/goals") + return common.HTTPGetAllPagesFE[models.Goal](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/account_environments/" + g.AccountEnvironmentID + "/goals") } func (g *GoalRequester) HTTPGetGoal(id string) (models.Goal, error) { diff --git a/utils/http_request/feature_experimentation/project.go b/utils/http_request/feature_experimentation/project.go index 2a027e6..594683e 100644 --- a/utils/http_request/feature_experimentation/project.go +++ b/utils/http_request/feature_experimentation/project.go @@ -14,7 +14,7 @@ type ProjectRequester struct { } func (p *ProjectRequester) HTTPListProject() ([]models.Project, error) { - return common.HTTPGetAllPages[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + p.AccountID + "/projects") + return common.HTTPGetAllPagesFE[models.Project](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + p.AccountID + "/projects") } func (p *ProjectRequester) HTTPGetProject(id string) (models.Project, error) { diff --git a/utils/http_request/feature_experimentation/targeting_key.go b/utils/http_request/feature_experimentation/targeting_key.go index 5b0f571..c105f48 100644 --- a/utils/http_request/feature_experimentation/targeting_key.go +++ b/utils/http_request/feature_experimentation/targeting_key.go @@ -13,7 +13,7 @@ type TargetingKeyRequester struct { } func (t *TargetingKeyRequester) HTTPListTargetingKey() ([]models.TargetingKey, error) { - return common.HTTPGetAllPages[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + t.AccountID + "/targeting_keys") + return common.HTTPGetAllPagesFE[models.TargetingKey](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + t.AccountID + "/targeting_keys") } func (t *TargetingKeyRequester) HTTPGetTargetingKey(id string) (models.TargetingKey, error) { diff --git a/utils/http_request/feature_experimentation/user.go b/utils/http_request/feature_experimentation/user.go index d47a581..bbe919b 100644 --- a/utils/http_request/feature_experimentation/user.go +++ b/utils/http_request/feature_experimentation/user.go @@ -14,7 +14,7 @@ type UserRequester struct { } func (u *UserRequester) HTTPListUsers() ([]models.User, error) { - return common.HTTPGetAllPages[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + u.AccountID + "/account_environments/" + u.AccountEnvironmentID + "/users") + return common.HTTPGetAllPagesFE[models.User](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + u.AccountID + "/account_environments/" + u.AccountEnvironmentID + "/users") } func (u *UserRequester) HTTPBatchUpdateUsers(data string) ([]byte, error) { diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index 8a6ce0f..dd3bc85 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -13,7 +13,7 @@ type VariationRequester struct { } func (v *VariationRequester) HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return common.HTTPGetAllPages[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") + return common.HTTPGetAllPagesFE[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") } func (v *VariationRequester) HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { diff --git a/utils/http_request/feature_experimentation/variation_group.go b/utils/http_request/feature_experimentation/variation_group.go index fa4c3e7..067dd98 100644 --- a/utils/http_request/feature_experimentation/variation_group.go +++ b/utils/http_request/feature_experimentation/variation_group.go @@ -13,7 +13,7 @@ type VariationGroupRequester struct { } func (vg *VariationGroupRequester) HTTPListVariationGroup(campaignID string) ([]models.VariationGroup, error) { - return common.HTTPGetAllPages[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups") + return common.HTTPGetAllPagesFE[models.VariationGroup](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + vg.AccountID + "/account_environments/" + vg.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups") } func (vg *VariationGroupRequester) HTTPGetVariationGroup(campaignID, id string) (models.VariationGroup, error) { diff --git a/utils/http_request/main.go b/utils/http_request/main.go index fc522f7..6504f31 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -3,6 +3,7 @@ package http_request import ( "github.com/flagship-io/flagship/utils/http_request/common" "github.com/flagship-io/flagship/utils/http_request/feature_experimentation" + "github.com/flagship-io/flagship/utils/http_request/web_experimentation" ) type HTTPResource interface { @@ -13,8 +14,9 @@ var ResourceRequester common.ResourceRequest var HTTPResources = []HTTPResource{&ResourceRequester} +// feature experimentation var CampaignRequester feature_experimentation.CampaignRequester = feature_experimentation.CampaignRequester{ResourceRequest: &ResourceRequester} -var AccountEnvironmentRequester feature_experimentation.AccountEnvironmentRequester = feature_experimentation.AccountEnvironmentRequester{ResourceRequest: &ResourceRequester} +var AccountEnvironmentFERequester feature_experimentation.AccountEnvironmentFERequester = feature_experimentation.AccountEnvironmentFERequester{ResourceRequest: &ResourceRequester} var FlagRequester feature_experimentation.FlagRequester = feature_experimentation.FlagRequester{ResourceRequest: &ResourceRequester} var GoalRequester feature_experimentation.GoalRequester = feature_experimentation.GoalRequester{ResourceRequest: &ResourceRequester} var ProjectRequester feature_experimentation.ProjectRequester = feature_experimentation.ProjectRequester{ResourceRequest: &ResourceRequester} @@ -23,3 +25,8 @@ var TargetingKeyRequester feature_experimentation.TargetingKeyRequester = featur var VariationGroupRequester feature_experimentation.VariationGroupRequester = feature_experimentation.VariationGroupRequester{ResourceRequest: &ResourceRequester} var VariationRequester feature_experimentation.VariationRequester = feature_experimentation.VariationRequester{ResourceRequest: &ResourceRequester} var PanicRequester feature_experimentation.PanicRequester = feature_experimentation.PanicRequester{ResourceRequest: &ResourceRequester} + +// web experimentation + +var TestRequester web_experimentation.TestRequester = web_experimentation.TestRequester{ResourceRequest: &ResourceRequester} +var GlobalCodeRequester web_experimentation.GlobalRequester = web_experimentation.GlobalRequester{ResourceRequest: &ResourceRequester} diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index 42ef979..bebaaeb 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -6,23 +6,26 @@ import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" - "github.com/spf13/viper" ) -func HTTPListTest() ([]models.Test, error) { - return common.HTTPGetAllPagesWe[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests") +type TestRequester struct { + *common.ResourceRequest } -func HTTPGetTest(id string) (models.Test, error) { - return common.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + id) +func (t *TestRequester) HTTPListTest() ([]models.Test, error) { + return common.HTTPGetAllPagesWE[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests") } -func HTTPCreateTest(data string) ([]byte, error) { - return common.HTTPRequest[models.Test](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests", []byte(data)) +func (t *TestRequester) HTTPGetTest(id string) (models.Test, error) { + return common.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) } -func HTTPEditTest(id, data string) ([]byte, error) { - return common.HTTPRequest[models.Test](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, []byte(data)) +func (t *TestRequester) HTTPCreateTest(data string) ([]byte, error) { + return common.HTTPRequest[models.Test](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests", []byte(data)) +} + +func (t *TestRequester) HTTPEditTest(id, data string) ([]byte, error) { + return common.HTTPRequest[models.Test](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, []byte(data)) } /* func HTTPSwitchCampaign(id, state string) error { @@ -39,7 +42,7 @@ func HTTPEditTest(id, data string) ([]byte, error) { return err } */ -func HTTPDeleteTest(id string) error { - _, err := common.HTTPRequest[models.Test](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/tests/"+id, nil) +func (t *TestRequester) HTTPDeleteTest(id string) error { + _, err := common.HTTPRequest[models.Test](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) return err } diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go index e22db1e..fa6d1f6 100644 --- a/utils/http_request/web_experimentation/global_code.go +++ b/utils/http_request/web_experimentation/global_code.go @@ -4,13 +4,16 @@ import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" - "github.com/spf13/viper" ) -func HTTPListGlobalCode() ([]models.GlobalCode, error) { - return common.HTTPGetAllPagesWe[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes") +type GlobalRequester struct { + *common.ResourceRequest } -func HTTPGetGlobalCode(id string) (models.GlobalCode, error) { - return common.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/global-codes/" + id) +func (g *GlobalRequester) HTTPListGlobalCode() ([]models.GlobalCode, error) { + return common.HTTPGetAllPagesWE[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes") +} + +func (g *GlobalRequester) HTTPGetGlobalCode(id string) (models.GlobalCode, error) { + return common.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes/" + id) } From 67cf5dd60f402be92ee3fd486b6d90ae656bcd85 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 3 Apr 2024 08:39:41 +0000 Subject: [PATCH 10/48] add requester for we sub command and rename campaign and variation --- .../campaign/campaign_test.go | 4 ++-- cmd/feature_experimentation/resource/load.go | 2 +- .../variation/create.go | 2 +- .../variation/delete.go | 2 +- cmd/feature_experimentation/variation/edit.go | 2 +- cmd/feature_experimentation/variation/get.go | 2 +- cmd/feature_experimentation/variation/list.go | 2 +- .../variation/variation_test.go | 4 ++-- cmd/web_experimentation/account/account.go | 5 ++--- cmd/web_experimentation/account/current.go | 3 +-- cmd/web_experimentation/account/list.go | 4 ++-- cmd/web_experimentation/account/use.go | 8 ++----- cmd/web_experimentation/campaign/campaign.go | 6 ++--- cmd/web_experimentation/variation/get.go | 4 ++-- .../web_experimentation.go | 2 ++ models/feature_experimentation/campaign.go | 4 ++-- models/feature_experimentation/variation.go | 2 +- .../variation_group.go | 8 +++---- models/web_experimentation/account.go | 6 ++--- .../account_environment.go | 9 -------- models/web_experimentation/campaign.go | 20 ++++++++--------- .../{vatiation-test.go => vatiation.go} | 2 +- .../feature_experimentation/campaign.go | 18 +++++++-------- .../feature_experimentation/variation.go | 22 +++++++++---------- .../feature_experimentation/variation_test.go | 2 +- utils/http_request/main.go | 6 +++-- .../web_experimentation/account.go | 15 +++++++++++++ .../web_experimentation/campaign.go | 14 ++++++------ .../web_experimentation/global_code.go | 6 ++--- .../web_experimentation/variation.go | 8 +++++-- .../feature_experimentation/campaign.go | 12 +++++----- .../feature_experimentation/variation.go | 10 ++++----- .../variation_group.go | 2 +- 33 files changed, 113 insertions(+), 105 deletions(-) delete mode 100644 models/web_experimentation/account_environment.go rename models/web_experimentation/{vatiation-test.go => vatiation.go} (96%) create mode 100644 utils/http_request/web_experimentation/account.go diff --git a/cmd/feature_experimentation/campaign/campaign_test.go b/cmd/feature_experimentation/campaign/campaign_test.go index b712dc1..57c2b51 100644 --- a/cmd/feature_experimentation/campaign/campaign_test.go +++ b/cmd/feature_experimentation/campaign/campaign_test.go @@ -25,8 +25,8 @@ func TestMain(m *testing.M) { m.Run() } -var testCampaign models.Campaign -var testCampaignList []models.Campaign +var testCampaign models.CampaignFE +var testCampaignList []models.CampaignFE func TestCampaignCommand(t *testing.T) { output, _ := utils.ExecuteCommand(CampaignCmd) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 4843826..bf06a23 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -106,7 +106,7 @@ type VariationGroupData struct { } type VariationData struct { - *models.Variation + *models.VariationFE } type ResourceType int diff --git a/cmd/feature_experimentation/variation/create.go b/cmd/feature_experimentation/variation/create.go index 5fb0d74..580ebca 100644 --- a/cmd/feature_experimentation/variation/create.go +++ b/cmd/feature_experimentation/variation/create.go @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a variation", Long: `Create a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.VariationRequester.HTTPCreateVariation(CampaignID, VariationGroupID, DataRaw) + body, err := httprequest.VariationFERequester.HTTPCreateVariation(CampaignID, VariationGroupID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index a2ab04f..0ca2b5c 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a variation", Long: `Delete a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.VariationRequester.HTTPDeleteVariation(CampaignID, VariationGroupID, VariationID) + err := httprequest.VariationFERequester.HTTPDeleteVariation(CampaignID, VariationGroupID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/edit.go b/cmd/feature_experimentation/variation/edit.go index dd0df0f..81d01b9 100644 --- a/cmd/feature_experimentation/variation/edit.go +++ b/cmd/feature_experimentation/variation/edit.go @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a variation", Long: `Edit a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.VariationRequester.HTTPEditVariation(CampaignID, VariationGroupID, VariationID, DataRaw) + body, err := httprequest.VariationFERequester.HTTPEditVariation(CampaignID, VariationGroupID, VariationID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/get.go b/cmd/feature_experimentation/variation/get.go index 392a87c..ba9ebe1 100644 --- a/cmd/feature_experimentation/variation/get.go +++ b/cmd/feature_experimentation/variation/get.go @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a variation", Long: `Get a variation in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.VariationRequester.HTTPGetVariation(CampaignID, VariationGroupID, VariationID) + body, err := httprequest.VariationFERequester.HTTPGetVariation(CampaignID, VariationGroupID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/list.go b/cmd/feature_experimentation/variation/list.go index 3e0d58d..bd25fa3 100644 --- a/cmd/feature_experimentation/variation/list.go +++ b/cmd/feature_experimentation/variation/list.go @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all variations", Long: `List all variations in your variation group`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.VariationRequester.HTTPListVariation(CampaignID, VariationGroupID) + body, err := httprequest.VariationFERequester.HTTPListVariation(CampaignID, VariationGroupID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go index 19d436b..61d75a2 100644 --- a/cmd/feature_experimentation/variation/variation_test.go +++ b/cmd/feature_experimentation/variation/variation_test.go @@ -25,8 +25,8 @@ func TestMain(m *testing.M) { m.Run() } -var testVariation models.Variation -var testVariationList []models.Variation +var testVariation models.VariationFE +var testVariationList []models.VariationFE func TestVariationCommand(t *testing.T) { output, _ := utils.ExecuteCommand(VariationCmd) diff --git a/cmd/web_experimentation/account/account.go b/cmd/web_experimentation/account/account.go index d8ba6a4..bbb73e4 100644 --- a/cmd/web_experimentation/account/account.go +++ b/cmd/web_experimentation/account/account.go @@ -6,9 +6,8 @@ package account import "github.com/spf13/cobra" var ( - Username string - AccountID string - AccountEnvironmentID string + Username string + AccountID string ) // ConfigurationCmd represents the configuration command diff --git a/cmd/web_experimentation/account/current.go b/cmd/web_experimentation/account/current.go index e1e0015..12318fb 100644 --- a/cmd/web_experimentation/account/current.go +++ b/cmd/web_experimentation/account/current.go @@ -38,9 +38,8 @@ var currentCmd = &cobra.Command{ configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential configuration.AccountID = configurationYaml.AccountID - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID - utils.FormatItem([]string{"CurrentUsedCredential", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/account/list.go b/cmd/web_experimentation/account/list.go index 847a873..66d7ae0 100644 --- a/cmd/web_experimentation/account/list.go +++ b/cmd/web_experimentation/account/list.go @@ -19,11 +19,11 @@ var listCmd = &cobra.Command{ Long: `list all auth from your system`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() + body, err := httprequest.AccountWERequester.HTTPListAccount() if err != nil { log.Fatalf("error occurred: %v", err) } - utils.FormatItem([]string{"Id", "Environment", "IsMain", "Panic", "SingleAssignment"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Id", "Name", "Identifier", "Role"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index 62b91b6..7fccc78 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -17,8 +17,8 @@ var useCmd = &cobra.Command{ Short: "get an auth credential", Long: `list an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - if AccountID == "" && AccountEnvironmentID == "" { - fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id or account-environment-id") + if AccountID == "" { + fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id") return } @@ -26,15 +26,11 @@ var useCmd = &cobra.Command{ config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) } - if AccountEnvironmentID != "" { - config.SetAccountEnvID(utils.WEB_EXPERIMENTATION, AccountEnvironmentID) - } }, } func init() { useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") - useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to display") AccountCmd.AddCommand(useCmd) } diff --git a/cmd/web_experimentation/campaign/campaign.go b/cmd/web_experimentation/campaign/campaign.go index e59988d..d88ea02 100644 --- a/cmd/web_experimentation/campaign/campaign.go +++ b/cmd/web_experimentation/campaign/campaign.go @@ -15,9 +15,9 @@ var ( // campaignCmd represents the campaign command var CampaignCmd = &cobra.Command{ - Use: "test [create|edit|get|list|delete|switch]", - Short: "Manage your tests", - Long: `Manage your tests`, + Use: "campaign [get|list|delete|switch]", + Short: "Manage your campaigns", + Long: `Manage your campaigns`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/variation/get.go b/cmd/web_experimentation/variation/get.go index 8b8e5fb..3bcf5b0 100644 --- a/cmd/web_experimentation/variation/get.go +++ b/cmd/web_experimentation/variation/get.go @@ -8,7 +8,7 @@ import ( "fmt" "log" - httprequest "github.com/flagship-io/flagship/utils/http_request/web_experimentation" + httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" ) @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a variation", Long: `Get a variation in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.HTTPGetVariation(TestID, VariationID) + body, err := httprequest.VariationWERequester.HTTPGetVariation(TestID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index b62217e..724efd7 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -6,6 +6,7 @@ package web_experimentation import ( "os" + "github.com/flagship-io/flagship/cmd/web_experimentation/account" "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" "github.com/flagship-io/flagship/cmd/web_experimentation/global_code" @@ -35,6 +36,7 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(global_code.GlobalCodeCmd) WebExperimentationCmd.AddCommand(variation.VariationCmd) WebExperimentationCmd.AddCommand(auth.AuthCmd) + WebExperimentationCmd.AddCommand(account.AccountCmd) } func init() { diff --git a/models/feature_experimentation/campaign.go b/models/feature_experimentation/campaign.go index 6edbe73..3b1e197 100644 --- a/models/feature_experimentation/campaign.go +++ b/models/feature_experimentation/campaign.go @@ -1,6 +1,6 @@ package feature_experimentation -type Campaign struct { +type CampaignFE struct { Id string `json:"id,omitempty"` ProjectId string `json:"project_id"` Name string `json:"name"` @@ -17,6 +17,6 @@ type Scheduler struct { TimeZone string `json:"timezone"` } -type CampaignSwitchRequest struct { +type CampaignFESwitchRequest struct { State string `json:"state"` } diff --git a/models/feature_experimentation/variation.go b/models/feature_experimentation/variation.go index e159c57..21bf137 100644 --- a/models/feature_experimentation/variation.go +++ b/models/feature_experimentation/variation.go @@ -1,6 +1,6 @@ package feature_experimentation -type Variation struct { +type VariationFE struct { Id string `json:"id,omitempty"` Name string `json:"name"` Reference bool `json:"reference"` diff --git a/models/feature_experimentation/variation_group.go b/models/feature_experimentation/variation_group.go index 0ad331d..28ebb94 100644 --- a/models/feature_experimentation/variation_group.go +++ b/models/feature_experimentation/variation_group.go @@ -1,10 +1,10 @@ package feature_experimentation type VariationGroup struct { - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Variations *[]Variation `json:"variations"` - Targeting Targeting `json:"targeting"` + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Variations *[]VariationFE `json:"variations"` + Targeting Targeting `json:"targeting"` } type Targeting struct { diff --git a/models/web_experimentation/account.go b/models/web_experimentation/account.go index 897b438..03d5b84 100644 --- a/models/web_experimentation/account.go +++ b/models/web_experimentation/account.go @@ -1,8 +1,8 @@ package web_experimentation type AccountWE struct { - Id string `json:"id,omitempty"` + Id int `json:"id,omitempty"` Name string `json:"name"` - Identifier bool `json:"identifier"` - Role bool `json:"role"` + Identifier string `json:"identifier"` + Role string `json:"role"` } diff --git a/models/web_experimentation/account_environment.go b/models/web_experimentation/account_environment.go deleted file mode 100644 index 890cc33..0000000 --- a/models/web_experimentation/account_environment.go +++ /dev/null @@ -1,9 +0,0 @@ -package web_experimentation - -type AccountEnvironmentWE struct { - Id string `json:"id,omitempty"` - Environment string `json:"environment"` - IsMain bool `json:"is_main"` - Panic bool `json:"panic"` - SingleAssignment bool `json:"single_assignment"` -} diff --git a/models/web_experimentation/campaign.go b/models/web_experimentation/campaign.go index 2aaaaf0..01a5edf 100644 --- a/models/web_experimentation/campaign.go +++ b/models/web_experimentation/campaign.go @@ -1,15 +1,15 @@ package web_experimentation -type Test struct { - Id int `json:"id,omitempty"` - Name string `json:"name"` - Url string `json:"url"` - Description string `json:"description"` - Type string `json:"type"` - SubType string `json:"sub_type"` - State string `json:"state"` - Traffic *Traffic `json:"traffic"` - Variations *[]TestVariation `json:"variations"` +type CampaignWE struct { + Id int `json:"id,omitempty"` + Name string `json:"name"` + Url string `json:"url"` + Description string `json:"description"` + Type string `json:"type"` + SubType string `json:"sub_type"` + State string `json:"state"` + Traffic *Traffic `json:"traffic"` + Variations *[]VariationWE `json:"variations"` } type Traffic struct { diff --git a/models/web_experimentation/vatiation-test.go b/models/web_experimentation/vatiation.go similarity index 96% rename from models/web_experimentation/vatiation-test.go rename to models/web_experimentation/vatiation.go index 691ce99..072bea1 100644 --- a/models/web_experimentation/vatiation-test.go +++ b/models/web_experimentation/vatiation.go @@ -1,6 +1,6 @@ package web_experimentation -type TestVariation struct { +type VariationWE struct { Id int `json:"id,omitempty"` Name string `json:"name"` Description string `json:"description"` diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index eed228b..5495058 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -13,24 +13,24 @@ type CampaignRequester struct { *common.ResourceRequest } -func (c *CampaignRequester) HTTPListCampaign() ([]models.Campaign, error) { - return common.HTTPGetAllPagesFE[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") +func (c *CampaignRequester) HTTPListCampaign() ([]models.CampaignFE, error) { + return common.HTTPGetAllPagesFE[models.CampaignFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") } -func (c *CampaignRequester) HTTPGetCampaign(id string) (models.Campaign, error) { - return common.HTTPGetItem[models.Campaign](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns/" + id) +func (c *CampaignRequester) HTTPGetCampaign(id string) (models.CampaignFE, error) { + return common.HTTPGetItem[models.CampaignFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns/" + id) } func (c *CampaignRequester) HTTPCreateCampaign(data string) ([]byte, error) { - return common.HTTPRequest[models.Campaign](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns", []byte(data)) + return common.HTTPRequest[models.CampaignFE](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns", []byte(data)) } func (c *CampaignRequester) HTTPEditCampaign(id, data string) ([]byte, error) { - return common.HTTPRequest[models.Campaign](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, []byte(data)) + return common.HTTPRequest[models.CampaignFE](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, []byte(data)) } func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { - campaignSwitchRequest := models.CampaignSwitchRequest{ + campaignSwitchRequest := models.CampaignFESwitchRequest{ State: state, } @@ -39,11 +39,11 @@ func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { return err } - _, err = common.HTTPRequest[models.Campaign](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) + _, err = common.HTTPRequest[models.CampaignFE](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) return err } func (c *CampaignRequester) HTTPDeleteCampaign(id string) error { - _, err := common.HTTPRequest[models.Campaign](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, nil) + _, err := common.HTTPRequest[models.CampaignFE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation.go b/utils/http_request/feature_experimentation/variation.go index dd3bc85..b3b1869 100644 --- a/utils/http_request/feature_experimentation/variation.go +++ b/utils/http_request/feature_experimentation/variation.go @@ -8,27 +8,27 @@ import ( "github.com/flagship-io/flagship/utils/http_request/common" ) -type VariationRequester struct { +type VariationFERequester struct { *common.ResourceRequest } -func (v *VariationRequester) HTTPListVariation(campaignID, variationGroupID string) ([]models.Variation, error) { - return common.HTTPGetAllPagesFE[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") +func (v *VariationFERequester) HTTPListVariation(campaignID, variationGroupID string) ([]models.VariationFE, error) { + return common.HTTPGetAllPagesFE[models.VariationFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations") } -func (v *VariationRequester) HTTPGetVariation(campaignID, variationGroupID, id string) (models.Variation, error) { - return common.HTTPGetItem[models.Variation](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) +func (v *VariationFERequester) HTTPGetVariation(campaignID, variationGroupID, id string) (models.VariationFE, error) { + return common.HTTPGetItem[models.VariationFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + v.AccountID + "/account_environments/" + v.AccountEnvironmentID + "/campaigns/" + campaignID + "/variation_groups/" + variationGroupID + "/variations/" + id) } -func (v *VariationRequester) HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { - return common.HTTPRequest[models.Variation](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) +func (v *VariationFERequester) HTTPCreateVariation(campaignID, variationGroupID, data string) ([]byte, error) { + return common.HTTPRequest[models.VariationFE](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations", []byte(data)) } -func (v *VariationRequester) HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { - return common.HTTPRequest[models.Variation](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) +func (v *VariationFERequester) HTTPEditVariation(campaignID, variationGroupID, id, data string) ([]byte, error) { + return common.HTTPRequest[models.VariationFE](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, []byte(data)) } -func (v *VariationRequester) HTTPDeleteVariation(campaignID, variationGroupID, id string) error { - _, err := common.HTTPRequest[models.Variation](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) +func (v *VariationFERequester) HTTPDeleteVariation(campaignID, variationGroupID, id string) error { + _, err := common.HTTPRequest[models.VariationFE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+v.AccountID+"/account_environments/"+v.AccountEnvironmentID+"/campaigns/"+campaignID+"/variation_groups/"+variationGroupID+"/variations/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/variation_test.go b/utils/http_request/feature_experimentation/variation_test.go index 66b0464..83a4224 100644 --- a/utils/http_request/feature_experimentation/variation_test.go +++ b/utils/http_request/feature_experimentation/variation_test.go @@ -8,7 +8,7 @@ import ( ) var variationGroupID = "variationGroupID" -var variationRequester = VariationRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} +var variationRequester = VariationFERequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetVariation(t *testing.T) { diff --git a/utils/http_request/main.go b/utils/http_request/main.go index 6504f31..5737dc6 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -23,10 +23,12 @@ var ProjectRequester feature_experimentation.ProjectRequester = feature_experime var UserRequester feature_experimentation.UserRequester = feature_experimentation.UserRequester{ResourceRequest: &ResourceRequester} var TargetingKeyRequester feature_experimentation.TargetingKeyRequester = feature_experimentation.TargetingKeyRequester{ResourceRequest: &ResourceRequester} var VariationGroupRequester feature_experimentation.VariationGroupRequester = feature_experimentation.VariationGroupRequester{ResourceRequest: &ResourceRequester} -var VariationRequester feature_experimentation.VariationRequester = feature_experimentation.VariationRequester{ResourceRequest: &ResourceRequester} +var VariationFERequester feature_experimentation.VariationFERequester = feature_experimentation.VariationFERequester{ResourceRequest: &ResourceRequester} var PanicRequester feature_experimentation.PanicRequester = feature_experimentation.PanicRequester{ResourceRequest: &ResourceRequester} // web experimentation var TestRequester web_experimentation.TestRequester = web_experimentation.TestRequester{ResourceRequest: &ResourceRequester} -var GlobalCodeRequester web_experimentation.GlobalRequester = web_experimentation.GlobalRequester{ResourceRequest: &ResourceRequester} +var GlobalCodeRequester web_experimentation.GlobalCodeRequester = web_experimentation.GlobalCodeRequester{ResourceRequest: &ResourceRequester} +var AccountWERequester web_experimentation.AccountWERequester = web_experimentation.AccountWERequester{ResourceRequest: &ResourceRequester} +var VariationWERequester web_experimentation.VariationWERequester = web_experimentation.VariationWERequester{ResourceRequest: &ResourceRequester} diff --git a/utils/http_request/web_experimentation/account.go b/utils/http_request/web_experimentation/account.go new file mode 100644 index 0000000..fa7666f --- /dev/null +++ b/utils/http_request/web_experimentation/account.go @@ -0,0 +1,15 @@ +package web_experimentation + +import ( + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request/common" +) + +type AccountWERequester struct { + *common.ResourceRequest +} + +func (a *AccountWERequester) HTTPListAccount() ([]models.AccountWE, error) { + return common.HTTPGetAllPagesWE[models.AccountWE](utils.GetWebExperimentationHost() + "/v1/accounts/") +} diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index bebaaeb..1ca9458 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -12,20 +12,20 @@ type TestRequester struct { *common.ResourceRequest } -func (t *TestRequester) HTTPListTest() ([]models.Test, error) { - return common.HTTPGetAllPagesWE[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests") +func (t *TestRequester) HTTPListTest() ([]models.CampaignWE, error) { + return common.HTTPGetAllPagesWE[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests") } -func (t *TestRequester) HTTPGetTest(id string) (models.Test, error) { - return common.HTTPGetItem[models.Test](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) +func (t *TestRequester) HTTPGetTest(id string) (models.CampaignWE, error) { + return common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) } func (t *TestRequester) HTTPCreateTest(data string) ([]byte, error) { - return common.HTTPRequest[models.Test](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests", []byte(data)) + return common.HTTPRequest[models.CampaignWE](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests", []byte(data)) } func (t *TestRequester) HTTPEditTest(id, data string) ([]byte, error) { - return common.HTTPRequest[models.Test](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, []byte(data)) + return common.HTTPRequest[models.CampaignWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, []byte(data)) } /* func HTTPSwitchCampaign(id, state string) error { @@ -43,6 +43,6 @@ func (t *TestRequester) HTTPEditTest(id, data string) ([]byte, error) { } */ func (t *TestRequester) HTTPDeleteTest(id string) error { - _, err := common.HTTPRequest[models.Test](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) + _, err := common.HTTPRequest[models.CampaignWE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) return err } diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go index fa6d1f6..b9ba852 100644 --- a/utils/http_request/web_experimentation/global_code.go +++ b/utils/http_request/web_experimentation/global_code.go @@ -6,14 +6,14 @@ import ( "github.com/flagship-io/flagship/utils/http_request/common" ) -type GlobalRequester struct { +type GlobalCodeRequester struct { *common.ResourceRequest } -func (g *GlobalRequester) HTTPListGlobalCode() ([]models.GlobalCode, error) { +func (g *GlobalCodeRequester) HTTPListGlobalCode() ([]models.GlobalCode, error) { return common.HTTPGetAllPagesWE[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes") } -func (g *GlobalRequester) HTTPGetGlobalCode(id string) (models.GlobalCode, error) { +func (g *GlobalCodeRequester) HTTPGetGlobalCode(id string) (models.GlobalCode, error) { return common.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes/" + id) } diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go index 15c173a..3521f54 100644 --- a/utils/http_request/web_experimentation/variation.go +++ b/utils/http_request/web_experimentation/variation.go @@ -9,6 +9,10 @@ import ( "github.com/spf13/viper" ) -func HTTPGetVariation(testID, id int) (models.TestVariation, error) { - return common.HTTPGetItem[models.TestVariation](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) +type VariationWERequester struct { + *common.ResourceRequest +} + +func (v *VariationWERequester) HTTPGetVariation(testID, id int) (models.VariationWE, error) { + return common.HTTPGetItem[models.VariationWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) } diff --git a/utils/mock_function/feature_experimentation/campaign.go b/utils/mock_function/feature_experimentation/campaign.go index d61b7a7..6722b38 100644 --- a/utils/mock_function/feature_experimentation/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -31,7 +31,7 @@ var targetingTest = models.Targeting{ TargetingGroups: targetingGroupsTest, } -var variationTest = []models.Variation{ +var variationTest = []models.VariationFE{ { Name: "My variation 1", Reference: true, @@ -60,7 +60,7 @@ var variationGroupsTest = []models.VariationGroup{ }, } -var TestCampaign = models.Campaign{ +var TestCampaign = models.CampaignFE{ Id: "testCampaignID", Name: "testCampaignName", ProjectId: "testProjectID", @@ -70,7 +70,7 @@ var TestCampaign = models.Campaign{ Scheduler: scheduler, } -var TestCampaign1 = models.Campaign{ +var TestCampaign1 = models.CampaignFE{ Id: "testCampaignID1", Name: "testCampaignName1", ProjectId: "testProjectID1", @@ -80,7 +80,7 @@ var TestCampaign1 = models.Campaign{ Scheduler: scheduler, } -var TestCampaignEdit = models.Campaign{ +var TestCampaignEdit = models.CampaignFE{ Id: "testCampaignID", Name: "testCampaignName1", ProjectId: "testProjectID1", @@ -90,14 +90,14 @@ var TestCampaignEdit = models.Campaign{ Scheduler: scheduler, } -var TestCampaignlist = []models.Campaign{ +var TestCampaignlist = []models.CampaignFE{ TestCampaign, TestCampaign1, } func APICampaign() { - resp := utils.HTTPListResponse[models.Campaign]{ + resp := utils.HTTPListResponse[models.CampaignFE]{ Items: TestCampaignlist, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/variation.go b/utils/mock_function/feature_experimentation/variation.go index 9672b68..69ca492 100644 --- a/utils/mock_function/feature_experimentation/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -9,7 +9,7 @@ import ( "github.com/jarcoal/httpmock" ) -var TestVariation = models.Variation{ +var TestVariation = models.VariationFE{ Id: "testVariationID", Name: "testVariationName", Reference: true, @@ -20,7 +20,7 @@ var TestVariation = models.Variation{ }, } -var TestVariation1 = models.Variation{ +var TestVariation1 = models.VariationFE{ Id: "testVariationID1", Name: "testVariationName1", Reference: false, @@ -31,7 +31,7 @@ var TestVariation1 = models.Variation{ }, } -var TestVariationEdit = models.Variation{ +var TestVariationEdit = models.VariationFE{ Id: "testVariationID", Name: "testVariationName1", Reference: false, @@ -42,7 +42,7 @@ var TestVariationEdit = models.Variation{ }, } -var TestVariationList = []models.Variation{ +var TestVariationList = []models.VariationFE{ TestVariation, TestVariation1, } @@ -52,7 +52,7 @@ func APIVariation() { campaignID := "campaignID" variationGroupID := "variationGroupID" - resp := utils.HTTPListResponse[models.Variation]{ + resp := utils.HTTPListResponse[models.VariationFE]{ Items: TestVariationList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go index 60f55fd..afec9d5 100644 --- a/utils/mock_function/feature_experimentation/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -21,7 +21,7 @@ var targetingGroups = []models.TargetingGroup{ }, } -var variations = []models.Variation{ +var variations = []models.VariationFE{ { Name: "My variation 1", Reference: true, From 9d95a4ba665459107bf64e1ea7a6cc4ac796251d Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 3 Apr 2024 12:51:02 +0000 Subject: [PATCH 11/48] fix refreshToken & renaming & add account-env command --- .../account/account.go | 5 +- .../account/current.go | 2 +- cmd/feature_experimentation/account/list.go | 2 +- cmd/feature_experimentation/account/use.go | 18 +++---- .../account_environment.go | 21 ++++++++ .../account_environment/current.go | 49 +++++++++++++++++++ .../account_environment/list.go | 32 ++++++++++++ .../account_environment/use.go | 38 ++++++++++++++ cmd/feature_experimentation/auth/login.go | 5 +- .../campaign/create.go | 2 +- .../campaign/delete.go | 2 +- cmd/feature_experimentation/campaign/edit.go | 2 +- cmd/feature_experimentation/campaign/get.go | 2 +- cmd/feature_experimentation/campaign/list.go | 2 +- .../campaign/switch.go | 2 +- .../feature_experimentation.go | 7 ++- cmd/feature_experimentation/resource/load.go | 4 +- cmd/web_experimentation/account/use.go | 10 ++-- cmd/web_experimentation/auth/login.go | 2 +- cmd/web_experimentation/campaign/get.go | 2 +- cmd/web_experimentation/campaign/list.go | 2 +- cmd/web_experimentation/variation/get.go | 1 - .../web_experimentation.go | 6 +-- models/token.go | 8 ++- utils/config/config.go | 1 + utils/config/default.go | 2 +- utils/http_request/common/request.go | 26 +++++----- utils/http_request/common/token.go | 39 +++++++++++---- .../feature_experimentation/campaign.go | 14 +++--- .../feature_experimentation/campaign_test.go | 2 +- utils/http_request/main.go | 4 +- .../web_experimentation/campaign.go | 12 ++--- 32 files changed, 249 insertions(+), 77 deletions(-) create mode 100644 cmd/feature_experimentation/account_environment/account_environment.go create mode 100644 cmd/feature_experimentation/account_environment/current.go create mode 100644 cmd/feature_experimentation/account_environment/list.go create mode 100644 cmd/feature_experimentation/account_environment/use.go diff --git a/cmd/feature_experimentation/account/account.go b/cmd/feature_experimentation/account/account.go index d8ba6a4..bbb73e4 100644 --- a/cmd/feature_experimentation/account/account.go +++ b/cmd/feature_experimentation/account/account.go @@ -6,9 +6,8 @@ package account import "github.com/spf13/cobra" var ( - Username string - AccountID string - AccountEnvironmentID string + Username string + AccountID string ) // ConfigurationCmd represents the configuration command diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index 150a139..523db45 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -40,7 +40,7 @@ var currentCmd = &cobra.Command{ configuration.AccountID = configurationYaml.AccountID configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID - utils.FormatItem([]string{"CurrentUsedCredential", "AccountID", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/account/list.go b/cmd/feature_experimentation/account/list.go index 847a873..5149552 100644 --- a/cmd/feature_experimentation/account/list.go +++ b/cmd/feature_experimentation/account/list.go @@ -29,5 +29,5 @@ var listCmd = &cobra.Command{ func init() { - AccountCmd.AddCommand(listCmd) + //AccountCmd.AddCommand(listCmd) } diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index a7577c5..3614ff0 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -5,6 +5,7 @@ package account import ( "fmt" + "log" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" @@ -17,24 +18,21 @@ var useCmd = &cobra.Command{ Short: "get an auth credential", Long: `list an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - if AccountID == "" && AccountEnvironmentID == "" { - fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id or account-environment-id") + if AccountID == "" { + fmt.Fprintln(cmd.OutOrStderr(), "required flag account-id") return } - if AccountID != "" { - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) - } + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) - if AccountEnvironmentID != "" { - config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) - } }, } func init() { - useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") - useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to display") + useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to manage") + if err := useCmd.MarkFlagRequired("account-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } AccountCmd.AddCommand(useCmd) } diff --git a/cmd/feature_experimentation/account_environment/account_environment.go b/cmd/feature_experimentation/account_environment/account_environment.go new file mode 100644 index 0000000..7a0aa75 --- /dev/null +++ b/cmd/feature_experimentation/account_environment/account_environment.go @@ -0,0 +1,21 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package accountenvironment + +import "github.com/spf13/cobra" + +var ( + Username string + AccountEnvironmentID string +) + +// ConfigurationCmd represents the configuration command +var AccountEnvironmentCmd = &cobra.Command{ + Use: "account-environment [use|list|current]", + Short: "Manage your CLI authentication", + Long: `Manage your CLI authentication`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/feature_experimentation/account_environment/current.go b/cmd/feature_experimentation/account_environment/current.go new file mode 100644 index 0000000..300f201 --- /dev/null +++ b/cmd/feature_experimentation/account_environment/current.go @@ -0,0 +1,49 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package accountenvironment + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// getCmd represents the list command +var currentCmd = &cobra.Command{ + Use: "current", + Short: "current an auth credential", + Long: `current an auth credential from your system`, + Run: func(cmd *cobra.Command, args []string) { + + var configurationYaml models.AccountYaml + var configuration models.AccountJSON + + yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &configurationYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential + configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID + + utils.FormatItem([]string{"CurrentUsedCredential", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + AccountEnvironmentCmd.AddCommand(currentCmd) +} diff --git a/cmd/feature_experimentation/account_environment/list.go b/cmd/feature_experimentation/account_environment/list.go new file mode 100644 index 0000000..c460f38 --- /dev/null +++ b/cmd/feature_experimentation/account_environment/list.go @@ -0,0 +1,32 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package accountenvironment + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list", + Short: "list all account environment id associated to your account", + Long: `list all account environment id associated to your account`, + Run: func(cmd *cobra.Command, args []string) { + + body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "Environment", "IsMain", "Panic", "SingleAssignment"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + AccountEnvironmentCmd.AddCommand(listCmd) +} diff --git a/cmd/feature_experimentation/account_environment/use.go b/cmd/feature_experimentation/account_environment/use.go new file mode 100644 index 0000000..0475cdf --- /dev/null +++ b/cmd/feature_experimentation/account_environment/use.go @@ -0,0 +1,38 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package accountenvironment + +import ( + "fmt" + "log" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" +) + +// getCmd represents the list command +var useCmd = &cobra.Command{ + Use: "use", + Short: "use a specific account envrionment id", + Long: `use a specific account envrionment id`, + Run: func(cmd *cobra.Command, args []string) { + if AccountEnvironmentID == "" { + fmt.Fprintln(cmd.OutOrStderr(), "required flag account-id or account-environment-id") + return + } + + config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) + + }, +} + +func init() { + useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to manage") + + if err := useCmd.MarkFlagRequired("account-environment-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + AccountEnvironmentCmd.AddCommand(useCmd) +} diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 4aaeaed..e57cb49 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -37,7 +37,7 @@ var loginCmd = &cobra.Command{ Long: `login`, Run: func(cmd *cobra.Command, args []string) { if !checkSingleFlag(credentialsFile != "", Username != "") { - log.Fatalf("error occurred: %s", "1 flag is required. (browser, username, credential-file, email)") + log.Fatalf("error occurred: %s", "1 flag is required. (username, credential-file)") } if credentialsFile != "" { @@ -66,7 +66,7 @@ var loginCmd = &cobra.Command{ return } - if ClientID == "" && ClientSecret == "" && AccountId == "" { + if ClientID == "" || ClientSecret == "" || AccountId == "" { fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") return } @@ -79,6 +79,7 @@ var loginCmd = &cobra.Command{ if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } + config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) diff --git a/cmd/feature_experimentation/campaign/create.go b/cmd/feature_experimentation/campaign/create.go index 05dc53a..9054376 100644 --- a/cmd/feature_experimentation/campaign/create.go +++ b/cmd/feature_experimentation/campaign/create.go @@ -17,7 +17,7 @@ var createCmd = &cobra.Command{ Short: "Create a campaign", Long: `Create a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignRequester.HTTPCreateCampaign(DataRaw) + body, err := httprequest.CampaignFERequester.HTTPCreateCampaign(DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go index 793d893..947705a 100644 --- a/cmd/feature_experimentation/campaign/delete.go +++ b/cmd/feature_experimentation/campaign/delete.go @@ -17,7 +17,7 @@ var deleteCmd = &cobra.Command{ Short: "Delete a campaign", Long: `Delete a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - err := httprequest.CampaignRequester.HTTPDeleteCampaign(CampaignID) + err := httprequest.CampaignFERequester.HTTPDeleteCampaign(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go index 3829fa2..b141cd1 100644 --- a/cmd/feature_experimentation/campaign/edit.go +++ b/cmd/feature_experimentation/campaign/edit.go @@ -17,7 +17,7 @@ var editCmd = &cobra.Command{ Short: "Edit a campaign", Long: `Edit a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignRequester.HTTPEditCampaign(CampaignID, DataRaw) + body, err := httprequest.CampaignFERequester.HTTPEditCampaign(CampaignID, DataRaw) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/get.go b/cmd/feature_experimentation/campaign/get.go index f644474..a146133 100644 --- a/cmd/feature_experimentation/campaign/get.go +++ b/cmd/feature_experimentation/campaign/get.go @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a campaign", Long: `Get a campaign in your project`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignRequester.HTTPGetCampaign(CampaignID) + body, err := httprequest.CampaignFERequester.HTTPGetCampaign(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/list.go b/cmd/feature_experimentation/campaign/list.go index 48533ff..d8a3060 100644 --- a/cmd/feature_experimentation/campaign/list.go +++ b/cmd/feature_experimentation/campaign/list.go @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all campaigns", Long: `List all campaigns`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignRequester.HTTPListCampaign() + body, err := httprequest.CampaignFERequester.HTTPListCampaign() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go index 5f428e2..5219fe2 100644 --- a/cmd/feature_experimentation/campaign/switch.go +++ b/cmd/feature_experimentation/campaign/switch.go @@ -20,7 +20,7 @@ var SwitchCmd = &cobra.Command{ if !(Status == "active" || Status == "paused" || Status == "interrupted") { fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 3 values: active or paused or interrupted") } else { - err := httprequest.CampaignRequester.HTTPSwitchCampaign(CampaignID, Status) + err := httprequest.CampaignFERequester.HTTPSwitchCampaign(CampaignID, Status) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 2ffc22a..b233e99 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -7,6 +7,7 @@ import ( "os" "github.com/flagship-io/flagship/cmd/feature_experimentation/account" + accountenvironment "github.com/flagship-io/flagship/cmd/feature_experimentation/account_environment" "github.com/flagship-io/flagship/cmd/feature_experimentation/analyze" "github.com/flagship-io/flagship/cmd/feature_experimentation/auth" "github.com/flagship-io/flagship/cmd/feature_experimentation/campaign" @@ -34,6 +35,9 @@ var FeatureExperimentationCmd = &cobra.Command{ Aliases: []string{"feature-experimentation", "feature-exp", "fe", "feat-exp"}, Short: "Manage resources related to the feature experimentation product", Long: `Manage resources related to the feature experimentation product in your account`, + PersistentPreRun: func(cmd *cobra.Command, args []string) { + initConfig() + }, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, @@ -53,10 +57,10 @@ func addSubCommandPalettes() { FeatureExperimentationCmd.AddCommand(resource.ResourceCmd) FeatureExperimentationCmd.AddCommand(auth.AuthCmd) FeatureExperimentationCmd.AddCommand(account.AccountCmd) + FeatureExperimentationCmd.AddCommand(accountenvironment.AccountEnvironmentCmd) } func init() { - cobra.OnInitialize(initConfig) addSubCommandPalettes() } @@ -80,7 +84,6 @@ func initConfig() { r := &http_request.ResourceRequester r.Init(&requestConfig) - return } diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index bf06a23..4a046a9 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -58,11 +58,11 @@ type CampaignData struct { } func (f *CampaignData) Save(data string) ([]byte, error) { - return http_request.CampaignRequester.HTTPCreateCampaign(data) + return http_request.CampaignFERequester.HTTPCreateCampaign(data) } func (f *CampaignData) Delete(id string) error { - return http_request.CampaignRequester.HTTPDeleteCampaign(id) + return http_request.CampaignFERequester.HTTPDeleteCampaign(id) } type FlagData struct { diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index 7fccc78..e434360 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -5,6 +5,7 @@ package account import ( "fmt" + "log" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" @@ -22,15 +23,16 @@ var useCmd = &cobra.Command{ return } - if AccountID != "" { - config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) - } + config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) }, } func init() { - useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to display") + useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to manage") + if err := useCmd.MarkFlagRequired("account-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } AccountCmd.AddCommand(useCmd) } diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index 0311617..d3b3247 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -112,7 +112,7 @@ var loginCmd = &cobra.Command{ return } - if password == "" && totp == "" { + if password == "" || totp == "" { fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (password, totp)") return } diff --git a/cmd/web_experimentation/campaign/get.go b/cmd/web_experimentation/campaign/get.go index c573840..e88f4df 100644 --- a/cmd/web_experimentation/campaign/get.go +++ b/cmd/web_experimentation/campaign/get.go @@ -18,7 +18,7 @@ var getCmd = &cobra.Command{ Short: "Get a test", Long: `Get a test in your account`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.TestRequester.HTTPGetTest(CampaignID) + body, err := httprequest.CampaignWERequester.HTTPGetCampaign(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/campaign/list.go b/cmd/web_experimentation/campaign/list.go index adad5e8..855b6dc 100644 --- a/cmd/web_experimentation/campaign/list.go +++ b/cmd/web_experimentation/campaign/list.go @@ -18,7 +18,7 @@ var listCmd = &cobra.Command{ Short: "List all campaigns", Long: `List all campaigns`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.TestRequester.HTTPListTest() + body, err := httprequest.CampaignWERequester.HTTPListCampaign() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/variation/get.go b/cmd/web_experimentation/variation/get.go index 3bcf5b0..da8eb54 100644 --- a/cmd/web_experimentation/variation/get.go +++ b/cmd/web_experimentation/variation/get.go @@ -22,7 +22,6 @@ var getCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } - fmt.Println(body) jsonBody, err := json.Marshal(body) if err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 724efd7..67b6076 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -26,6 +26,9 @@ var WebExperimentationCmd = &cobra.Command{ Aliases: []string{"web-experimentation", "web-exp", "we"}, Short: "Manage resources related to the feature experimentation product", Long: `Manage resources related to the feature experimentation product in your account`, + PersistentPreRun: func(cmd *cobra.Command, args []string) { + initConfig() + }, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, @@ -40,7 +43,6 @@ func addSubCommandPalettes() { } func init() { - cobra.OnInitialize(initConfig) addSubCommandPalettes() } @@ -62,7 +64,5 @@ func initConfig() { r := &http_request.ResourceRequester r.Init(&requestConfig) - return - } diff --git a/models/token.go b/models/token.go index f65150b..e7c347a 100644 --- a/models/token.go +++ b/models/token.go @@ -65,8 +65,14 @@ type PasswordRequest struct { ClientSecret string `json:"client_secret"` } -type RefreshTokenRequest struct { +type RefreshTokenRequestFE struct { GrantType string `json:"grant_type"` ClientID string `json:"client_id"` RefreshToken string `json:"refresh_token"` } +type RefreshTokenRequestWE struct { + GrantType string `json:"grant_type"` + ClientID string `json:"client_id"` + RefreshToken string `json:"refresh_token"` + ClientSecret string `json:"client_secret"` +} diff --git a/utils/config/config.go b/utils/config/config.go index be87b13..8ca1c13 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -174,6 +174,7 @@ func WriteToken(product, configurationName string, authenticationResponse models v.SetConfigFile(configFilepath) + v.MergeInConfig() v.Set("token", authenticationResponse.AccessToken) v.Set("refresh_token", authenticationResponse.RefreshToken) diff --git a/utils/config/default.go b/utils/config/default.go index aaac0e9..ff2791f 100644 --- a/utils/config/default.go +++ b/utils/config/default.go @@ -3,7 +3,7 @@ package config import "github.com/flagship-io/flagship/cmd/version" const ( - OutputFormat = "json" + OutputFormat = "table" GrantType = "client_credentials" Expiration = 86400 Scope = "*" diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index a40af92..6b10d4f 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -12,6 +12,8 @@ import ( "strings" "time" + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" ) @@ -58,6 +60,7 @@ type RequestConfig struct { Token string `mapstructure:"token"` RefreshToken string `mapstructure:"refresh_token"` CurrentUsedCredential string `mapstructure:"current_used_credential"` + OutputFormat string `mapstructure:"output_format"` } var cred RequestConfig @@ -67,19 +70,21 @@ func Init(credL RequestConfig) { } func regenerateToken(product, configName string) { - authenticationResponse, err := HTTPRefreshToken(cred.ClientID, cred.RefreshToken) + var authenticationResponse models.TokenResponse - if err != nil { - log.Fatalf("%s", err) + if product == utils.FEATURE_EXPERIMENTATION { + authenticationResponse, _ = HTTPRefreshTokenFE(cred.ClientID, cred.RefreshToken) + } else { + authenticationResponse, _ = HTTPRefreshTokenWE(utils.CLIENT_ID, utils.CLIENT_SECRET, cred.RefreshToken) } if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") - } else { - cred.RefreshToken = authenticationResponse.RefreshToken - cred.Token = authenticationResponse.AccessToken - config.WriteToken(product, configName, authenticationResponse) } + cred.RefreshToken = authenticationResponse.RefreshToken + cred.Token = authenticationResponse.AccessToken + config.WriteToken(product, configName, authenticationResponse) + } func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) { @@ -88,12 +93,11 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) bodyIO = bytes.NewBuffer(body) } - //fmt.Println(method, url) var resource T - resourceType := reflect.TypeOf(resource).String() + resourceType := reflect.TypeOf(resource) - if resourceType == "feature_experimentation.Campaign" || resourceType == "feature_experimentation.Goal" { + if resourceType == reflect.TypeOf(feature_experimentation.Goal{}) || resourceType == reflect.TypeOf(feature_experimentation.CampaignFE{}) { if cred.AccountID == "" || cred.AccountEnvironmentID == "" { log.Fatalf("account_id or account_environment_id required, Please configure your CLI") } @@ -109,7 +113,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) log.Fatalf("account_id required, Please configure your CLI") } // for resource loader - if resourceType == "resource.ResourceData" && !strings.Contains(url, "token") && (cred.AccountID == "" || cred.AccountEnvironmentID == "") { + if resourceType.String() == "resource.ResourceData" && !strings.Contains(url, "token") && (cred.AccountID == "" || cred.AccountEnvironmentID == "") { log.Fatalf("account_id or account_environment_id required, Please configure your CLI") } diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 61d01c2..88eeee9 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -2,16 +2,15 @@ package common import ( "encoding/json" - "fmt" "net/http" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" ) -func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, error) { +func HTTPRefreshTokenFE(client_id, refresh_token string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse - authRequest := models.RefreshTokenRequest{ + authRequest := models.RefreshTokenRequestFE{ ClientID: client_id, GrantType: "refresh_token", RefreshToken: refresh_token, @@ -34,6 +33,32 @@ func HTTPRefreshToken(client_id, refresh_token string) (models.TokenResponse, er return authenticationResponse, err } +func HTTPRefreshTokenWE(client_id, client_secret, refresh_token string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.RefreshTokenRequestWE{ + ClientID: client_id, + GrantType: "refresh_token", + RefreshToken: refresh_token, + ClientSecret: client_secret, + } + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1"+"/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.ClientCredentialsRequest{ @@ -113,8 +138,6 @@ func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfa return models.TokenResponse{}, err } - fmt.Println(string(mfaRespBody)) - mfmRequest := models.MultiFactorMethodRequestWE{ GrantType: "multi_factor_methods", MfaToken: mfaResponse.MfaToken, @@ -136,8 +159,6 @@ func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfa return models.TokenResponse{}, err } - fmt.Println(string(mfmRespBody)) - mfRequest := models.MultiFactorRequestWE{ GrantType: "multi_factor", MfaToken: mfmResponse.MfaToken, @@ -160,14 +181,12 @@ func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfa return models.TokenResponse{}, err } - fmt.Println(authenticationResponse) - return authenticationResponse, err } func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse - authRequest := models.RefreshTokenRequest{ + authRequest := models.RefreshTokenRequestFE{ ClientID: client_id, GrantType: "refresh_token", RefreshToken: refresh_token, diff --git a/utils/http_request/feature_experimentation/campaign.go b/utils/http_request/feature_experimentation/campaign.go index 5495058..9c6bb05 100644 --- a/utils/http_request/feature_experimentation/campaign.go +++ b/utils/http_request/feature_experimentation/campaign.go @@ -9,27 +9,27 @@ import ( "github.com/flagship-io/flagship/utils/http_request/common" ) -type CampaignRequester struct { +type CampaignFERequester struct { *common.ResourceRequest } -func (c *CampaignRequester) HTTPListCampaign() ([]models.CampaignFE, error) { +func (c *CampaignFERequester) HTTPListCampaign() ([]models.CampaignFE, error) { return common.HTTPGetAllPagesFE[models.CampaignFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns") } -func (c *CampaignRequester) HTTPGetCampaign(id string) (models.CampaignFE, error) { +func (c *CampaignFERequester) HTTPGetCampaign(id string) (models.CampaignFE, error) { return common.HTTPGetItem[models.CampaignFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + c.AccountID + "/account_environments/" + c.AccountEnvironmentID + "/campaigns/" + id) } -func (c *CampaignRequester) HTTPCreateCampaign(data string) ([]byte, error) { +func (c *CampaignFERequester) HTTPCreateCampaign(data string) ([]byte, error) { return common.HTTPRequest[models.CampaignFE](http.MethodPost, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns", []byte(data)) } -func (c *CampaignRequester) HTTPEditCampaign(id, data string) ([]byte, error) { +func (c *CampaignFERequester) HTTPEditCampaign(id, data string) ([]byte, error) { return common.HTTPRequest[models.CampaignFE](http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, []byte(data)) } -func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { +func (c *CampaignFERequester) HTTPSwitchCampaign(id, state string) error { campaignSwitchRequest := models.CampaignFESwitchRequest{ State: state, } @@ -43,7 +43,7 @@ func (c *CampaignRequester) HTTPSwitchCampaign(id, state string) error { return err } -func (c *CampaignRequester) HTTPDeleteCampaign(id string) error { +func (c *CampaignFERequester) HTTPDeleteCampaign(id string) error { _, err := common.HTTPRequest[models.CampaignFE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+c.AccountID+"/account_environments/"+c.AccountEnvironmentID+"/campaigns/"+id, nil) return err } diff --git a/utils/http_request/feature_experimentation/campaign_test.go b/utils/http_request/feature_experimentation/campaign_test.go index 65fbe13..e87c0ba 100644 --- a/utils/http_request/feature_experimentation/campaign_test.go +++ b/utils/http_request/feature_experimentation/campaign_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" ) -var campaignRequester = CampaignRequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} +var campaignRequester = CampaignFERequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} func TestHTTPGetCampaign(t *testing.T) { respBody, err := campaignRequester.HTTPGetCampaign("testCampaignID") diff --git a/utils/http_request/main.go b/utils/http_request/main.go index 5737dc6..23277fc 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -15,7 +15,7 @@ var ResourceRequester common.ResourceRequest var HTTPResources = []HTTPResource{&ResourceRequester} // feature experimentation -var CampaignRequester feature_experimentation.CampaignRequester = feature_experimentation.CampaignRequester{ResourceRequest: &ResourceRequester} +var CampaignFERequester feature_experimentation.CampaignFERequester = feature_experimentation.CampaignFERequester{ResourceRequest: &ResourceRequester} var AccountEnvironmentFERequester feature_experimentation.AccountEnvironmentFERequester = feature_experimentation.AccountEnvironmentFERequester{ResourceRequest: &ResourceRequester} var FlagRequester feature_experimentation.FlagRequester = feature_experimentation.FlagRequester{ResourceRequest: &ResourceRequester} var GoalRequester feature_experimentation.GoalRequester = feature_experimentation.GoalRequester{ResourceRequest: &ResourceRequester} @@ -28,7 +28,7 @@ var PanicRequester feature_experimentation.PanicRequester = feature_experimentat // web experimentation -var TestRequester web_experimentation.TestRequester = web_experimentation.TestRequester{ResourceRequest: &ResourceRequester} +var CampaignWERequester web_experimentation.CampaignWERequester = web_experimentation.CampaignWERequester{ResourceRequest: &ResourceRequester} var GlobalCodeRequester web_experimentation.GlobalCodeRequester = web_experimentation.GlobalCodeRequester{ResourceRequest: &ResourceRequester} var AccountWERequester web_experimentation.AccountWERequester = web_experimentation.AccountWERequester{ResourceRequest: &ResourceRequester} var VariationWERequester web_experimentation.VariationWERequester = web_experimentation.VariationWERequester{ResourceRequest: &ResourceRequester} diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index 1ca9458..c332bd4 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -8,23 +8,23 @@ import ( "github.com/flagship-io/flagship/utils/http_request/common" ) -type TestRequester struct { +type CampaignWERequester struct { *common.ResourceRequest } -func (t *TestRequester) HTTPListTest() ([]models.CampaignWE, error) { +func (t *CampaignWERequester) HTTPListCampaign() ([]models.CampaignWE, error) { return common.HTTPGetAllPagesWE[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests") } -func (t *TestRequester) HTTPGetTest(id string) (models.CampaignWE, error) { +func (t *CampaignWERequester) HTTPGetCampaign(id string) (models.CampaignWE, error) { return common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) } -func (t *TestRequester) HTTPCreateTest(data string) ([]byte, error) { +func (t *CampaignWERequester) HTTPCreateCampaign(data string) ([]byte, error) { return common.HTTPRequest[models.CampaignWE](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests", []byte(data)) } -func (t *TestRequester) HTTPEditTest(id, data string) ([]byte, error) { +func (t *CampaignWERequester) HTTPEditCampaign(id, data string) ([]byte, error) { return common.HTTPRequest[models.CampaignWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, []byte(data)) } @@ -42,7 +42,7 @@ func (t *TestRequester) HTTPEditTest(id, data string) ([]byte, error) { return err } */ -func (t *TestRequester) HTTPDeleteTest(id string) error { +func (t *CampaignWERequester) HTTPDeleteCampaign(id string) error { _, err := common.HTTPRequest[models.CampaignWE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) return err } From dbbb706b53fa4a5d94b10adab40cdd646e0254a7 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 3 Apr 2024 13:53:46 +0000 Subject: [PATCH 12/48] remove useless listing --- cmd/feature_experimentation/account/list.go | 33 ------------------- .../account_environment/list.go | 6 ++-- utils/http_request/common/request.go | 1 + .../account_environment.go | 8 +++-- 4 files changed, 11 insertions(+), 37 deletions(-) delete mode 100644 cmd/feature_experimentation/account/list.go diff --git a/cmd/feature_experimentation/account/list.go b/cmd/feature_experimentation/account/list.go deleted file mode 100644 index 5149552..0000000 --- a/cmd/feature_experimentation/account/list.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package account - -import ( - "log" - - "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -// listCmd represents the list command -var listCmd = &cobra.Command{ - Use: "list", - Short: "list all auth", - Long: `list all auth from your system`, - Run: func(cmd *cobra.Command, args []string) { - - body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() - if err != nil { - log.Fatalf("error occurred: %v", err) - } - utils.FormatItem([]string{"Id", "Environment", "IsMain", "Panic", "SingleAssignment"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) - }, -} - -func init() { - - //AccountCmd.AddCommand(listCmd) -} diff --git a/cmd/feature_experimentation/account_environment/list.go b/cmd/feature_experimentation/account_environment/list.go index c460f38..58cca16 100644 --- a/cmd/feature_experimentation/account_environment/list.go +++ b/cmd/feature_experimentation/account_environment/list.go @@ -12,14 +12,15 @@ import ( "github.com/spf13/viper" ) +var accountID string + // listCmd represents the list command var listCmd = &cobra.Command{ Use: "list", Short: "list all account environment id associated to your account", Long: `list all account environment id associated to your account`, Run: func(cmd *cobra.Command, args []string) { - - body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment() + body, err := httprequest.AccountEnvironmentFERequester.HTTPListAccountEnvironment(accountID) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -28,5 +29,6 @@ var listCmd = &cobra.Command{ } func init() { + useCmd.Flags().StringVarP(&accountID, "account-id", "a", "", "account id of the credentials you want to list") AccountEnvironmentCmd.AddCommand(listCmd) } diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 6b10d4f..0f745c6 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -159,6 +159,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) regenerateToken(cred.Product, cred.CurrentUsedCredential) return HTTPRequest[T](method, url, body) } + return respBody, err } diff --git a/utils/http_request/feature_experimentation/account_environment.go b/utils/http_request/feature_experimentation/account_environment.go index 0ac0348..2891513 100644 --- a/utils/http_request/feature_experimentation/account_environment.go +++ b/utils/http_request/feature_experimentation/account_environment.go @@ -10,8 +10,12 @@ type AccountEnvironmentFERequester struct { *common.ResourceRequest } -func (a *AccountEnvironmentFERequester) HTTPListAccountEnvironment() ([]models.AccountEnvironmentFE, error) { - return common.HTTPGetAllPagesFE[models.AccountEnvironmentFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + a.AccountID + "/account_environments") +func (a *AccountEnvironmentFERequester) HTTPListAccountEnvironment(accountID string) ([]models.AccountEnvironmentFE, error) { + if accountID == "" { + accountID = a.AccountID + } + + return common.HTTPGetAllPagesFE[models.AccountEnvironmentFE](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + accountID + "/account_environments") } func (a *AccountEnvironmentFERequester) HTTPGetAccountEnvironment(id string) (models.AccountEnvironmentFE, error) { From 840c743d568317c77ed3759a078721d852e4f6c4 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 3 Apr 2024 14:26:57 +0000 Subject: [PATCH 13/48] add new error for failing request --- .../account_environment/list.go | 2 +- utils/http_request/common/request.go | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/cmd/feature_experimentation/account_environment/list.go b/cmd/feature_experimentation/account_environment/list.go index 58cca16..be412a1 100644 --- a/cmd/feature_experimentation/account_environment/list.go +++ b/cmd/feature_experimentation/account_environment/list.go @@ -29,6 +29,6 @@ var listCmd = &cobra.Command{ } func init() { - useCmd.Flags().StringVarP(&accountID, "account-id", "a", "", "account id of the credentials you want to list") + listCmd.Flags().StringVarP(&accountID, "account-id", "a", "", "account id of the credentials you want to list") AccountEnvironmentCmd.AddCommand(listCmd) } diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 0f745c6..8bebb37 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -4,11 +4,14 @@ import ( "bytes" "compress/gzip" "encoding/json" + "errors" "fmt" "io" "log" "net/http" + "os" "reflect" + "regexp" "strings" "time" @@ -160,6 +163,13 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) return HTTPRequest[T](method, url, body) } + match, _ := regexp.MatchString("4..|5..", resp.Status) + if match { + err := errors.New(string(respBody)) + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return respBody, err } From 8bb953004a94a80c7374dad5aed5d800a5c549c9 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 5 Apr 2024 13:14:37 +0000 Subject: [PATCH 14/48] Add unit test for fe and we account and auth cmds & fix typos --- .../account/account.go | 2 +- .../account/account_test.go | 60 +++++++++++++ .../account/current.go | 14 +-- cmd/feature_experimentation/account/use.go | 2 + .../account_environment.go | 2 +- .../account_environment_test.go | 60 +++++++++++++ .../account_environment/current.go | 12 +-- .../account_environment/use.go | 2 + cmd/feature_experimentation/auth/auth.go | 4 +- cmd/feature_experimentation/auth/auth_test.go | 33 ++++--- cmd/feature_experimentation/auth/delete.go | 40 +++++++++ cmd/feature_experimentation/auth/get.go | 4 +- cmd/feature_experimentation/auth/list.go | 20 +++-- cmd/feature_experimentation/auth/login.go | 30 ++++--- cmd/web_experimentation/account/account.go | 2 +- .../account/account_test.go | 60 +++++++++++++ cmd/web_experimentation/account/current.go | 12 +-- cmd/web_experimentation/account/use.go | 2 + cmd/web_experimentation/auth/auth.go | 4 +- cmd/web_experimentation/auth/auth_test.go | 86 +++++++++++++++++++ cmd/web_experimentation/auth/delete.go | 40 +++++++++ cmd/web_experimentation/auth/get.go | 3 +- cmd/web_experimentation/auth/list.go | 20 +++-- cmd/web_experimentation/auth/login.go | 61 +++++++------ models/auth.go | 4 + utils/config/config.go | 26 +++--- utils/format.go | 4 +- utils/http_request/common/request.go | 21 +++-- utils/mock_function/configuration.go | 14 --- .../feature_experimentation/account.go | 11 +++ .../feature_experimentation/auth.go | 11 ++- .../feature_experimentation/token.go | 4 +- utils/mock_function/request.go | 2 +- .../web_experimentation/account.go | 11 +++ .../mock_function/web_experimentation/auth.go | 21 +++++ .../web_experimentation/token.go | 40 +++++++++ 36 files changed, 614 insertions(+), 130 deletions(-) create mode 100644 cmd/feature_experimentation/account/account_test.go create mode 100644 cmd/feature_experimentation/account_environment/account_environment_test.go create mode 100644 cmd/feature_experimentation/auth/delete.go create mode 100644 cmd/web_experimentation/account/account_test.go create mode 100644 cmd/web_experimentation/auth/auth_test.go create mode 100644 cmd/web_experimentation/auth/delete.go delete mode 100644 utils/mock_function/configuration.go create mode 100644 utils/mock_function/feature_experimentation/account.go create mode 100644 utils/mock_function/web_experimentation/account.go create mode 100644 utils/mock_function/web_experimentation/auth.go create mode 100644 utils/mock_function/web_experimentation/token.go diff --git a/cmd/feature_experimentation/account/account.go b/cmd/feature_experimentation/account/account.go index bbb73e4..4b8de07 100644 --- a/cmd/feature_experimentation/account/account.go +++ b/cmd/feature_experimentation/account/account.go @@ -10,7 +10,7 @@ var ( AccountID string ) -// ConfigurationCmd represents the configuration command +// AccountCmd represents the account command var AccountCmd = &cobra.Command{ Use: "account [use|list|current]", Short: "Manage your CLI authentication", diff --git a/cmd/feature_experimentation/account/account_test.go b/cmd/feature_experimentation/account/account_test.go new file mode 100644 index 0000000..b4e1224 --- /dev/null +++ b/cmd/feature_experimentation/account/account_test.go @@ -0,0 +1,60 @@ +package account + +import ( + "encoding/json" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_fe.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_fe.APIToken() + + m.Run() +} + +var testAccount models.AccountJSON + +func TestAccountCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountCmd) + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") +} + +func TestAccountHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountCmd, "--help") + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") +} + +func TestAccountUseCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AccountCmd, "use") + assert.Contains(t, failOutput, "Error: required flag(s) \"account-id\" not set") + + successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-a=account_id") + assert.Equal(t, "Account ID set to : account_id\n", successOutput) +} + +func TestAccountCurrentCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AccountCmd, "current") + + err := json.Unmarshal([]byte(output), &testAccount) + + assert.Nil(t, err) + + assert.Equal(t, feature_experimentation.TestAccount.AccountID, testAccount.AccountID) +} diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index 523db45..c6381d2 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -22,8 +22,8 @@ var currentCmd = &cobra.Command{ Long: `current an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.AccountYaml - var configuration models.AccountJSON + var accountYaml models.AccountYaml + var account models.AccountJSON yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) if err != nil { @@ -31,16 +31,16 @@ var currentCmd = &cobra.Command{ } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &accountYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential - configuration.AccountID = configurationYaml.AccountID - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID + account.CurrentUsedCredential = accountYaml.CurrentUsedCredential + account.AccountID = accountYaml.AccountID + account.AccountEnvironmentID = accountYaml.AccountEnvironmentID - utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index 3614ff0..7c34ff4 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -25,6 +25,8 @@ var useCmd = &cobra.Command{ config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) + fmt.Fprintln(cmd.OutOrStdout(), "Account ID set to : "+AccountID) + }, } diff --git a/cmd/feature_experimentation/account_environment/account_environment.go b/cmd/feature_experimentation/account_environment/account_environment.go index 7a0aa75..c3bda6d 100644 --- a/cmd/feature_experimentation/account_environment/account_environment.go +++ b/cmd/feature_experimentation/account_environment/account_environment.go @@ -10,7 +10,7 @@ var ( AccountEnvironmentID string ) -// ConfigurationCmd represents the configuration command +// AccountEnvironmentCmd represents the account environment command var AccountEnvironmentCmd = &cobra.Command{ Use: "account-environment [use|list|current]", Short: "Manage your CLI authentication", diff --git a/cmd/feature_experimentation/account_environment/account_environment_test.go b/cmd/feature_experimentation/account_environment/account_environment_test.go new file mode 100644 index 0000000..d438bb4 --- /dev/null +++ b/cmd/feature_experimentation/account_environment/account_environment_test.go @@ -0,0 +1,60 @@ +package accountenvironment + +import ( + "encoding/json" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_fe.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_fe.APIToken() + + m.Run() +} + +var testAccount models.AccountJSON + +func TestAccountEnvironmentCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountEnvironmentCmd) + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account-environment [use|list|current]") +} + +func TestAccountEnvironmentHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "--help") + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account-environment [use|list|current]") +} + +func TestAccountEnvironmentUseCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "use") + assert.Contains(t, failOutput, "Error: required flag(s) \"account-environment-id\" not set") + + successOutput, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "use", "--account-environment-id=account_environment_id") + assert.Equal(t, "Account Environment ID set to : account_environment_id\n", successOutput) +} + +func TestAccountEnvironmentCurrentCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "current") + + err := json.Unmarshal([]byte(output), &testAccount) + + assert.Nil(t, err) + + assert.Equal(t, web_experimentation.TestAccount.AccountEnvironmentID, testAccount.AccountEnvironmentID) +} diff --git a/cmd/feature_experimentation/account_environment/current.go b/cmd/feature_experimentation/account_environment/current.go index 300f201..2cc0bea 100644 --- a/cmd/feature_experimentation/account_environment/current.go +++ b/cmd/feature_experimentation/account_environment/current.go @@ -22,8 +22,8 @@ var currentCmd = &cobra.Command{ Long: `current an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.AccountYaml - var configuration models.AccountJSON + var accountYaml models.AccountYaml + var account models.AccountJSON yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) if err != nil { @@ -31,15 +31,15 @@ var currentCmd = &cobra.Command{ } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &accountYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential - configuration.AccountEnvironmentID = configurationYaml.AccountEnvironmentID + account.CurrentUsedCredential = accountYaml.CurrentUsedCredential + account.AccountEnvironmentID = accountYaml.AccountEnvironmentID - utils.FormatItem([]string{"CurrentUsedCredential", "AccountEnvironmentID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountEnvironmentID"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/account_environment/use.go b/cmd/feature_experimentation/account_environment/use.go index 0475cdf..01609c1 100644 --- a/cmd/feature_experimentation/account_environment/use.go +++ b/cmd/feature_experimentation/account_environment/use.go @@ -25,6 +25,8 @@ var useCmd = &cobra.Command{ config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) + fmt.Fprintln(cmd.OutOrStdout(), "Account Environment ID set to : "+AccountEnvironmentID) + }, } diff --git a/cmd/feature_experimentation/auth/auth.go b/cmd/feature_experimentation/auth/auth.go index 2cb0eaf..1f07ce2 100644 --- a/cmd/feature_experimentation/auth/auth.go +++ b/cmd/feature_experimentation/auth/auth.go @@ -12,9 +12,9 @@ var ( AccountId string ) -// ConfigurationCmd represents the configuration command +// AuthCmd represents the auth command var AuthCmd = &cobra.Command{ - Use: "authentication [login|get|list]", + Use: "authentication [login|get|list|delete]", Aliases: []string{"auth"}, Short: "Manage your CLI authentication for feature experimentation", Long: `Manage your CLI authentication for feature experimentation`, diff --git a/cmd/feature_experimentation/auth/auth_test.go b/cmd/feature_experimentation/auth/auth_test.go index 932448b..3fbfb5b 100644 --- a/cmd/feature_experimentation/auth/auth_test.go +++ b/cmd/feature_experimentation/auth/auth_test.go @@ -8,6 +8,7 @@ import ( "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" @@ -26,21 +27,21 @@ func TestMain(m *testing.M) { m.Run() } -var testConfiguration models.Auth -var testConfigurationList []models.Auth +var testAuth models.Auth +var testAuthList []models.Auth func TestAuthCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AuthCmd) - assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list]") + assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list|delete]") } func TestAuthHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AuthCmd, "--help") - assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list]") + assert.Contains(t, output, "Manage your CLI authentication for feature experimentation\n\nUsage:\n authentication [login|get|list|delete]") } func TestAuthLoginCommand(t *testing.T) { - successOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_configuration", "-i=testConfigurationClientID", "-s=testConfigurationClientSecret", "-a=account_id") + successOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_auth", "-i=testAuthClientID", "-s=testAuthClientSecret", "-a=account_id") assert.Equal(t, "Credential created successfully\n", successOutput) } @@ -48,15 +49,15 @@ func TestAuthListCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AuthCmd, "list") - err := json.Unmarshal([]byte(output), &testConfigurationList) + err := json.Unmarshal([]byte(output), &testAuthList) assert.Nil(t, err) - //byt, err := json.Marshal(mockfunction.TestConfiguration) + byt, err := json.Marshal(feature_experimentation.TestAuth) assert.Nil(t, err) - //assert.Contains(t, output, string(byt)) + assert.Contains(t, output, string(byt)) } func TestAuthGetCommand(t *testing.T) { @@ -64,10 +65,20 @@ func TestAuthGetCommand(t *testing.T) { failOutput, _ := utils.ExecuteCommand(AuthCmd, "get") assert.Contains(t, failOutput, "Error: required flag(s) \"username\" not set") - successOutput, _ := utils.ExecuteCommand(AuthCmd, "get", "--username=test_configuration") - err := json.Unmarshal([]byte(successOutput), &testConfiguration) + successOutput, _ := utils.ExecuteCommand(AuthCmd, "get", "--username=test_auth") + err := json.Unmarshal([]byte(successOutput), &testAuth) assert.Nil(t, err) - //assert.Equal(t, mockfunction.TestConfiguration, testConfiguration) + assert.Equal(t, feature_experimentation.TestAuth, testAuth) +} + +func TestAuthDeleteCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AuthCmd, "delete") + assert.Contains(t, failOutput, "Error: required flag(s) \"username\" not set") + + output, _ := utils.ExecuteCommand(AuthCmd, "delete", "--username=test_auth") + + assert.Contains(t, output, "Credential deleted successfully") } diff --git a/cmd/feature_experimentation/auth/delete.go b/cmd/feature_experimentation/auth/delete.go new file mode 100644 index 0000000..7ab9229 --- /dev/null +++ b/cmd/feature_experimentation/auth/delete.go @@ -0,0 +1,40 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "fmt" + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" +) + +// deleteCmd represents delete command +var deleteCmd = &cobra.Command{ + Use: "delete [-u | --username=]", + Short: "Delete an auth", + Long: `Delete an auth`, + Run: func(cmd *cobra.Command, args []string) { + + config.CheckABTastyHomeDirectory() + + if err := os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username)); err != nil { + log.Fatalf("error occurred: %s", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), "Credential deleted successfully") + }, +} + +func init() { + deleteCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to delete") + + if err := deleteCmd.MarkFlagRequired("username"); err != nil { + log.Fatalf("error occurred: %v", err) + } + AuthCmd.AddCommand(deleteCmd) +} diff --git a/cmd/feature_experimentation/auth/get.go b/cmd/feature_experimentation/auth/get.go index 56c40cf..97f6801 100644 --- a/cmd/feature_experimentation/auth/get.go +++ b/cmd/feature_experimentation/auth/get.go @@ -39,8 +39,10 @@ var getCmd = &cobra.Command{ auth.Username = authYaml.Username auth.ClientID = authYaml.ClientID auth.ClientSecret = authYaml.ClientSecret + auth.Token = authYaml.Token + auth.RefreshToken = authYaml.RefreshToken - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret", "Token", "RefreshToken"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/auth/list.go b/cmd/feature_experimentation/auth/list.go index 341fbf9..ff6409a 100644 --- a/cmd/feature_experimentation/auth/list.go +++ b/cmd/feature_experimentation/auth/list.go @@ -30,28 +30,30 @@ var listCmd = &cobra.Command{ for _, fileName := range existingAuths { if fileName != "" { - var configurationYaml models.AuthYaml - var configuration models.Auth + var authYaml models.AuthYaml + var auth models.Auth yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, fileName)) if err != nil { log.Fatalf("error occurred: %s", err) } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &authYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - if configurationYaml.Username != "" { - configuration.Username = configurationYaml.Username - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret - auths = append(auths, configuration) + if authYaml.Username != "" { + auth.Username = authYaml.Username + auth.ClientID = authYaml.ClientID + auth.ClientSecret = authYaml.ClientSecret + auth.Token = authYaml.Token + auth.RefreshToken = authYaml.RefreshToken + auths = append(auths, auth) } } } - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "ClientID", "ClientSecret", "Token"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index e57cb49..0429094 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -5,7 +5,6 @@ package auth import ( "fmt" - "log" "slices" "github.com/flagship-io/flagship/utils" @@ -37,14 +36,19 @@ var loginCmd = &cobra.Command{ Long: `login`, Run: func(cmd *cobra.Command, args []string) { if !checkSingleFlag(credentialsFile != "", Username != "") { - log.Fatalf("error occurred: %s", "1 flag is required. (username, credential-file)") + fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", "1 flag is required. (username, credential-file)") + return } if credentialsFile != "" { v := config.ReadCredentialsFromFile(credentialsFile) + if v.GetString("username") == "" || v.GetString("client_id") == "" || v.GetString("client_secret") == "" || v.GetString("account_id") == "" { + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") + return + } authenticationResponse, err := common.HTTPCreateTokenFE(v.GetString("client_id"), v.GetString("client_secret"), v.GetString("account_id")) if err != nil { - log.Fatalf("%s", err) + fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) return } config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) @@ -56,13 +60,18 @@ var loginCmd = &cobra.Command{ if Username != "" { existingCredentials, err := config.GetUsernames(utils.FEATURE_EXPERIMENTATION) if err != nil { - log.Fatalf("error occurred: %s", err) + fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) + return } if slices.Contains(existingCredentials, Username) { - config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) - - fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + if AccountId != "" { + config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + + fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + return + } + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (account id)") return } @@ -72,12 +81,13 @@ var loginCmd = &cobra.Command{ } authenticationResponse, err := common.HTTPCreateTokenFE(ClientID, ClientSecret, AccountId) if err != nil { - log.Fatalf("%s", err) + fmt.Fprintln(cmd.OutOrStderr(), err) return } if authenticationResponse.AccessToken == "" { - log.Fatal("client_id or client_secret not valid") + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, client_id or client_secret not valid") + return } config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) diff --git a/cmd/web_experimentation/account/account.go b/cmd/web_experimentation/account/account.go index bbb73e4..4b8de07 100644 --- a/cmd/web_experimentation/account/account.go +++ b/cmd/web_experimentation/account/account.go @@ -10,7 +10,7 @@ var ( AccountID string ) -// ConfigurationCmd represents the configuration command +// AccountCmd represents the account command var AccountCmd = &cobra.Command{ Use: "account [use|list|current]", Short: "Manage your CLI authentication", diff --git a/cmd/web_experimentation/account/account_test.go b/cmd/web_experimentation/account/account_test.go new file mode 100644 index 0000000..5eeaac5 --- /dev/null +++ b/cmd/web_experimentation/account/account_test.go @@ -0,0 +1,60 @@ +package account + +import ( + "encoding/json" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIToken() + + m.Run() +} + +var testAccount models.AccountJSON + +func TestAccountCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountCmd) + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") +} + +func TestAccountHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountCmd, "--help") + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") +} + +func TestAccountUseCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AccountCmd, "use") + assert.Contains(t, failOutput, "Error: required flag(s) \"account-id\" not set") + + successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-a=account_id") + assert.Equal(t, "Account ID set to : account_id\n", successOutput) +} + +func TestAccountCurrentCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AccountCmd, "current") + + err := json.Unmarshal([]byte(output), &testAccount) + + assert.Nil(t, err) + + assert.Equal(t, web_experimentation.TestAccount.AccountID, testAccount.AccountID) +} diff --git a/cmd/web_experimentation/account/current.go b/cmd/web_experimentation/account/current.go index 12318fb..52737e4 100644 --- a/cmd/web_experimentation/account/current.go +++ b/cmd/web_experimentation/account/current.go @@ -22,8 +22,8 @@ var currentCmd = &cobra.Command{ Long: `current an auth credential from your system`, Run: func(cmd *cobra.Command, args []string) { - var configurationYaml models.AccountYaml - var configuration models.AccountJSON + var accountYaml models.AccountYaml + var account models.AccountJSON yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI)) if err != nil { @@ -31,15 +31,15 @@ var currentCmd = &cobra.Command{ } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &accountYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - configuration.CurrentUsedCredential = configurationYaml.CurrentUsedCredential - configuration.AccountID = configurationYaml.AccountID + account.CurrentUsedCredential = accountYaml.CurrentUsedCredential + account.AccountID = accountYaml.AccountID - utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, configuration, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index e434360..188b881 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -25,6 +25,8 @@ var useCmd = &cobra.Command{ config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) + fmt.Fprintln(cmd.OutOrStdout(), "Account ID set to : "+AccountID) + }, } diff --git a/cmd/web_experimentation/auth/auth.go b/cmd/web_experimentation/auth/auth.go index 5a0a880..cb5f9bd 100644 --- a/cmd/web_experimentation/auth/auth.go +++ b/cmd/web_experimentation/auth/auth.go @@ -11,9 +11,9 @@ var ( Username string ) -// ConfigurationCmd represents the configuration command +// AuthCmd represents the auth command var AuthCmd = &cobra.Command{ - Use: "authentication [login|get|list]", + Use: "authentication [login|get|list|delete]", Aliases: []string{"auth"}, Short: "Manage your CLI authentication for web experimentation", Long: `Manage your CLI authentication for web experimentation`, diff --git a/cmd/web_experimentation/auth/auth_test.go b/cmd/web_experimentation/auth/auth_test.go new file mode 100644 index 0000000..41ca699 --- /dev/null +++ b/cmd/web_experimentation/auth/auth_test.go @@ -0,0 +1,86 @@ +package auth + +import ( + "encoding/json" + "fmt" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + //defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIToken() + + m.Run() +} + +var testAuth models.Auth +var testAuthList []models.Auth + +func TestAuthCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AuthCmd) + assert.Contains(t, output, "Manage your CLI authentication for web experimentation\n\nUsage:\n authentication [login|get|list|delete]") +} + +func TestAuthHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AuthCmd, "--help") + assert.Contains(t, output, "Manage your CLI authentication for web experimentation\n\nUsage:\n authentication [login|get|list|delete]") +} + +func TestAuthLoginCommand(t *testing.T) { + successOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_auth", "--password=password", "--totp=00000") + assert.Equal(t, "Credential created successfully\n", successOutput) +} + +func TestAuthListCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AuthCmd, "list") + + err := json.Unmarshal([]byte(output), &testAuthList) + fmt.Println(testAuth) + + assert.Nil(t, err) + + byt, err := json.Marshal(web_experimentation.TestAuth) + + assert.Nil(t, err) + + assert.Contains(t, output, string(byt)) +} + +func TestAuthGetCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AuthCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"username\" not set") + + successOutput, _ := utils.ExecuteCommand(AuthCmd, "get", "--username=test_auth") + err := json.Unmarshal([]byte(successOutput), &testAuth) + + assert.Nil(t, err) + + //assert.Equal(t, feature_experimentation.TestAuth, testAuth) +} + +func TestAuthDeleteCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(AuthCmd, "delete") + assert.Contains(t, failOutput, "Error: required flag(s) \"username\" not set") + + output, _ := utils.ExecuteCommand(AuthCmd, "delete", "--username=test_auth") + + assert.Contains(t, output, "Credential deleted successfully") +} diff --git a/cmd/web_experimentation/auth/delete.go b/cmd/web_experimentation/auth/delete.go new file mode 100644 index 0000000..4ef3909 --- /dev/null +++ b/cmd/web_experimentation/auth/delete.go @@ -0,0 +1,40 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "fmt" + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" +) + +// deleteCmd represents delete command +var deleteCmd = &cobra.Command{ + Use: "delete [-u | --username=]", + Short: "Delete an auth", + Long: `Delete an auth`, + Run: func(cmd *cobra.Command, args []string) { + + config.CheckABTastyHomeDirectory() + + if err := os.Remove(config.CredentialPath(utils.WEB_EXPERIMENTATION, Username)); err != nil { + log.Fatalf("error occurred: %s", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), "Credential deleted successfully") + }, +} + +func init() { + deleteCmd.Flags().StringVarP(&Username, "username", "u", "", "username of the credentials you want to delete") + + if err := deleteCmd.MarkFlagRequired("username"); err != nil { + log.Fatalf("error occurred: %v", err) + } + AuthCmd.AddCommand(deleteCmd) +} diff --git a/cmd/web_experimentation/auth/get.go b/cmd/web_experimentation/auth/get.go index faabf80..d05d01a 100644 --- a/cmd/web_experimentation/auth/get.go +++ b/cmd/web_experimentation/auth/get.go @@ -39,8 +39,9 @@ var getCmd = &cobra.Command{ auth.Username = authYaml.Username auth.ClientID = authYaml.ClientID auth.ClientSecret = authYaml.ClientSecret + auth.Token = authYaml.Token - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "Token"}, auth, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/auth/list.go b/cmd/web_experimentation/auth/list.go index 0d1df26..a61e253 100644 --- a/cmd/web_experimentation/auth/list.go +++ b/cmd/web_experimentation/auth/list.go @@ -30,28 +30,30 @@ var listCmd = &cobra.Command{ for _, fileName := range existingAuths { if fileName != "" { - var configurationYaml models.AuthYaml - var configuration models.Auth + var authYaml models.AuthYaml + var auth models.Auth yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, fileName)) if err != nil { log.Fatalf("error occurred: %s", err) } // Unmarshal the YAML data into the struct - err = yaml.Unmarshal(yamlFile, &configurationYaml) + err = yaml.Unmarshal(yamlFile, &authYaml) if err != nil { log.Fatalf("error occurred: %s", err) } - if configurationYaml.Username != "" { - configuration.Username = configurationYaml.Username - configuration.ClientID = configurationYaml.ClientID - configuration.ClientSecret = configurationYaml.ClientSecret - auths = append(auths, configuration) + if authYaml.Username != "" { + auth.Username = authYaml.Username + auth.ClientID = authYaml.ClientID + auth.ClientSecret = authYaml.ClientSecret + auth.Token = authYaml.Token + auth.RefreshToken = authYaml.RefreshToken + auths = append(auths, auth) } } } - utils.FormatItem([]string{"Username", "ClientID", "ClientSecret"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Username", "Token"}, auths, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index d3b3247..8cbfd40 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -23,7 +23,6 @@ var ( browser bool password string totp string - code string ) func checkSingleFlag(bool1, bool2 bool) bool { @@ -65,6 +64,7 @@ var loginCmd = &cobra.Command{ } if browser { + codeChan := make(chan string) clientID := utils.CLIENT_ID clientSecret := utils.CLIENT_SECRET @@ -81,23 +81,37 @@ var loginCmd = &cobra.Command{ if err := openLink(url); err != nil { log.Fatalf("Error opening link: %s", err) } - http.HandleFunc("/auth/callback", handleCallback) - if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { - log.Fatalf("Error starting callback server: %s", err) - } - authenticationResponse, err := common.HTTPCreateTokenWEAuthorizationCode(clientID, clientSecret, code) - if err != nil { - log.Fatalf("%s", err) - return - } + go func() { + http.HandleFunc("/auth/callback", func(w http.ResponseWriter, r *http.Request) { + handleCallback(w, r, codeChan) + }) - if authenticationResponse.AccessToken == "" { - log.Fatal("Credentials not valid.") - } + if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { + log.Fatalf("Error starting callback server: %s", err) + } + }() + + code := <-codeChan - fmt.Fprintln(cmd.OutOrStdout(), "Token generated successfully") + if code != "" { + authenticationResponse, err := common.HTTPCreateTokenWEAuthorizationCode(clientID, clientSecret, code) + if err != nil { + log.Fatalf("error occurred: %s", err) + return + } + fmt.Println(authenticationResponse) + if authenticationResponse.AccessToken == "" { + log.Fatal("Credentials not valid.") + } + // Waiting for fix to implemente route to get username "/users/me" + + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") + return + } + + fmt.Fprintln(cmd.OutOrStderr(), "Error occurred.") } if Username != "" { @@ -118,7 +132,7 @@ var loginCmd = &cobra.Command{ } authenticationResponse, err := common.HTTPCreateTokenWEPassword(utils.CLIENT_ID, utils.CLIENT_SECRET, Username, password, totp) if err != nil { - log.Fatalf("%s", err) + log.Fatalf("error occurred: %s", err) return } @@ -140,28 +154,27 @@ func init() { loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of an auth") loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "Generate link for browser") - loginCmd.Flags().StringVarP(&Username, "username", "u", "", "configuration name") - loginCmd.Flags().StringVarP(&password, "password", "", "", "configuration name") - loginCmd.Flags().StringVarP(&totp, "totp", "", "", "configuration name") + loginCmd.Flags().StringVarP(&Username, "username", "u", "", "username") + loginCmd.Flags().StringVarP(&password, "password", "", "", "password") + loginCmd.Flags().StringVarP(&totp, "totp", "", "", "totp") AuthCmd.AddCommand(loginCmd) } -func handleCallback(w http.ResponseWriter, r *http.Request) { - fmt.Println(r.URL.Query().Get("code")) - code = r.URL.Query().Get("code") +func handleCallback(w http.ResponseWriter, r *http.Request, codeChan chan<- string) { + code := r.URL.Query().Get("code") if code == "" { http.Error(w, "No token found in URL", http.StatusBadRequest) os.Exit(0) return } - http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) + codeChan <- code - fmt.Println("code received:", code) + http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) go func() { time.Sleep(5 * time.Second) - os.Exit(0) + close(codeChan) }() } diff --git a/models/auth.go b/models/auth.go index 73ee665..0699da9 100644 --- a/models/auth.go +++ b/models/auth.go @@ -4,12 +4,16 @@ type Auth struct { Username string `json:"username"` ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"` + Token string `json:"token"` + RefreshToken string `json:"refresh_token"` } type AuthYaml struct { Username string `yaml:"username"` ClientID string `yaml:"client_id"` ClientSecret string `yaml:"client_secret"` + Token string `yaml:"token"` + RefreshToken string `yaml:"refresh_token"` } type AccountYaml struct { diff --git a/utils/config/config.go b/utils/config/config.go index 8ca1c13..0b333d0 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -39,14 +39,14 @@ func CheckABTastyHomeDirectory() (string, error) { if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.FEATURE_EXPERIMENTATION, os.ModePerm) if err != nil { - log.Fatal(err) + log.Fatalf("error occurred: %s", err) } } if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.WEB_EXPERIMENTATION, os.ModePerm) if err != nil { - log.Fatal(err) + log.Fatalf("error occurred: %s", err) } } @@ -57,9 +57,8 @@ func CredentialPath(product, username string) string { homeDir, _ := CheckABTastyHomeDirectory() filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml") if err != nil { - log.Fatalf("error occured: %v", err) + log.Fatalf("error occured: %s", err) } - return filepath } @@ -108,19 +107,22 @@ func CreateAuthFile(product, username, clientId, clientSecret string, authentica } } -func ReadAuth(product, configurationName string) *viper.Viper { +func ReadAuth(product, AuthName string) *viper.Viper { v := viper.New() - configFilepath := CredentialPath(product, configurationName) + configFilepath := CredentialPath(product, AuthName) + if _, err := os.Stat(configFilepath); errors.Is(err, os.ErrNotExist) { + log.Fatalf("error occurred: %v", err) + } v.SetConfigFile(configFilepath) v.MergeInConfig() return v } -func SelectAuth(product, configurationName string) { +func SelectAuth(product, AuthName string) { var v = viper.New() filepath := CredentialPath(product, utils.HOME_CLI) - v.Set("current_used_credential", configurationName) + v.Set("current_used_credential", AuthName) err := v.WriteConfigAs(filepath) if err != nil { @@ -157,9 +159,9 @@ func SetAccountEnvID(product, accountEnvID string) { } } -func ReadCredentialsFromFile(configurationFile string) *viper.Viper { +func ReadCredentialsFromFile(AuthFile string) *viper.Viper { var v = viper.New() - v.SetConfigFile(configurationFile) + v.SetConfigFile(AuthFile) err := v.MergeInConfig() if err != nil { log.Fatalf("error occurred: %v", err) @@ -168,9 +170,9 @@ func ReadCredentialsFromFile(configurationFile string) *viper.Viper { return v } -func WriteToken(product, configurationName string, authenticationResponse models.TokenResponse) { +func WriteToken(product, AuthName string, authenticationResponse models.TokenResponse) { v := viper.New() - configFilepath := CredentialPath(product, configurationName) + configFilepath := CredentialPath(product, AuthName) v.SetConfigFile(configFilepath) diff --git a/utils/format.go b/utils/format.go index 1bc00ca..4b5fc15 100644 --- a/utils/format.go +++ b/utils/format.go @@ -23,7 +23,7 @@ func FormatItem[T any](columns []string, item T, outputFormat string, w io.Write if outputFormat == "json" { projectJSON, err := json.Marshal(item) if err != nil { - log.Fatalf("%s\n", err) + log.Fatalf("error occurred: %s", err) } fmt.Fprintln(w, string(projectJSON)) return @@ -32,7 +32,7 @@ func FormatItem[T any](columns []string, item T, outputFormat string, w io.Write if outputFormat == "json-pretty" { projectJSON, err := json.MarshalIndent(item, "", " ") if err != nil { - log.Fatalf("%s\n", err) + log.Fatalf("error occurred: %s", err) } fmt.Fprintln(w, string(projectJSON)) return diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 8bebb37..5a016c4 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -17,6 +17,7 @@ import ( "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/models/feature_experimentation" + "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" ) @@ -102,7 +103,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) if resourceType == reflect.TypeOf(feature_experimentation.Goal{}) || resourceType == reflect.TypeOf(feature_experimentation.CampaignFE{}) { if cred.AccountID == "" || cred.AccountEnvironmentID == "" { - log.Fatalf("account_id or account_environment_id required, Please configure your CLI") + log.Fatalf("account_id or account_environment_id required, Please authenticate your CLI") } } @@ -112,16 +113,22 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) } if cred.Product == utils.FEATURE_EXPERIMENTATION { - if cred.AccountID == "" { - log.Fatalf("account_id required, Please configure your CLI") + if (cred.Username == "" || cred.AccountID == "") && resourceType != reflect.TypeOf(models.TokenFE{}) { + log.Fatalf("username and account_id required, Please authenticate your CLI") } // for resource loader if resourceType.String() == "resource.ResourceData" && !strings.Contains(url, "token") && (cred.AccountID == "" || cred.AccountEnvironmentID == "") { - log.Fatalf("account_id or account_environment_id required, Please configure your CLI") + log.Fatalf("account_id or account_environment_id required, Please authenticate your CLI") } - if strings.Contains(url, "token") && cred.ClientID == "" && cred.ClientSecret == "" { - log.Fatalf("client_id or client_secret required, Please configure your CLI") + /* if strings.Contains(url, "token") && cred.ClientID == "" && cred.ClientSecret == "" { + log.Fatalf("client_id or client_secret required, Please authenticate your CLI") + } */ + } + + if cred.Product == utils.WEB_EXPERIMENTATION { + if resourceType != reflect.TypeOf(web_experimentation.AccountWE{}) && !strings.Contains(url, "token") && cred.AccountID == "" { + log.Fatalf("username, account_id required, Please authenticate your CLI") } } @@ -166,7 +173,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) match, _ := regexp.MatchString("4..|5..", resp.Status) if match { err := errors.New(string(respBody)) - fmt.Fprintln(os.Stderr, err) + fmt.Fprintf(os.Stderr, "error occurred: %v", err) os.Exit(1) } diff --git a/utils/mock_function/configuration.go b/utils/mock_function/configuration.go deleted file mode 100644 index 3b6fe52..0000000 --- a/utils/mock_function/configuration.go +++ /dev/null @@ -1,14 +0,0 @@ -package mockfunction - -/* var TestConfiguration = models.Configuration{ - Name: "test_configuration", - ClientID: "testConfigurationClientID", - ClientSecret: "testConfigurationClientSecret", - AccountID: "testConfigurationAccountID", - AccountEnvironmentID: "testConfigurationAccountEnvID", -} - -func InitMockConfiguration() { - config.SetViperMock() - os.Remove(config.SetPathForConfigName("test_configuration")) -} */ diff --git a/utils/mock_function/feature_experimentation/account.go b/utils/mock_function/feature_experimentation/account.go new file mode 100644 index 0000000..72636ef --- /dev/null +++ b/utils/mock_function/feature_experimentation/account.go @@ -0,0 +1,11 @@ +package feature_experimentation + +import ( + "github.com/flagship-io/flagship/models" +) + +var TestAccount = models.AccountJSON{ + CurrentUsedCredential: "test_auth", + AccountID: "account_id", + AccountEnvironmentID: "account_environment_id", +} diff --git a/utils/mock_function/feature_experimentation/auth.go b/utils/mock_function/feature_experimentation/auth.go index 5070ec6..f070e6a 100644 --- a/utils/mock_function/feature_experimentation/auth.go +++ b/utils/mock_function/feature_experimentation/auth.go @@ -3,10 +3,19 @@ package feature_experimentation import ( "os" + "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" ) +var TestAuth = models.Auth{ + Username: "test_auth", + ClientID: "testAuthClientID", + ClientSecret: "testAuthClientSecret", + Token: "testAccessToken", + RefreshToken: "testRefreshToken", +} + func InitMockAuth() { - os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, "test_configuration")) + os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, "test_auth")) } diff --git a/utils/mock_function/feature_experimentation/token.go b/utils/mock_function/feature_experimentation/token.go index 84ac9ec..3cfd7ae 100644 --- a/utils/mock_function/feature_experimentation/token.go +++ b/utils/mock_function/feature_experimentation/token.go @@ -21,8 +21,8 @@ func APIToken() { token := "token" testAuthenticationResponse := models.TokenResponse{ - AccessToken: "access_token", - RefreshToken: "refresh_token", + AccessToken: "testAccessToken", + RefreshToken: "testRefreshToken", } httpmock.RegisterResponder("GET", utils.GetHostFeatureExperimentationAuth()+"/token?access_token="+token, diff --git a/utils/mock_function/request.go b/utils/mock_function/request.go index cda6738..c255323 100644 --- a/utils/mock_function/request.go +++ b/utils/mock_function/request.go @@ -14,7 +14,7 @@ type TestRequest struct { } var Auth = common.RequestConfig{ - Username: "test_configuration", + Username: "test_auth", ClientID: "client_id", ClientSecret: "client_secret", AccountID: "account_id", diff --git a/utils/mock_function/web_experimentation/account.go b/utils/mock_function/web_experimentation/account.go new file mode 100644 index 0000000..638945c --- /dev/null +++ b/utils/mock_function/web_experimentation/account.go @@ -0,0 +1,11 @@ +package web_experimentation + +import ( + "github.com/flagship-io/flagship/models" +) + +var TestAccount = models.AccountJSON{ + CurrentUsedCredential: "test_auth", + AccountID: "account_id", + AccountEnvironmentID: "account_environment_id", +} diff --git a/utils/mock_function/web_experimentation/auth.go b/utils/mock_function/web_experimentation/auth.go new file mode 100644 index 0000000..40d88f4 --- /dev/null +++ b/utils/mock_function/web_experimentation/auth.go @@ -0,0 +1,21 @@ +package web_experimentation + +import ( + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" +) + +var TestAuth = models.Auth{ + Username: "test_auth", + ClientID: "", + ClientSecret: "", + Token: "testAccessToken", + RefreshToken: "testRefreshToken", +} + +func InitMockAuth() { + os.Remove(config.CredentialPath(utils.WEB_EXPERIMENTATION, "test_auth")) +} diff --git a/utils/mock_function/web_experimentation/token.go b/utils/mock_function/web_experimentation/token.go new file mode 100644 index 0000000..64c2a2b --- /dev/null +++ b/utils/mock_function/web_experimentation/token.go @@ -0,0 +1,40 @@ +package web_experimentation + +import ( + "net/http" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/jarcoal/httpmock" +) + +var TestToken = models.TokenWE{ + ClientID: "client_id", + AccountID: "account_id", + ExpiresIn: 0, + Scope: "*", +} + +func APIToken() { + + token := "token" + + testAuthenticationResponse := models.TokenResponse{ + AccessToken: "testAccessToken", + RefreshToken: "testRefreshToken", + } + + httpmock.RegisterResponder("GET", utils.GetHostWebExperimentationAuth()+"/v1/token?access_token="+token, + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestToken) + return resp, nil + }, + ) + + httpmock.RegisterResponder("POST", utils.GetHostWebExperimentationAuth()+"/v1/token", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, testAuthenticationResponse) + return resp, nil + }, + ) +} From c8bf76ad02cadcc4f4033752db98272aae10b0ba Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 5 Apr 2024 13:21:33 +0000 Subject: [PATCH 15/48] Add stdout writer for error messages --- cmd/feature_experimentation/resource/load.go | 8 ++++---- cmd/feature_experimentation/variation/delete.go | 2 +- cmd/feature_experimentation/variation_group/delete.go | 2 +- cmd/web_experimentation/auth/auth_test.go | 2 -- cmd/web_experimentation/auth/login.go | 1 - utils/config/config.go | 4 ++-- utils/functions.go | 4 +++- 7 files changed, 11 insertions(+), 12 deletions(-) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 4a046a9..a129706 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -280,7 +280,7 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { data, err := json.Marshal(resource.Data) if err != nil { - fmt.Printf("error occurred marshal data: %v\n", err) + fmt.Fprintf(os.Stderr, "error occurred marshal data: %v\n", err) } var httpMethod string = "POST" @@ -316,7 +316,7 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { err = json.Unmarshal(data, &resourceData) if err != nil { - fmt.Printf("error occurred unmarshall resourceData: %v\n", err) + fmt.Fprintf(os.Stderr, "error occurred unmarshall resourceData: %v\n", err) } for k, vInterface := range resourceData { @@ -385,11 +385,11 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { err = json.Unmarshal(response, &responseData) if err != nil { - fmt.Printf("error occurred unmarshal responseData: %v\n", err) + fmt.Fprintf(os.Stderr, "error occurred unmarshal responseData: %v\n", err) } if responseData == nil { - fmt.Println("error occurred not response data: " + string(response)) + fmt.Fprintln(os.Stderr, "error occurred not response data: "+string(response)) continue } diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index 0ca2b5c..7edb776 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -30,7 +30,7 @@ func init() { deleteCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the variation you want to delete") if err := deleteCmd.MarkFlagRequired("id"); err != nil { - fmt.Println(err) + fmt.Fprintf(deleteCmd.OutOrStderr(), "error occurred: %s", err) } VariationCmd.AddCommand(deleteCmd) } diff --git a/cmd/feature_experimentation/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go index 2dbc8ce..afc51f8 100644 --- a/cmd/feature_experimentation/variation_group/delete.go +++ b/cmd/feature_experimentation/variation_group/delete.go @@ -30,7 +30,7 @@ func init() { deleteCmd.Flags().StringVarP(&VariationGroupID, "id", "i", "", "id of the variation group you want to delete") if err := deleteCmd.MarkFlagRequired("id"); err != nil { - fmt.Println(err) + fmt.Fprintf(deleteCmd.OutOrStderr(), "error occurred: %s", err) } VariationGroupCmd.AddCommand(deleteCmd) } diff --git a/cmd/web_experimentation/auth/auth_test.go b/cmd/web_experimentation/auth/auth_test.go index 41ca699..3e1d978 100644 --- a/cmd/web_experimentation/auth/auth_test.go +++ b/cmd/web_experimentation/auth/auth_test.go @@ -2,7 +2,6 @@ package auth import ( "encoding/json" - "fmt" "testing" "github.com/flagship-io/flagship/models" @@ -51,7 +50,6 @@ func TestAuthListCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AuthCmd, "list") err := json.Unmarshal([]byte(output), &testAuthList) - fmt.Println(testAuth) assert.Nil(t, err) diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index 8cbfd40..1edb4fb 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -100,7 +100,6 @@ var loginCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) return } - fmt.Println(authenticationResponse) if authenticationResponse.AccessToken == "" { log.Fatal("Credentials not valid.") diff --git a/utils/config/config.go b/utils/config/config.go index 0b333d0..52d3b31 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -69,13 +69,13 @@ func GetUsernames(product string) ([]string, error) { f, err := os.Open(homeDir + "/.flagship/credentials/" + product) if err != nil { - fmt.Println(err) + fmt.Fprintf(os.Stderr, "error occurred: %s", err) return nil, err } files, err := f.Readdir(0) if err != nil { - fmt.Println(err) + fmt.Fprintf(os.Stderr, "error occurred: %s", err) return nil, err } diff --git a/utils/functions.go b/utils/functions.go index f5c1932..e9a190b 100644 --- a/utils/functions.go +++ b/utils/functions.go @@ -3,6 +3,7 @@ package utils import ( "bytes" "fmt" + "os" "github.com/spf13/cobra" ) @@ -24,7 +25,8 @@ func ExecuteCommand(cmd *cobra.Command, args ...string) (output string, err erro err = cmd.Execute() if err != nil { - fmt.Println(err) + fmt.Fprintf(os.Stderr, "error occurred: %s", err) + } return buf.String(), err From e79ee7e77b262ebdbba0157fc12b963ccde95a7f Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 5 Apr 2024 14:17:36 +0000 Subject: [PATCH 16/48] add token cmd and unit test and add viper global instance for analyze flag and fix bug in analyze --- .../analyze/analyze.go | 2 +- .../feature_experimentation.go | 4 ++- cmd/feature_experimentation/info/info.go | 30 ------------------- cmd/feature_experimentation/token/info.go | 14 ++++----- .../token/token_test.go | 18 ++++++++++- utils/config/config.go | 2 +- utils/http_request/common/token.go | 4 +-- .../feature_experimentation/token.go | 2 +- 8 files changed, 30 insertions(+), 46 deletions(-) delete mode 100644 cmd/feature_experimentation/info/info.go diff --git a/cmd/feature_experimentation/analyze/analyze.go b/cmd/feature_experimentation/analyze/analyze.go index 5efa4df..fc52891 100644 --- a/cmd/feature_experimentation/analyze/analyze.go +++ b/cmd/feature_experimentation/analyze/analyze.go @@ -5,7 +5,7 @@ package analyze import ( "github.com/flagship-io/codebase-analyzer/pkg/config" - "github.com/flagship-io/flagship/cmd/feature_experimentation/flag" + "github.com/flagship-io/flagship/cmd/feature_experimentation/analyze/flag" "github.com/spf13/cobra" ) diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index b233e99..596a9bc 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -17,6 +17,7 @@ import ( "github.com/flagship-io/flagship/cmd/feature_experimentation/project" "github.com/flagship-io/flagship/cmd/feature_experimentation/resource" targetingkey "github.com/flagship-io/flagship/cmd/feature_experimentation/targeting_key" + "github.com/flagship-io/flagship/cmd/feature_experimentation/token" "github.com/flagship-io/flagship/cmd/feature_experimentation/user" "github.com/flagship-io/flagship/cmd/feature_experimentation/variation" variationgroup "github.com/flagship-io/flagship/cmd/feature_experimentation/variation_group" @@ -57,6 +58,7 @@ func addSubCommandPalettes() { FeatureExperimentationCmd.AddCommand(resource.ResourceCmd) FeatureExperimentationCmd.AddCommand(auth.AuthCmd) FeatureExperimentationCmd.AddCommand(account.AccountCmd) + FeatureExperimentationCmd.AddCommand(token.TokenCmd) FeatureExperimentationCmd.AddCommand(accountenvironment.AccountEnvironmentCmd) } @@ -72,7 +74,6 @@ func initConfig() { v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION + "/.cli.yaml") v.MergeInConfig() if v.GetString("current_used_credential") != "" { - vL := config.ReadAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("current_used_credential")) v.MergeConfigMap(vL.AllSettings()) } @@ -80,6 +81,7 @@ func initConfig() { v.Unmarshal(&requestConfig) common.Init(requestConfig) resource.Init(requestConfig) + viper.MergeConfigMap(v.AllSettings()) r := &http_request.ResourceRequester diff --git a/cmd/feature_experimentation/info/info.go b/cmd/feature_experimentation/info/info.go deleted file mode 100644 index 83fc9bd..0000000 --- a/cmd/feature_experimentation/info/info.go +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com - -*/ -package info - -import ( - "fmt" - - "github.com/fatih/color" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -// InfoCmd represents the info command -var InfoCmd = &cobra.Command{ - Use: "info", - Short: "Show informations related to your Flagship CLI", - Long: `Show informations like account environment id, account id and client id your Flagship CLI runs on`, - Run: func(cmd *cobra.Command, args []string) { - - yellow := color.New(color.FgYellow).SprintFunc() - - fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", yellow("Account ID"), viper.GetString("account_id")) - fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", yellow("Account environment ID"), viper.GetString("account_environment_id")) - fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", yellow("Client ID"), viper.GetString("client_id")) - fmt.Fprintf(cmd.OutOrStdout(), "%s: %d (in second)\n", yellow("Token expiration"), viper.GetInt("expiration")) - fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", yellow("Token scope"), viper.GetString("scope")) - }, -} diff --git a/cmd/feature_experimentation/token/info.go b/cmd/feature_experimentation/token/info.go index 3ae8065..7ed5f46 100644 --- a/cmd/feature_experimentation/token/info.go +++ b/cmd/feature_experimentation/token/info.go @@ -4,7 +4,6 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package token import ( - "fmt" "log" "github.com/flagship-io/flagship/utils" @@ -19,15 +18,12 @@ var infoCmd = &cobra.Command{ Short: "Get the information related to your token", Long: `Get the information related to your token`, Run: func(cmd *cobra.Command, args []string) { - if viper.GetString("token") != "" { - body, err := common.HTTPCheckToken(viper.GetString("token")) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - utils.FormatItem([]string{"ClientID", "AccountID", "ExpiresIn", "Scope"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) - } else { - fmt.Fprintln(cmd.OutOrStdout(), "Token required") + body, err := common.HTTPCheckToken() + if err != nil { + log.Fatalf("error occurred: %v", err) } + utils.FormatItem([]string{"ClientID", "AccountID", "ExpiresIn", "Scope"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, } diff --git a/cmd/feature_experimentation/token/token_test.go b/cmd/feature_experimentation/token/token_test.go index 0626673..85f128e 100644 --- a/cmd/feature_experimentation/token/token_test.go +++ b/cmd/feature_experimentation/token/token_test.go @@ -1,17 +1,20 @@ package token import ( + "encoding/json" "testing" "github.com/flagship-io/flagship/models" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) -var testToken models.TokenWE +var _testToken models.TokenFE func TestMain(m *testing.M) { @@ -19,9 +22,12 @@ func TestMain(m *testing.M) { defer httpmock.DeactivateAndReset() mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_fe.APIToken() m.Run() } +var testToken models.TokenFE + func TestTokenCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TokenCmd) assert.Contains(t, output, "Manage your token\n") @@ -31,3 +37,13 @@ func TestTokenHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TokenCmd, "--help") assert.Contains(t, output, "Manage your token\n") } + +func TestTokenInfoCommand(t *testing.T) { + successOutput, _ := utils.ExecuteCommand(TokenCmd, "info") + err := json.Unmarshal([]byte(successOutput), &_testToken) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_fe.TestToken, _testToken) + +} diff --git a/utils/config/config.go b/utils/config/config.go index 52d3b31..c00a691 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -111,7 +111,7 @@ func ReadAuth(product, AuthName string) *viper.Viper { v := viper.New() configFilepath := CredentialPath(product, AuthName) if _, err := os.Stat(configFilepath); errors.Is(err, os.ErrNotExist) { - log.Fatalf("error occurred: %v", err) + fmt.Fprintf(os.Stdout, "error occurred: %v \n", err) } v.SetConfigFile(configFilepath) v.MergeInConfig() diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 88eeee9..cec8771 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -209,6 +209,6 @@ func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenRe return authenticationResponse, err } -func HTTPCheckToken(token string) (models.TokenFE, error) { - return HTTPGetItem[models.TokenFE](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + token) +func HTTPCheckToken() (models.TokenFE, error) { + return HTTPGetItem[models.TokenFE](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + cred.Token) } diff --git a/utils/mock_function/feature_experimentation/token.go b/utils/mock_function/feature_experimentation/token.go index 3cfd7ae..74211da 100644 --- a/utils/mock_function/feature_experimentation/token.go +++ b/utils/mock_function/feature_experimentation/token.go @@ -18,7 +18,7 @@ var TestToken = models.TokenFE{ func APIToken() { - token := "token" + token := "access_token" testAuthenticationResponse := models.TokenResponse{ AccessToken: "testAccessToken", From 461a7bc9052207b78ac72e42d602db95de109203 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 8 Apr 2024 08:36:57 +0000 Subject: [PATCH 17/48] add setAccount/AccountEnvId to credential file login method & fix comments --- cmd/feature_experimentation/auth/login.go | 6 +++++- cmd/web_experimentation/auth/login.go | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 0429094..8506a43 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -53,6 +53,10 @@ var loginCmd = &cobra.Command{ } config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) config.SelectAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("username")) + config.SetAccountID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_id")) + if v.GetString("account_environment_id") != "" { + config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_environment_id")) + } fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") return } @@ -68,7 +72,7 @@ var loginCmd = &cobra.Command{ config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) - fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) return } fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (account id)") diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index 1edb4fb..38873af 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -121,7 +121,7 @@ var loginCmd = &cobra.Command{ if slices.Contains(existingCredentials, Username) { config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) - fmt.Fprintln(cmd.OutOrStdout(), "Auth changed successfully to "+Username) + fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) return } From 3d4a427559aa8fa67356378a3c3485a14f6345c0 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 8 Apr 2024 15:20:07 +0000 Subject: [PATCH 18/48] add we campaign test --- .../campaign/campaign_test.go | 65 +++++++++++++ cmd/web_experimentation/campaign/get.go | 10 +- cmd/web_experimentation/campaign/list.go | 2 +- models/web_experimentation/campaign.go | 25 +++-- utils/functions.go | 14 ++- utils/http_request/main_test.go | 3 + .../web_experimentation/campaign.go | 29 ------ .../web_experimentation/campaign_test.go | 93 ++++++------------- .../web_experimentation/main_test.go | 25 +++++ .../feature_experimentation/campaign.go | 2 +- .../feature_experimentation/flag.go | 2 +- .../feature_experimentation/goal.go | 2 +- .../feature_experimentation/project.go | 2 +- .../feature_experimentation/targeting_key.go | 2 +- .../feature_experimentation/user.go | 2 +- .../feature_experimentation/variation.go | 2 +- .../variation_group.go | 2 +- utils/mock_function/request.go | 2 +- .../web_experimentation/campaign.go | 59 ++++++++++++ 19 files changed, 221 insertions(+), 122 deletions(-) create mode 100644 cmd/web_experimentation/campaign/campaign_test.go create mode 100644 utils/http_request/web_experimentation/main_test.go create mode 100644 utils/mock_function/web_experimentation/campaign.go diff --git a/cmd/web_experimentation/campaign/campaign_test.go b/cmd/web_experimentation/campaign/campaign_test.go new file mode 100644 index 0000000..b2a6925 --- /dev/null +++ b/cmd/web_experimentation/campaign/campaign_test.go @@ -0,0 +1,65 @@ +package campaign + +import ( + "encoding/json" + "strconv" + "testing" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_we.APICampaign() + + m.Run() +} + +var testCampaign models.CampaignWE +var testCampaignList []models.CampaignWE + +func TestCampaignCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(CampaignCmd) + assert.Contains(t, output, "Manage your campaigns") +} + +func TestCampaignHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(CampaignCmd, "--help") + assert.Contains(t, output, "Manage your campaigns") +} + +func TestCampaignGetCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(CampaignCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(CampaignCmd, "get", "--id="+strconv.Itoa(100000)) + + err := json.Unmarshal([]byte(successOutput), &testCampaign) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestCampaign, testCampaign) +} + +func TestCampaignListCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(CampaignCmd, "list") + + err := json.Unmarshal([]byte(output), &testCampaignList) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestCampaignlist, testCampaignList) +} diff --git a/cmd/web_experimentation/campaign/get.go b/cmd/web_experimentation/campaign/get.go index e88f4df..f1245d2 100644 --- a/cmd/web_experimentation/campaign/get.go +++ b/cmd/web_experimentation/campaign/get.go @@ -4,12 +4,12 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package campaign import ( - "encoding/json" - "fmt" "log" + "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // getCmd represents get command @@ -22,12 +22,8 @@ var getCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } - jsonBody, err := json.Marshal(body) - if err != nil { - log.Fatalf("error occurred: %v", err) - } + utils.FormatItem([]string{"Id", "Name", "Description", "Type", "State", "Url"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) - fmt.Printf("%s", string(jsonBody)) }, } diff --git a/cmd/web_experimentation/campaign/list.go b/cmd/web_experimentation/campaign/list.go index 855b6dc..8e458dc 100644 --- a/cmd/web_experimentation/campaign/list.go +++ b/cmd/web_experimentation/campaign/list.go @@ -22,7 +22,7 @@ var listCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } - utils.FormatItem([]string{"Id", "Name", "Description", "Type", "State"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"Id", "Name", "Description", "Type", "State", "Url"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/models/web_experimentation/campaign.go b/models/web_experimentation/campaign.go index 01a5edf..37ba55a 100644 --- a/models/web_experimentation/campaign.go +++ b/models/web_experimentation/campaign.go @@ -1,15 +1,22 @@ package web_experimentation type CampaignWE struct { - Id int `json:"id,omitempty"` - Name string `json:"name"` - Url string `json:"url"` - Description string `json:"description"` - Type string `json:"type"` - SubType string `json:"sub_type"` - State string `json:"state"` - Traffic *Traffic `json:"traffic"` - Variations *[]VariationWE `json:"variations"` + Id int `json:"id,omitempty"` + Name string `json:"name"` + Url string `json:"url"` + Description string `json:"description"` + Type string `json:"type"` + SubType string `json:"sub_type"` + State string `json:"state"` + Traffic *Traffic `json:"traffic"` + Variations *[]VariationWE `json:"variations"` + SubTests *[]CampaignWE `json:"sub_tests"` + CreatingDate DateTemplate `json:"created_at"` + Labels []string `json:"labels"` + LastPlayTimestamp DateTemplate `json:"last_play"` + LastPauseTimestamp DateTemplate `json:"last_pause"` + GlobalCodeCampaign string `json:"global_code"` + SourceCode string `json:"source_code"` } type Traffic struct { diff --git a/utils/functions.go b/utils/functions.go index e9a190b..17fd6c3 100644 --- a/utils/functions.go +++ b/utils/functions.go @@ -8,7 +8,7 @@ import ( "github.com/spf13/cobra" ) -type HTTPListResponse[T any] struct { +type HTTPListResponseFE[T any] struct { Items []T `json:"items"` CurrentItemsCount int `json:"current_items_count"` CurrentPage int `json:"current_page"` @@ -17,6 +17,18 @@ type HTTPListResponse[T any] struct { LastPage int `json:"last_page"` } +type HTTPListResponseWE[T any] struct { + Data []T `json:"_data"` + Pagination Pagination `json:"_pagination"` +} + +type Pagination struct { + Total int `json:"_total"` + Pages int `json:"_pages"` + Page int `json:"_page"` + MaxPerPage int `json:"_max_per_page"` +} + func ExecuteCommand(cmd *cobra.Command, args ...string) (output string, err error) { buf := new(bytes.Buffer) cmd.SetOut(buf) diff --git a/utils/http_request/main_test.go b/utils/http_request/main_test.go index 124c595..26ecbe9 100644 --- a/utils/http_request/main_test.go +++ b/utils/http_request/main_test.go @@ -5,6 +5,8 @@ import ( mockfunction "github.com/flagship-io/flagship/utils/mock_function" "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" ) @@ -14,6 +16,7 @@ func TestMain(m *testing.M) { defer httpmock.DeactivateAndReset() feature_experimentation.APIToken() + web_experimentation.APIToken() mockfunction.Request() m.Run() } diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index c332bd4..f59230b 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -1,8 +1,6 @@ package web_experimentation import ( - "net/http" - models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -19,30 +17,3 @@ func (t *CampaignWERequester) HTTPListCampaign() ([]models.CampaignWE, error) { func (t *CampaignWERequester) HTTPGetCampaign(id string) (models.CampaignWE, error) { return common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) } - -func (t *CampaignWERequester) HTTPCreateCampaign(data string) ([]byte, error) { - return common.HTTPRequest[models.CampaignWE](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests", []byte(data)) -} - -func (t *CampaignWERequester) HTTPEditCampaign(id, data string) ([]byte, error) { - return common.HTTPRequest[models.CampaignWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, []byte(data)) -} - -/* func HTTPSwitchCampaign(id, state string) error { - campaignSwitchRequest := models.CampaignSwitchRequest{ - State: state, - } - - campaignSwitchRequestJSON, err := json.Marshal(campaignSwitchRequest) - if err != nil { - return err - } - - _, err = common.HTTPRequest(http.MethodPatch, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+viper.GetString("account_id")+"/account_environments/"+viper.GetString("account_environment_id")+"/campaigns/"+id+"/toggle", campaignSwitchRequestJSON) - return err -} */ - -func (t *CampaignWERequester) HTTPDeleteCampaign(id string) error { - _, err := common.HTTPRequest[models.CampaignWE](http.MethodDelete, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) - return err -} diff --git a/utils/http_request/web_experimentation/campaign_test.go b/utils/http_request/web_experimentation/campaign_test.go index 1cede23..9e02674 100644 --- a/utils/http_request/web_experimentation/campaign_test.go +++ b/utils/http_request/web_experimentation/campaign_test.go @@ -2,84 +2,45 @@ package web_experimentation import ( "testing" -) - -func TestHTTPGetCampaign(t *testing.T) { - /* - respBody, err := HTTPGetCampaign("testCampaignID") - - assert.NotNil(t, respBody) - assert.Nil(t, err) - - assert.Equal(t, "testCampaignID", respBody.Id) - assert.Equal(t, "testCampaignName", respBody.Name) - assert.Equal(t, "testProjectID", respBody.ProjectId) - assert.Equal(t, "testCampaignDescription", respBody.Description) - assert.Equal(t, "toggle", respBody.Type) - */ -} - -func TestHTTPListCampaign(t *testing.T) { - - /* - respBody, err := HTTPListCampaign() - assert.NotNil(t, respBody) - assert.Nil(t, err) + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/stretchr/testify/assert" +) - assert.Equal(t, "testCampaignID", respBody[0].Id) - assert.Equal(t, "testCampaignName", respBody[0].Name) - assert.Equal(t, "testProjectID", respBody[0].ProjectId) - assert.Equal(t, "testCampaignDescription", respBody[0].Description) - assert.Equal(t, "toggle", respBody[0].Type) +var campaignRequester = CampaignWERequester{&common.ResourceRequest{AccountID: "account_id"}} - assert.Equal(t, "testCampaignID1", respBody[1].Id) - assert.Equal(t, "testCampaignName1", respBody[1].Name) - assert.Equal(t, "testProjectID1", respBody[1].ProjectId) - assert.Equal(t, "testCampaignDescription1", respBody[1].Description) - assert.Equal(t, "toggle", respBody[1].Type) - */ -} +func TestHTTPGetCampaign(t *testing.T) { -func TestHTTPCreateCampaign(t *testing.T) { + respBody, err := campaignRequester.HTTPGetCampaign("100000") - /* - dataCampaign := "{\"project_id\":\"testProjectID\",\"name\":\"testCampaignName\",\"description\":\"testCampaignDescription\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" - respBody, err := HTTPCreateCampaign(dataCampaign) + assert.NotNil(t, respBody) + assert.Nil(t, err) - assert.NotNil(t, respBody) - assert.Nil(t, err) + assert.Equal(t, 100000, respBody.Id) + assert.Equal(t, "testCampaignName", respBody.Name) + assert.Equal(t, "console.log(\"Hello World!\")", respBody.GlobalCodeCampaign) + assert.Equal(t, "testCampaignDescription", respBody.Description) + assert.Equal(t, "ab", respBody.Type) - assert.Equal(t, []byte("{\"id\":\"testCampaignID\",\"project_id\":\"testProjectID\",\"name\":\"testCampaignName\",\"description\":\"testCampaignDescription\",\"type\":\"toggle\",\"status\":\"\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"reference\":false,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"key\":\"isVIP\",\"operator\":\"CONTAINS\",\"value\":true}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}"), respBody) - */ } -func TestHTTPEditCampaign(t *testing.T) { - /* - dataCampaign := "{\"project_id\":\"testProjectID1\",\"name\":\"testCampaignName1\",\"description\":\"testCampaignDescription1\",\"type\":\"toggle\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"allocation\":50,\"reference\":true,\"modifications\":{\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"allocation\":50,\"reference\":false,\"modifications\":{\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"operator\":\"CONTAINS\",\"key\":\"isVIP\",\"value\":\"true\"}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}" - - respBody, err := HTTPEditCampaign("testCampaignID", dataCampaign) - - assert.NotNil(t, respBody) - assert.Nil(t, err) - - assert.Equal(t, []byte("{\"id\":\"testCampaignID\",\"project_id\":\"testProjectID1\",\"name\":\"testCampaignName1\",\"description\":\"testCampaignDescription1\",\"type\":\"toggle\",\"status\":\"\",\"variation_groups\":[{\"name\":\"variationGroupName\",\"variations\":[{\"name\":\"My variation 1\",\"reference\":true,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"blue\"}}},{\"name\":\"My variation 2\",\"reference\":false,\"allocation\":50,\"modifications\":{\"type\":\"string\",\"value\":{\"color\":\"red\"}}}],\"targeting\":{\"targeting_groups\":[{\"targetings\":[{\"key\":\"isVIP\",\"operator\":\"CONTAINS\",\"value\":true}]}]}}],\"scheduler\":{\"start_date\":\"2022-02-01 10:00:00\",\"stop_date\":\"2022-02-02 08:00:00\",\"timezone\":\"Europe/Paris\"}}"), respBody) - */ -} +func TestHTTPListCampaign(t *testing.T) { -func TestHTTPDeleteCampaign(t *testing.T) { - /* - err := HTTPDeleteCampaign("testCampaignID") + respBody, err := campaignRequester.HTTPListCampaign() - assert.Nil(t, err) - */ -} + assert.NotNil(t, respBody) + assert.Nil(t, err) -func TestHTTPSwitchCampaign(t *testing.T) { + assert.Equal(t, 100000, respBody[0].Id) + assert.Equal(t, "testCampaignName", respBody[0].Name) + assert.Equal(t, "console.log(\"Hello World!\")", respBody[0].GlobalCodeCampaign) + assert.Equal(t, "testCampaignDescription", respBody[0].Description) + assert.Equal(t, "ab", respBody[0].Type) - /* - err := HTTPSwitchCampaign("testCampaignID", "active") + assert.Equal(t, 100001, respBody[1].Id) + assert.Equal(t, "testCampaignName1", respBody[1].Name) + assert.Equal(t, "console.log(\"Hello Earth!\")", respBody[1].GlobalCodeCampaign) + assert.Equal(t, "testCampaignDescription1", respBody[1].Description) + assert.Equal(t, "ab", respBody[1].Type) - assert.Nil(t, err) - */ } diff --git a/utils/http_request/web_experimentation/main_test.go b/utils/http_request/web_experimentation/main_test.go new file mode 100644 index 0000000..d983b31 --- /dev/null +++ b/utils/http_request/web_experimentation/main_test.go @@ -0,0 +1,25 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + mockfunction "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + + mockfunction_ "github.com/flagship-io/flagship/utils/mock_function" + + "github.com/jarcoal/httpmock" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + common.Init(mockfunction_.Auth) + + mockfunction.APICampaign() + mockfunction.APIToken() + + m.Run() +} diff --git a/utils/mock_function/feature_experimentation/campaign.go b/utils/mock_function/feature_experimentation/campaign.go index 6722b38..da5e06e 100644 --- a/utils/mock_function/feature_experimentation/campaign.go +++ b/utils/mock_function/feature_experimentation/campaign.go @@ -97,7 +97,7 @@ var TestCampaignlist = []models.CampaignFE{ func APICampaign() { - resp := utils.HTTPListResponse[models.CampaignFE]{ + resp := utils.HTTPListResponseFE[models.CampaignFE]{ Items: TestCampaignlist, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/flag.go b/utils/mock_function/feature_experimentation/flag.go index 64a3330..e370996 100644 --- a/utils/mock_function/feature_experimentation/flag.go +++ b/utils/mock_function/feature_experimentation/flag.go @@ -40,7 +40,7 @@ var TestFlagList = []models.Flag{ func APIFlag() { - resp := utils.HTTPListResponse[models.Flag]{ + resp := utils.HTTPListResponseFE[models.Flag]{ Items: TestFlagList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/goal.go b/utils/mock_function/feature_experimentation/goal.go index adb905e..8320f56 100644 --- a/utils/mock_function/feature_experimentation/goal.go +++ b/utils/mock_function/feature_experimentation/goal.go @@ -40,7 +40,7 @@ var TestGoalList = []models.Goal{ func APIGoal() { - resp := utils.HTTPListResponse[models.Goal]{ + resp := utils.HTTPListResponseFE[models.Goal]{ Items: TestGoalList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/project.go b/utils/mock_function/feature_experimentation/project.go index 4be44e3..3f849e6 100644 --- a/utils/mock_function/feature_experimentation/project.go +++ b/utils/mock_function/feature_experimentation/project.go @@ -30,7 +30,7 @@ var TestProjectList = []models.Project{ } func APIProject() { - resp := utils.HTTPListResponse[models.Project]{ + resp := utils.HTTPListResponseFE[models.Project]{ Items: TestProjectList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/targeting_key.go b/utils/mock_function/feature_experimentation/targeting_key.go index ebc9b05..baa1fe5 100644 --- a/utils/mock_function/feature_experimentation/targeting_key.go +++ b/utils/mock_function/feature_experimentation/targeting_key.go @@ -37,7 +37,7 @@ var TestTargetingKeyList = []models.TargetingKey{ func APITargetingKey() { - resp := utils.HTTPListResponse[models.TargetingKey]{ + resp := utils.HTTPListResponseFE[models.TargetingKey]{ Items: TestTargetingKeyList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/user.go b/utils/mock_function/feature_experimentation/user.go index a0c7817..f1db504 100644 --- a/utils/mock_function/feature_experimentation/user.go +++ b/utils/mock_function/feature_experimentation/user.go @@ -25,7 +25,7 @@ func APIUser() { email := "example@abtasty.com" - resp := utils.HTTPListResponse[models.User]{ + resp := utils.HTTPListResponseFE[models.User]{ Items: TestUserList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/variation.go b/utils/mock_function/feature_experimentation/variation.go index 69ca492..1f7a382 100644 --- a/utils/mock_function/feature_experimentation/variation.go +++ b/utils/mock_function/feature_experimentation/variation.go @@ -52,7 +52,7 @@ func APIVariation() { campaignID := "campaignID" variationGroupID := "variationGroupID" - resp := utils.HTTPListResponse[models.VariationFE]{ + resp := utils.HTTPListResponseFE[models.VariationFE]{ Items: TestVariationList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/feature_experimentation/variation_group.go b/utils/mock_function/feature_experimentation/variation_group.go index afec9d5..8a8b160 100644 --- a/utils/mock_function/feature_experimentation/variation_group.go +++ b/utils/mock_function/feature_experimentation/variation_group.go @@ -67,7 +67,7 @@ func APIVariationGroup() { campaignID := "campaignID" - resp := utils.HTTPListResponse[models.VariationGroup]{ + resp := utils.HTTPListResponseFE[models.VariationGroup]{ Items: TestVariationGroupList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/request.go b/utils/mock_function/request.go index c255323..c5c7fcc 100644 --- a/utils/mock_function/request.go +++ b/utils/mock_function/request.go @@ -42,7 +42,7 @@ func Request() { testRequestList := []TestRequest{testRequest, testRequest1} - resp := utils.HTTPListResponse[TestRequest]{ + resp := utils.HTTPListResponseFE[TestRequest]{ Items: testRequestList, CurrentItemsCount: 2, CurrentPage: 1, diff --git a/utils/mock_function/web_experimentation/campaign.go b/utils/mock_function/web_experimentation/campaign.go new file mode 100644 index 0000000..cd758b9 --- /dev/null +++ b/utils/mock_function/web_experimentation/campaign.go @@ -0,0 +1,59 @@ +package web_experimentation + +import ( + "net/http" + "strconv" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/jarcoal/httpmock" +) + +var TestCampaign = models.CampaignWE{ + Id: 100000, + Name: "testCampaignName", + Description: "testCampaignDescription", + Type: "ab", + GlobalCodeCampaign: "console.log(\"Hello World!\")", +} + +var TestCampaign1 = models.CampaignWE{ + Id: 100001, + Name: "testCampaignName1", + Description: "testCampaignDescription1", + Type: "ab", + GlobalCodeCampaign: "console.log(\"Hello Earth!\")", +} + +var TestCampaignlist = []models.CampaignWE{ + TestCampaign, + TestCampaign1, +} + +func APICampaign() { + + respList := utils.HTTPListResponseWE[models.CampaignWE]{ + Data: TestCampaignlist, + Pagination: utils.Pagination{ + Total: 1, + Pages: 2, + MaxPerPage: 10, + Page: 1, + }, + } + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestCampaign) + return resp, nil + }, + ) + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, respList) + return resp, nil + }, + ) +} From a1576108fc31190a083847228df81183033c8d62 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 9 Apr 2024 08:27:45 +0000 Subject: [PATCH 19/48] add flag for redirect uri for browser auth login in WE --- cmd/web_experimentation/auth/login.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index 38873af..ad0d5ee 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -20,9 +20,10 @@ import ( ) var ( - browser bool - password string - totp string + browser bool + password string + redirectUri string + totp string ) func checkSingleFlag(bool1, bool2 bool) bool { @@ -105,6 +106,7 @@ var loginCmd = &cobra.Command{ log.Fatal("Credentials not valid.") } // Waiting for fix to implemente route to get username "/users/me" + // add flag for redirect uri (for vscode etc...) fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") return @@ -152,8 +154,9 @@ func init() { loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of an auth") loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of an auth") - loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "Generate link for browser") + loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "generate link for browser") loginCmd.Flags().StringVarP(&Username, "username", "u", "", "username") + loginCmd.Flags().StringVarP(&redirectUri, "redirect-uri", "", "http://abtasty.com", "redirect uri") loginCmd.Flags().StringVarP(&password, "password", "", "", "password") loginCmd.Flags().StringVarP(&totp, "totp", "", "", "totp") @@ -170,7 +173,7 @@ func handleCallback(w http.ResponseWriter, r *http.Request, codeChan chan<- stri codeChan <- code - http.Redirect(w, r, "http://abtasty.com", http.StatusSeeOther) + http.Redirect(w, r, redirectUri, http.StatusSeeOther) go func() { time.Sleep(5 * time.Second) From 2631484c99d668c3ea4986824dedab189aa799fd Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 11 Apr 2024 12:48:06 +0000 Subject: [PATCH 20/48] add variation/campaign/account global code & renaming/fixes --- cmd/feature_experimentation/account/use.go | 4 +- .../account_environment/use.go | 4 +- .../account-global-code.go | 19 ++++++++ .../account-global-code/get.go | 39 +++++++++++++++ cmd/web_experimentation/account/use.go | 4 +- .../campaign-global-code.go | 19 ++++++++ cmd/web_experimentation/global_code/list.go | 11 ++--- .../variation-global-code/get.go | 47 +++++++++++++++++++ .../variation-global-code.go | 38 +++++++++++++++ cmd/web_experimentation/variation/get.go | 15 +++--- .../variation/variation.go | 6 +-- .../web_experimentation.go | 6 +++ models/web_experimentation/account.go | 14 ++++-- .../{vatiation.go => variation.go} | 24 ++++++++++ utils/http_request/main.go | 4 +- .../account-global-code.go | 16 +++++++ .../campaign-global-code.go | 16 +++++++ .../variation-global-code.go | 16 +++++++ .../web_experimentation/variation.go | 3 +- 19 files changed, 272 insertions(+), 33 deletions(-) create mode 100644 cmd/web_experimentation/account-global-code/account-global-code.go create mode 100644 cmd/web_experimentation/account-global-code/get.go create mode 100644 cmd/web_experimentation/campaign-global-code/campaign-global-code.go create mode 100644 cmd/web_experimentation/variation-global-code/get.go create mode 100644 cmd/web_experimentation/variation-global-code/variation-global-code.go rename models/web_experimentation/{vatiation.go => variation.go} (55%) create mode 100644 utils/http_request/web_experimentation/account-global-code.go create mode 100644 utils/http_request/web_experimentation/campaign-global-code.go create mode 100644 utils/http_request/web_experimentation/variation-global-code.go diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index 7c34ff4..31d856c 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -31,9 +31,9 @@ var useCmd = &cobra.Command{ } func init() { - useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to manage") + useCmd.Flags().StringVarP(&AccountID, "id", "i", "", "account id of the credentials you want to manage") - if err := useCmd.MarkFlagRequired("account-id"); err != nil { + if err := useCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } AccountCmd.AddCommand(useCmd) diff --git a/cmd/feature_experimentation/account_environment/use.go b/cmd/feature_experimentation/account_environment/use.go index 01609c1..701ec0f 100644 --- a/cmd/feature_experimentation/account_environment/use.go +++ b/cmd/feature_experimentation/account_environment/use.go @@ -31,9 +31,9 @@ var useCmd = &cobra.Command{ } func init() { - useCmd.Flags().StringVarP(&AccountEnvironmentID, "account-environment-id", "e", "", "account env id of the credentials you want to manage") + useCmd.Flags().StringVarP(&AccountEnvironmentID, "id", "i", "", "account env id of the credentials you want to manage") - if err := useCmd.MarkFlagRequired("account-environment-id"); err != nil { + if err := useCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } AccountEnvironmentCmd.AddCommand(useCmd) diff --git a/cmd/web_experimentation/account-global-code/account-global-code.go b/cmd/web_experimentation/account-global-code/account-global-code.go new file mode 100644 index 0000000..5e374f2 --- /dev/null +++ b/cmd/web_experimentation/account-global-code/account-global-code.go @@ -0,0 +1,19 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account_global_code + +import ( + "github.com/spf13/cobra" +) + +// AccountGlobalCodeCmd represents the account global code command +var AccountGlobalCodeCmd = &cobra.Command{ + Use: "account-global-code [get]", + Short: "Get account global code", + Aliases: []string{"agc"}, + Long: `Get account global code of your account`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/account-global-code/get.go b/cmd/web_experimentation/account-global-code/get.go new file mode 100644 index 0000000..9aba9e4 --- /dev/null +++ b/cmd/web_experimentation/account-global-code/get.go @@ -0,0 +1,39 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account_global_code + +import ( + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var accountID string + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ]", + Short: "Get global account code", + Long: `Get global account code from your account`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.AccountGlobalCodeRequester.HTTPGetAccountGlobalCode(accountID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), body) + + }, +} + +func init() { + getCmd.Flags().StringVarP(&accountID, "id", "i", "", "id of the global code account you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + AccountGlobalCodeCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index 188b881..a329eb8 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -31,9 +31,9 @@ var useCmd = &cobra.Command{ } func init() { - useCmd.Flags().StringVarP(&AccountID, "account-id", "a", "", "account id of the credentials you want to manage") + useCmd.Flags().StringVarP(&AccountID, "id", "i", "", "account id of the credentials you want to manage") - if err := useCmd.MarkFlagRequired("account-id"); err != nil { + if err := useCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } AccountCmd.AddCommand(useCmd) diff --git a/cmd/web_experimentation/campaign-global-code/campaign-global-code.go b/cmd/web_experimentation/campaign-global-code/campaign-global-code.go new file mode 100644 index 0000000..e32a0f9 --- /dev/null +++ b/cmd/web_experimentation/campaign-global-code/campaign-global-code.go @@ -0,0 +1,19 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign_global_code + +import ( + "github.com/spf13/cobra" +) + +// CampaignGlobalCodeCmd represents the campaign global code command +var CampaignGlobalCodeCmd = &cobra.Command{ + Use: "campaign-global-code [get]", + Short: "Get campaign global code", + Aliases: []string{"cgc"}, + Long: `Get campaign global code from your account`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/global_code/list.go b/cmd/web_experimentation/global_code/list.go index cdb9e4a..fa4c1c8 100644 --- a/cmd/web_experimentation/global_code/list.go +++ b/cmd/web_experimentation/global_code/list.go @@ -4,12 +4,12 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package global_code import ( - "encoding/json" - "fmt" "log" + "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // listCmd represents the list command @@ -23,12 +23,7 @@ var listCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - jsonBody, err := json.Marshal(body) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - fmt.Printf("%s", string(jsonBody)) + utils.FormatItem([]string{"Id", "Code"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) }, } diff --git a/cmd/web_experimentation/variation-global-code/get.go b/cmd/web_experimentation/variation-global-code/get.go new file mode 100644 index 0000000..9569626 --- /dev/null +++ b/cmd/web_experimentation/variation-global-code/get.go @@ -0,0 +1,47 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +type ModificationGlobalCode struct { + JS string `json:"js,omitempty"` + CSS string `json:"css,omitempty"` +} + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ] [--test-id ]", + Short: "Get variation global code", + Long: `Get variation global code in your account`, + Run: func(cmd *cobra.Command, args []string) { + var modificationResp ModificationGlobalCode + body, err := httprequest.ModificationRequester.HTTPGetModification(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == VariationID && modification.Type == "customScriptNew" { + modificationResp.JS = modification.Value + } + if modification.VariationID == VariationID && modification.Type == "addCSS" { + modificationResp.CSS = modification.Value + } + } + + utils.FormatItem([]string{"JS", "CSS"}, modificationResp, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + VariationGlobalCodeCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/variation-global-code/variation-global-code.go b/cmd/web_experimentation/variation-global-code/variation-global-code.go new file mode 100644 index 0000000..3de0bc7 --- /dev/null +++ b/cmd/web_experimentation/variation-global-code/variation-global-code.go @@ -0,0 +1,38 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "log" + + "github.com/spf13/cobra" +) + +var CampaignID string +var VariationID int + +// VariationGlobalCodeCmd represents the variation global code command +var VariationGlobalCodeCmd = &cobra.Command{ + Use: "variation-global-code [get]", + Short: "Get variable global code", + Aliases: []string{"vgc"}, + Long: `Get variable global code from your account`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func init() { + getCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := getCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } +} diff --git a/cmd/web_experimentation/variation/get.go b/cmd/web_experimentation/variation/get.go index da8eb54..7b25e79 100644 --- a/cmd/web_experimentation/variation/get.go +++ b/cmd/web_experimentation/variation/get.go @@ -4,12 +4,12 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package variation import ( - "encoding/json" - "fmt" "log" + "github.com/flagship-io/flagship/utils" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // getCmd represents the get command @@ -18,21 +18,18 @@ var getCmd = &cobra.Command{ Short: "Get a variation", Long: `Get a variation in your campaign`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.VariationWERequester.HTTPGetVariation(TestID, VariationID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - jsonBody, err := json.Marshal(body) + body, err := httprequest.VariationWERequester.HTTPGetVariation(CampaignID, VariationID) if err != nil { log.Fatalf("error occurred: %v", err) } - fmt.Printf("%s", string(jsonBody)) + utils.FormatItem([]string{"Id", "Name", "Description", "Type", "Traffic"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, } func init() { - getCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the variation group you want to display") + getCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the variation you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation/variation.go b/cmd/web_experimentation/variation/variation.go index a5aa120..19546fe 100644 --- a/cmd/web_experimentation/variation/variation.go +++ b/cmd/web_experimentation/variation/variation.go @@ -12,7 +12,7 @@ import ( ) var ( - TestID int + CampaignID int VariationID int ) @@ -27,9 +27,9 @@ var VariationCmd = &cobra.Command{ } func init() { - VariationCmd.PersistentFlags().IntVarP(&TestID, "test-id", "", 0, "id of the campaign where you want to manage your variation group") + VariationCmd.PersistentFlags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the campaign where you want to manage your variation") - if err := VariationCmd.MarkPersistentFlagRequired("test-id"); err != nil { + if err := VariationCmd.MarkPersistentFlagRequired("campaign-id"); err != nil { log.Fatalf("error occurred: %v", err) } } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 67b6076..2cd2eaf 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -7,10 +7,13 @@ import ( "os" "github.com/flagship-io/flagship/cmd/web_experimentation/account" + account_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/account-global-code" "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" + campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign-global-code" "github.com/flagship-io/flagship/cmd/web_experimentation/global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" + variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation-global-code" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/flagship-io/flagship/utils/http_request" @@ -40,6 +43,9 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(variation.VariationCmd) WebExperimentationCmd.AddCommand(auth.AuthCmd) WebExperimentationCmd.AddCommand(account.AccountCmd) + WebExperimentationCmd.AddCommand(campaign_global_code.CampaignGlobalCodeCmd) + WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) + WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) } func init() { diff --git a/models/web_experimentation/account.go b/models/web_experimentation/account.go index 03d5b84..e805253 100644 --- a/models/web_experimentation/account.go +++ b/models/web_experimentation/account.go @@ -1,8 +1,14 @@ package web_experimentation type AccountWE struct { - Id int `json:"id,omitempty"` - Name string `json:"name"` - Identifier string `json:"identifier"` - Role string `json:"role"` + Id int `json:"id,omitempty"` + Name string `json:"name"` + Identifier string `json:"identifier"` + Role string `json:"role"` + GlobalCode GlobalCode_ `json:"global_code"` +} + +type GlobalCode_ struct { + OnDomReady bool `json:"on_dom_ready"` + Value string `json:"value"` } diff --git a/models/web_experimentation/vatiation.go b/models/web_experimentation/variation.go similarity index 55% rename from models/web_experimentation/vatiation.go rename to models/web_experimentation/variation.go index 072bea1..4485f13 100644 --- a/models/web_experimentation/vatiation.go +++ b/models/web_experimentation/variation.go @@ -22,3 +22,27 @@ type Component struct { Form string `json:"form"` Options string `json:"options"` } + +type Modification struct { + Id int `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Value string `json:"value"` + VariationID int `json:"variation_id"` + UpdatedBy UpdatedBy_ `json:"updated_by"` + UpdatedAt DateTemplate `json:"updated_at"` +} + +type UpdatedBy_ struct { + Id int `json:"id"` + Email string `json:"email"` +} + +type ModificationWE struct { + GlobalModifications []Modification `json:"global_modifications"` + Modifications []Modification `json:"modifications"` +} + +type ModificationDataWE struct { + Data ModificationWE `json:"_data"` +} diff --git a/utils/http_request/main.go b/utils/http_request/main.go index 23277fc..a341f5f 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -27,8 +27,10 @@ var VariationFERequester feature_experimentation.VariationFERequester = feature_ var PanicRequester feature_experimentation.PanicRequester = feature_experimentation.PanicRequester{ResourceRequest: &ResourceRequester} // web experimentation - var CampaignWERequester web_experimentation.CampaignWERequester = web_experimentation.CampaignWERequester{ResourceRequest: &ResourceRequester} var GlobalCodeRequester web_experimentation.GlobalCodeRequester = web_experimentation.GlobalCodeRequester{ResourceRequest: &ResourceRequester} var AccountWERequester web_experimentation.AccountWERequester = web_experimentation.AccountWERequester{ResourceRequest: &ResourceRequester} var VariationWERequester web_experimentation.VariationWERequester = web_experimentation.VariationWERequester{ResourceRequest: &ResourceRequester} +var CampaignGlobalCodeRequester web_experimentation.CampaignGlobalCodeRequester = web_experimentation.CampaignGlobalCodeRequester{ResourceRequest: &ResourceRequester} +var AccountGlobalCodeRequester web_experimentation.AccountGlobalCodeRequester = web_experimentation.AccountGlobalCodeRequester{ResourceRequest: &ResourceRequester} +var ModificationRequester web_experimentation.ModificationRequester = web_experimentation.ModificationRequester{ResourceRequest: &ResourceRequester} diff --git a/utils/http_request/web_experimentation/account-global-code.go b/utils/http_request/web_experimentation/account-global-code.go new file mode 100644 index 0000000..51bbe15 --- /dev/null +++ b/utils/http_request/web_experimentation/account-global-code.go @@ -0,0 +1,16 @@ +package web_experimentation + +import ( + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request/common" +) + +type AccountGlobalCodeRequester struct { + *common.ResourceRequest +} + +func (a *AccountGlobalCodeRequester) HTTPGetAccountGlobalCode(id string) (string, error) { + resp, err := common.HTTPGetItem[models.AccountWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + id) + return resp.GlobalCode.Value, err +} diff --git a/utils/http_request/web_experimentation/campaign-global-code.go b/utils/http_request/web_experimentation/campaign-global-code.go new file mode 100644 index 0000000..1782567 --- /dev/null +++ b/utils/http_request/web_experimentation/campaign-global-code.go @@ -0,0 +1,16 @@ +package web_experimentation + +import ( + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request/common" +) + +type CampaignGlobalCodeRequester struct { + *common.ResourceRequest +} + +func (c *CampaignGlobalCodeRequester) HTTPGetCampaignGlobalCode(id string) (string, error) { + resp, err := common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + c.AccountID + "/tests/" + id) + return resp.GlobalCodeCampaign, err +} diff --git a/utils/http_request/web_experimentation/variation-global-code.go b/utils/http_request/web_experimentation/variation-global-code.go new file mode 100644 index 0000000..fceb887 --- /dev/null +++ b/utils/http_request/web_experimentation/variation-global-code.go @@ -0,0 +1,16 @@ +package web_experimentation + +import ( + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request/common" +) + +type ModificationRequester struct { + *common.ResourceRequest +} + +func (m *ModificationRequester) HTTPGetModification(id string) ([]models.Modification, error) { + resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + id + "/modifications") + return resp.Data.Modifications, err +} diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go index 3521f54..465a0b4 100644 --- a/utils/http_request/web_experimentation/variation.go +++ b/utils/http_request/web_experimentation/variation.go @@ -6,7 +6,6 @@ import ( models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" - "github.com/spf13/viper" ) type VariationWERequester struct { @@ -14,5 +13,5 @@ type VariationWERequester struct { } func (v *VariationWERequester) HTTPGetVariation(testID, id int) (models.VariationWE, error) { - return common.HTTPGetItem[models.VariationWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + viper.GetString("account_id") + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) + return common.HTTPGetItem[models.VariationWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + v.AccountID + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) } From df51094754dd8ae95147433edd50ac6ef0198df0 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 11 Apr 2024 13:05:14 +0000 Subject: [PATCH 21/48] fix long desc commands --- .../account/current.go | 2 +- cmd/feature_experimentation/account/use.go | 2 +- .../account_environment/current.go | 2 +- cmd/feature_experimentation/auth/get.go | 2 +- cmd/feature_experimentation/auth/list.go | 2 +- .../campaign/create.go | 2 +- .../campaign/delete.go | 2 +- cmd/feature_experimentation/campaign/edit.go | 2 +- cmd/feature_experimentation/campaign/get.go | 2 +- .../campaign/switch.go | 2 +- .../feature_experimentation.go | 2 +- cmd/feature_experimentation/flag/create.go | 2 +- cmd/feature_experimentation/flag/delete.go | 2 +- cmd/feature_experimentation/flag/edit.go | 2 +- cmd/feature_experimentation/flag/flag.go | 3 +- cmd/feature_experimentation/flag/get.go | 2 +- cmd/feature_experimentation/flag/list.go | 2 +- cmd/feature_experimentation/goal/create.go | 2 +- cmd/feature_experimentation/goal/delete.go | 2 +- cmd/feature_experimentation/goal/edit.go | 2 +- cmd/feature_experimentation/goal/get.go | 2 +- cmd/feature_experimentation/goal/goal.go | 3 +- cmd/feature_experimentation/goal/list.go | 2 +- cmd/feature_experimentation/panic/panic.go | 2 +- cmd/feature_experimentation/project/create.go | 2 +- cmd/feature_experimentation/project/delete.go | 2 +- cmd/feature_experimentation/project/edit.go | 2 +- cmd/feature_experimentation/project/get.go | 2 +- cmd/feature_experimentation/project/list.go | 2 +- cmd/feature_experimentation/project/switch.go | 2 +- .../targeting_key/create.go | 2 +- .../targeting_key/delete.go | 2 +- .../targeting_key/edit.go | 2 +- .../targeting_key/get.go | 2 +- .../targeting_key/list.go | 2 +- .../targeting_key/targeting_key.go | 3 +- cmd/feature_experimentation/user/create.go | 2 +- cmd/feature_experimentation/user/delete.go | 2 +- cmd/feature_experimentation/user/edit.go | 2 +- cmd/feature_experimentation/user/list.go | 2 +- .../variation/create.go | 2 +- .../variation/delete.go | 2 +- cmd/feature_experimentation/variation/edit.go | 2 +- cmd/feature_experimentation/variation/get.go | 2 +- cmd/feature_experimentation/variation/list.go | 2 +- .../variation/variation.go | 2 +- .../variation_group/create.go | 2 +- .../variation_group/delete.go | 2 +- .../variation_group/edit.go | 2 +- .../variation_group/get.go | 2 +- .../variation_group/list.go | 2 +- .../variation_group/variation_group.go | 2 +- .../account-global-code.go | 2 +- .../account-global-code/get.go | 2 +- cmd/web_experimentation/account/current.go | 2 +- cmd/web_experimentation/account/list.go | 2 +- cmd/web_experimentation/account/use.go | 2 +- cmd/web_experimentation/auth/get.go | 2 +- cmd/web_experimentation/auth/list.go | 2 +- .../campaign-global-code.go | 2 +- .../campaign-global-code/get.go | 39 +++++++++++++++++++ cmd/web_experimentation/campaign/get.go | 8 ++-- .../variation-global-code/get.go | 2 +- .../variation-global-code.go | 2 +- cmd/web_experimentation/variation/get.go | 2 +- .../variation/variation.go | 2 +- .../web_experimentation.go | 4 +- 67 files changed, 109 insertions(+), 73 deletions(-) create mode 100644 cmd/web_experimentation/campaign-global-code/get.go diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index c6381d2..797b8a5 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -19,7 +19,7 @@ import ( var currentCmd = &cobra.Command{ Use: "current", Short: "current an auth credential", - Long: `current an auth credential from your system`, + Long: `current an auth credential`, Run: func(cmd *cobra.Command, args []string) { var accountYaml models.AccountYaml diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index 31d856c..87b2279 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -16,7 +16,7 @@ import ( var useCmd = &cobra.Command{ Use: "use", Short: "get an auth credential", - Long: `list an auth credential from your system`, + Long: `list an auth credential`, Run: func(cmd *cobra.Command, args []string) { if AccountID == "" { fmt.Fprintln(cmd.OutOrStderr(), "required flag account-id") diff --git a/cmd/feature_experimentation/account_environment/current.go b/cmd/feature_experimentation/account_environment/current.go index 2cc0bea..4afc191 100644 --- a/cmd/feature_experimentation/account_environment/current.go +++ b/cmd/feature_experimentation/account_environment/current.go @@ -19,7 +19,7 @@ import ( var currentCmd = &cobra.Command{ Use: "current", Short: "current an auth credential", - Long: `current an auth credential from your system`, + Long: `current an auth credential`, Run: func(cmd *cobra.Command, args []string) { var accountYaml models.AccountYaml diff --git a/cmd/feature_experimentation/auth/get.go b/cmd/feature_experimentation/auth/get.go index 97f6801..5545d39 100644 --- a/cmd/feature_experimentation/auth/get.go +++ b/cmd/feature_experimentation/auth/get.go @@ -19,7 +19,7 @@ import ( var getCmd = &cobra.Command{ Use: "get", Short: "get an auth credential for feature experimentation", - Long: `get an auth credential for feature experimentation from your system`, + Long: `get an auth credential for feature experimentation`, Run: func(cmd *cobra.Command, args []string) { var authYaml models.AuthYaml diff --git a/cmd/feature_experimentation/auth/list.go b/cmd/feature_experimentation/auth/list.go index ff6409a..fda5543 100644 --- a/cmd/feature_experimentation/auth/list.go +++ b/cmd/feature_experimentation/auth/list.go @@ -19,7 +19,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "list all auth", - Long: `list all auth from your system`, + Long: `list all auth`, Run: func(cmd *cobra.Command, args []string) { var auths []models.Auth diff --git a/cmd/feature_experimentation/campaign/create.go b/cmd/feature_experimentation/campaign/create.go index 9054376..6d30fb8 100644 --- a/cmd/feature_experimentation/campaign/create.go +++ b/cmd/feature_experimentation/campaign/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [-d | --data-raw=]", Short: "Create a campaign", - Long: `Create a campaign in your project`, + Long: `Create a campaign`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.CampaignFERequester.HTTPCreateCampaign(DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/campaign/delete.go b/cmd/feature_experimentation/campaign/delete.go index 947705a..c0589c5 100644 --- a/cmd/feature_experimentation/campaign/delete.go +++ b/cmd/feature_experimentation/campaign/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-i | --id=]", Short: "Delete a campaign", - Long: `Delete a campaign in your project`, + Long: `Delete a campaign`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.CampaignFERequester.HTTPDeleteCampaign(CampaignID) if err != nil { diff --git a/cmd/feature_experimentation/campaign/edit.go b/cmd/feature_experimentation/campaign/edit.go index b141cd1..12cd681 100644 --- a/cmd/feature_experimentation/campaign/edit.go +++ b/cmd/feature_experimentation/campaign/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-i | --id=] [ -d | --data-raw=]", Short: "Edit a campaign", - Long: `Edit a campaign in your project`, + Long: `Edit a campaign`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.CampaignFERequester.HTTPEditCampaign(CampaignID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/campaign/get.go b/cmd/feature_experimentation/campaign/get.go index a146133..8a09aa6 100644 --- a/cmd/feature_experimentation/campaign/get.go +++ b/cmd/feature_experimentation/campaign/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [-i | --id=]", Short: "Get a campaign", - Long: `Get a campaign in your project`, + Long: `Get a campaign`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.CampaignFERequester.HTTPGetCampaign(CampaignID) if err != nil { diff --git a/cmd/feature_experimentation/campaign/switch.go b/cmd/feature_experimentation/campaign/switch.go index 5219fe2..53cccf4 100644 --- a/cmd/feature_experimentation/campaign/switch.go +++ b/cmd/feature_experimentation/campaign/switch.go @@ -15,7 +15,7 @@ import ( var SwitchCmd = &cobra.Command{ Use: "switch [-i | --id=] [-s | --status=]", Short: "Switch a campaign state", - Long: `Switch a campaign state in your project`, + Long: `Switch a campaign state`, Run: func(cmd *cobra.Command, args []string) { if !(Status == "active" || Status == "paused" || Status == "interrupted") { fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 3 values: active or paused or interrupted") diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 596a9bc..1742ca5 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -32,7 +32,7 @@ import ( // FeatureExperimentationCmd represents the feature experimentation command var FeatureExperimentationCmd = &cobra.Command{ - Use: "feature-experimentation [project|campaign|flag|goal|targeting-key|variation-group|variation]", + Use: "feature-experimentation [auth|account|account-environment|project|campaign|flag|goal|targeting-key|variation-group|variation]", Aliases: []string{"feature-experimentation", "feature-exp", "fe", "feat-exp"}, Short: "Manage resources related to the feature experimentation product", Long: `Manage resources related to the feature experimentation product in your account`, diff --git a/cmd/feature_experimentation/flag/create.go b/cmd/feature_experimentation/flag/create.go index 6450f8a..d4338ce 100644 --- a/cmd/feature_experimentation/flag/create.go +++ b/cmd/feature_experimentation/flag/create.go @@ -17,7 +17,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [--name --type --default-value --description --predefined-values | -d | --data-raw ]", Short: "Create a flag", - Long: `Create a flag in your account`, + Long: `Create a flag`, Run: func(cmd *cobra.Command, args []string) { var data string var predefinedValues_ []string diff --git a/cmd/feature_experimentation/flag/delete.go b/cmd/feature_experimentation/flag/delete.go index 0223909..6a0f18f 100644 --- a/cmd/feature_experimentation/flag/delete.go +++ b/cmd/feature_experimentation/flag/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-i | --id=]", Short: "Delete a flag", - Long: `Delete a flag in your account`, + Long: `Delete a flag`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.FlagRequester.HTTPDeleteFlag(FlagID) if err != nil { diff --git a/cmd/feature_experimentation/flag/edit.go b/cmd/feature_experimentation/flag/edit.go index 511482f..8d07b76 100644 --- a/cmd/feature_experimentation/flag/edit.go +++ b/cmd/feature_experimentation/flag/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-i | --id=] [-d | --data-raw ]", Short: "Edit a flag", - Long: `Edit a flag in your account`, + Long: `Edit a flag`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.FlagRequester.HTTPEditFlag(FlagID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/flag/flag.go b/cmd/feature_experimentation/flag/flag.go index 96875d4..5935bdf 100644 --- a/cmd/feature_experimentation/flag/flag.go +++ b/cmd/feature_experimentation/flag/flag.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package flag @@ -22,7 +21,7 @@ var ( var FlagCmd = &cobra.Command{ Use: "flag [create|edit|get|list|delete|usage]", Short: "Manage your flags", - Long: `Manage your flags in your account`, + Long: `Manage your flags`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/feature_experimentation/flag/get.go b/cmd/feature_experimentation/flag/get.go index a63f590..9e419d2 100644 --- a/cmd/feature_experimentation/flag/get.go +++ b/cmd/feature_experimentation/flag/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [-i | --id=]", Short: "Get a flag", - Long: `Get a flag in your account`, + Long: `Get a flag`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.FlagRequester.HTTPGetFlag(FlagID) if err != nil { diff --git a/cmd/feature_experimentation/flag/list.go b/cmd/feature_experimentation/flag/list.go index 38e86f0..36d1106 100644 --- a/cmd/feature_experimentation/flag/list.go +++ b/cmd/feature_experimentation/flag/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all flags", - Long: `List all flags in your account`, + Long: `List all flags`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.FlagRequester.HTTPListFlag() if err != nil { diff --git a/cmd/feature_experimentation/goal/create.go b/cmd/feature_experimentation/goal/create.go index 1542d06..084b74a 100644 --- a/cmd/feature_experimentation/goal/create.go +++ b/cmd/feature_experimentation/goal/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [-d | --data-raw ]", Short: "Create a goal", - Long: `Create a goal in your account`, + Long: `Create a goal`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.GoalRequester.HTTPCreateGoal(DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/goal/delete.go b/cmd/feature_experimentation/goal/delete.go index e9b0599..776037f 100644 --- a/cmd/feature_experimentation/goal/delete.go +++ b/cmd/feature_experimentation/goal/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-i | --id=]", Short: "Delete a flag", - Long: `Delete a flag in your account`, + Long: `Delete a flag`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.GoalRequester.HTTPDeleteGoal(GoalID) if err != nil { diff --git a/cmd/feature_experimentation/goal/edit.go b/cmd/feature_experimentation/goal/edit.go index 675dc39..0636e13 100644 --- a/cmd/feature_experimentation/goal/edit.go +++ b/cmd/feature_experimentation/goal/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-i | --id=] [-d | --data-raw ]", Short: "Edit a goal", - Long: `Edit a goal in your account`, + Long: `Edit a goal`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.GoalRequester.HTTPEditGoal(GoalID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/goal/get.go b/cmd/feature_experimentation/goal/get.go index d4c8a5a..673afda 100644 --- a/cmd/feature_experimentation/goal/get.go +++ b/cmd/feature_experimentation/goal/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [-i | --id=]", Short: "Get a goal", - Long: `Get a goal in your account`, + Long: `Get a goal`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.GoalRequester.HTTPGetGoal(GoalID) if err != nil { diff --git a/cmd/feature_experimentation/goal/goal.go b/cmd/feature_experimentation/goal/goal.go index 9cbfe12..3cb6a66 100644 --- a/cmd/feature_experimentation/goal/goal.go +++ b/cmd/feature_experimentation/goal/goal.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package goal @@ -17,7 +16,7 @@ var ( var GoalCmd = &cobra.Command{ Use: "goal [create|edit|get|list|delete]", Short: "Manage your goals", - Long: `Manage your goals in your account`, + Long: `Manage your goals`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/feature_experimentation/goal/list.go b/cmd/feature_experimentation/goal/list.go index 5148433..2631a82 100644 --- a/cmd/feature_experimentation/goal/list.go +++ b/cmd/feature_experimentation/goal/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all goals", - Long: `List all goals in your account`, + Long: `List all goals`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.GoalRequester.HTTPListGoal() if err != nil { diff --git a/cmd/feature_experimentation/panic/panic.go b/cmd/feature_experimentation/panic/panic.go index 9814cdb..65705f2 100644 --- a/cmd/feature_experimentation/panic/panic.go +++ b/cmd/feature_experimentation/panic/panic.go @@ -17,7 +17,7 @@ var panicStatus string var PanicCmd = &cobra.Command{ Use: "panic", Short: "Manage panic mode", - Long: `Manage panic mode in your account`, + Long: `Manage panic mode`, Run: func(cmd *cobra.Command, args []string) { if !(panicStatus == "on" || panicStatus == "off") { fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 2 values: on or off ") diff --git a/cmd/feature_experimentation/project/create.go b/cmd/feature_experimentation/project/create.go index ffa3d85..3147b3c 100644 --- a/cmd/feature_experimentation/project/create.go +++ b/cmd/feature_experimentation/project/create.go @@ -17,7 +17,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [-n | --name=]", Short: "Create a project", - Long: `Create a project in your account`, + Long: `Create a project`, Run: func(cmd *cobra.Command, args []string) { projectRequest := models.Project{ Name: ProjectName, diff --git a/cmd/feature_experimentation/project/delete.go b/cmd/feature_experimentation/project/delete.go index 7503d60..f5f6dcf 100644 --- a/cmd/feature_experimentation/project/delete.go +++ b/cmd/feature_experimentation/project/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-i | --id=]", Short: "Delete a project", - Long: `Delete a project in your account`, + Long: `Delete a project`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.ProjectRequester.HTTPDeleteProject(ProjectId) if err != nil { diff --git a/cmd/feature_experimentation/project/edit.go b/cmd/feature_experimentation/project/edit.go index e82070f..dcd05b7 100644 --- a/cmd/feature_experimentation/project/edit.go +++ b/cmd/feature_experimentation/project/edit.go @@ -17,7 +17,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-i | --id=] [-n | --name=]", Short: "Edit a project", - Long: `Edit a project in your account`, + Long: `Edit a project`, Run: func(cmd *cobra.Command, args []string) { projectRequest := models.Project{ Name: ProjectName, diff --git a/cmd/feature_experimentation/project/get.go b/cmd/feature_experimentation/project/get.go index d67f13b..08eb5a1 100644 --- a/cmd/feature_experimentation/project/get.go +++ b/cmd/feature_experimentation/project/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [-i | --id=]", Short: "Get a project", - Long: `Get a project in your account`, + Long: `Get a project`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.ProjectRequester.HTTPGetProject(ProjectId) if err != nil { diff --git a/cmd/feature_experimentation/project/list.go b/cmd/feature_experimentation/project/list.go index ac6bb0d..a727399 100644 --- a/cmd/feature_experimentation/project/list.go +++ b/cmd/feature_experimentation/project/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all projects", - Long: `List all projects in your account`, + Long: `List all projects`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.ProjectRequester.HTTPListProject() if err != nil { diff --git a/cmd/feature_experimentation/project/switch.go b/cmd/feature_experimentation/project/switch.go index edb1bd9..fb8b68f 100644 --- a/cmd/feature_experimentation/project/switch.go +++ b/cmd/feature_experimentation/project/switch.go @@ -15,7 +15,7 @@ import ( var switchCmd = &cobra.Command{ Use: "switch [-i | --id=] [-s | --status=]", Short: "switch a project state", - Long: `switch a project state in your account`, + Long: `switch a project state`, Run: func(cmd *cobra.Command, args []string) { if !(ProjectStatus == "active" || ProjectStatus == "paused" || ProjectStatus == "interrupted") { fmt.Fprintln(cmd.OutOrStdout(), "Status can only have 3 values: active or paused or interrupted") diff --git a/cmd/feature_experimentation/targeting_key/create.go b/cmd/feature_experimentation/targeting_key/create.go index b5a629e..cfffd69 100644 --- a/cmd/feature_experimentation/targeting_key/create.go +++ b/cmd/feature_experimentation/targeting_key/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [-d | --data-raw ]", Short: "Create a targeting key", - Long: `Create a targeting key in your account`, + Long: `Create a targeting key`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.TargetingKeyRequester.HTTPCreateTargetingKey(DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/delete.go b/cmd/feature_experimentation/targeting_key/delete.go index d1bea81..bc07e15 100644 --- a/cmd/feature_experimentation/targeting_key/delete.go +++ b/cmd/feature_experimentation/targeting_key/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-i | --id=]", Short: "Delete a targeting key", - Long: `Delete a targeting key in your account`, + Long: `Delete a targeting key`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.TargetingKeyRequester.HTTPDeleteTargetingKey(TargetingKeyID) if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/edit.go b/cmd/feature_experimentation/targeting_key/edit.go index f80b80a..36d0bbc 100644 --- a/cmd/feature_experimentation/targeting_key/edit.go +++ b/cmd/feature_experimentation/targeting_key/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-i | --id=] [-d | --data-raw ]", Short: "Edit a targeting key", - Long: `Edit a targeting key in your account`, + Long: `Edit a targeting key`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.TargetingKeyRequester.HTTPEditTargetingKey(TargetingKeyID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/get.go b/cmd/feature_experimentation/targeting_key/get.go index bfd3e18..4ccfa8c 100644 --- a/cmd/feature_experimentation/targeting_key/get.go +++ b/cmd/feature_experimentation/targeting_key/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [-i | --id=]", Short: "Get a targeting key", - Long: `Get a targeting key in your account`, + Long: `Get a targeting key`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.TargetingKeyRequester.HTTPGetTargetingKey(TargetingKeyID) if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/list.go b/cmd/feature_experimentation/targeting_key/list.go index afd70ac..34ae103 100644 --- a/cmd/feature_experimentation/targeting_key/list.go +++ b/cmd/feature_experimentation/targeting_key/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all targeting keys", - Long: `List all targeting keys in your account`, + Long: `List all targeting keys`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.TargetingKeyRequester.HTTPListTargetingKey() if err != nil { diff --git a/cmd/feature_experimentation/targeting_key/targeting_key.go b/cmd/feature_experimentation/targeting_key/targeting_key.go index e685edc..f1b3dd4 100644 --- a/cmd/feature_experimentation/targeting_key/targeting_key.go +++ b/cmd/feature_experimentation/targeting_key/targeting_key.go @@ -1,6 +1,5 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com - */ package targetingkey @@ -16,7 +15,7 @@ var TargetingKeyCmd = &cobra.Command{ Use: "targeting-key [create|edit|get|list|delete]", Aliases: []string{"tk"}, Short: "Manage your targeting keys", - Long: `Manage your targeting keys in your account`, + Long: `Manage your targeting keys`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/feature_experimentation/user/create.go b/cmd/feature_experimentation/user/create.go index bd921a4..4416a4e 100644 --- a/cmd/feature_experimentation/user/create.go +++ b/cmd/feature_experimentation/user/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [-d | --data ]", Short: "Create a user with right", - Long: `Create a user with right in your account`, + Long: `Create a user with right`, Run: func(cmd *cobra.Command, args []string) { _, err := httprequest.UserRequester.HTTPBatchUpdateUsers(DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/user/delete.go b/cmd/feature_experimentation/user/delete.go index 3d6bb4d..533a421 100644 --- a/cmd/feature_experimentation/user/delete.go +++ b/cmd/feature_experimentation/user/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [-e | --email ]", Short: "Delete a user", - Long: `Delete a user in your account`, + Long: `Delete a user`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.UserRequester.HTTPDeleteUsers(UserEmail) if err != nil { diff --git a/cmd/feature_experimentation/user/edit.go b/cmd/feature_experimentation/user/edit.go index 0f5c851..4aec696 100644 --- a/cmd/feature_experimentation/user/edit.go +++ b/cmd/feature_experimentation/user/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [-d | --data-raw=]", Short: "Edit a user with right", - Long: `Edit a user with right in your account`, + Long: `Edit a user with right`, Run: func(cmd *cobra.Command, args []string) { _, err := httprequest.UserRequester.HTTPBatchUpdateUsers(DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/user/list.go b/cmd/feature_experimentation/user/list.go index 0be71e5..2732972 100644 --- a/cmd/feature_experimentation/user/list.go +++ b/cmd/feature_experimentation/user/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "List all users", - Long: `List all users in your account`, + Long: `List all users`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.UserRequester.HTTPListUsers() if err != nil { diff --git a/cmd/feature_experimentation/variation/create.go b/cmd/feature_experimentation/variation/create.go index 580ebca..29e5cfd 100644 --- a/cmd/feature_experimentation/variation/create.go +++ b/cmd/feature_experimentation/variation/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [--campaign-id=] [--variation-group-id=] [-d | --data-raw ]", Short: "Create a variation", - Long: `Create a variation in your variation group`, + Long: `Create a variation`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationFERequester.HTTPCreateVariation(CampaignID, VariationGroupID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/variation/delete.go b/cmd/feature_experimentation/variation/delete.go index 7edb776..1ea13e3 100644 --- a/cmd/feature_experimentation/variation/delete.go +++ b/cmd/feature_experimentation/variation/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [--campaign-id=] [--variation-group-id=] [-i | --id=]", Short: "Delete a variation", - Long: `Delete a variation in your variation group`, + Long: `Delete a variation`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.VariationFERequester.HTTPDeleteVariation(CampaignID, VariationGroupID, VariationID) if err != nil { diff --git a/cmd/feature_experimentation/variation/edit.go b/cmd/feature_experimentation/variation/edit.go index 81d01b9..3105155 100644 --- a/cmd/feature_experimentation/variation/edit.go +++ b/cmd/feature_experimentation/variation/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [--campaign-id=] [--variation-group-id=] [-i | --id=] [-d | --data-raw=]", Short: "Edit a variation", - Long: `Edit a variation in your variation group`, + Long: `Edit a variation`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationFERequester.HTTPEditVariation(CampaignID, VariationGroupID, VariationID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/variation/get.go b/cmd/feature_experimentation/variation/get.go index ba9ebe1..431ec6c 100644 --- a/cmd/feature_experimentation/variation/get.go +++ b/cmd/feature_experimentation/variation/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [--campaign-id=] [--variation-group-id=] [-i | --id=]", Short: "Get a variation", - Long: `Get a variation in your variation group`, + Long: `Get a variation`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationFERequester.HTTPGetVariation(CampaignID, VariationGroupID, VariationID) if err != nil { diff --git a/cmd/feature_experimentation/variation/list.go b/cmd/feature_experimentation/variation/list.go index bd25fa3..1a5e3c8 100644 --- a/cmd/feature_experimentation/variation/list.go +++ b/cmd/feature_experimentation/variation/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list [--campaign-id=] [--variation-group-id=]", Short: "List all variations", - Long: `List all variations in your variation group`, + Long: `List all variations`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationFERequester.HTTPListVariation(CampaignID, VariationGroupID) if err != nil { diff --git a/cmd/feature_experimentation/variation/variation.go b/cmd/feature_experimentation/variation/variation.go index 6f46c26..8727e0f 100644 --- a/cmd/feature_experimentation/variation/variation.go +++ b/cmd/feature_experimentation/variation/variation.go @@ -22,7 +22,7 @@ var ( var VariationCmd = &cobra.Command{ Use: "variation [create|edit|get|list|delete]", Short: "Manage your variations", - Long: `Manage your variations in your variation group`, + Long: `Manage your variations`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/feature_experimentation/variation_group/create.go b/cmd/feature_experimentation/variation_group/create.go index 9de2fad..a30d67c 100644 --- a/cmd/feature_experimentation/variation_group/create.go +++ b/cmd/feature_experimentation/variation_group/create.go @@ -15,7 +15,7 @@ import ( var createCmd = &cobra.Command{ Use: "create [--campaign-id=] [-d | --data-raw ]", Short: "Create a variation group", - Long: `Create a variation group in your campaign`, + Long: `Create a variation group`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationGroupRequester.HTTPCreateVariationGroup(CampaignID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/variation_group/delete.go b/cmd/feature_experimentation/variation_group/delete.go index afc51f8..cc8d771 100644 --- a/cmd/feature_experimentation/variation_group/delete.go +++ b/cmd/feature_experimentation/variation_group/delete.go @@ -15,7 +15,7 @@ import ( var deleteCmd = &cobra.Command{ Use: "delete [--campaign-id=] [-i | --id ]", Short: "Delete a variation group", - Long: `Delete a variation group in your campaign`, + Long: `Delete a variation group`, Run: func(cmd *cobra.Command, args []string) { err := httprequest.VariationGroupRequester.HTTPDeleteVariationGroup(CampaignID, VariationGroupID) if err != nil { diff --git a/cmd/feature_experimentation/variation_group/edit.go b/cmd/feature_experimentation/variation_group/edit.go index 8357866..940d092 100644 --- a/cmd/feature_experimentation/variation_group/edit.go +++ b/cmd/feature_experimentation/variation_group/edit.go @@ -15,7 +15,7 @@ import ( var editCmd = &cobra.Command{ Use: "edit [--campaign-id=] [-i | --id ] [-d | --data-raw ]", Short: "Edit a variation group", - Long: `Edit a variation group in your campaign`, + Long: `Edit a variation group`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationGroupRequester.HTTPEditVariationGroup(CampaignID, VariationGroupID, DataRaw) if err != nil { diff --git a/cmd/feature_experimentation/variation_group/get.go b/cmd/feature_experimentation/variation_group/get.go index 28aed92..76274c9 100644 --- a/cmd/feature_experimentation/variation_group/get.go +++ b/cmd/feature_experimentation/variation_group/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [--campaign-id=] [-i | --id ]", Short: "Get a variation group", - Long: `Get a variation group in your campaign`, + Long: `Get a variation group`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationGroupRequester.HTTPGetVariationGroup(CampaignID, VariationGroupID) if err != nil { diff --git a/cmd/feature_experimentation/variation_group/list.go b/cmd/feature_experimentation/variation_group/list.go index 83691ff..d211fd5 100644 --- a/cmd/feature_experimentation/variation_group/list.go +++ b/cmd/feature_experimentation/variation_group/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list [--campaign-id=]", Short: "List all variation groups", - Long: `List all variation groups in your campaign`, + Long: `List all variation groups`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationGroupRequester.HTTPListVariationGroup(CampaignID) if err != nil { diff --git a/cmd/feature_experimentation/variation_group/variation_group.go b/cmd/feature_experimentation/variation_group/variation_group.go index 0da0de2..b44ba50 100644 --- a/cmd/feature_experimentation/variation_group/variation_group.go +++ b/cmd/feature_experimentation/variation_group/variation_group.go @@ -22,7 +22,7 @@ var VariationGroupCmd = &cobra.Command{ Use: "variation-group [create|edit|get|list|delete]", Aliases: []string{"vg"}, Short: "Manage your variation groups", - Long: `Manage your variation groups in your campaign`, + Long: `Manage your variation groups`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/account-global-code/account-global-code.go b/cmd/web_experimentation/account-global-code/account-global-code.go index 5e374f2..343415b 100644 --- a/cmd/web_experimentation/account-global-code/account-global-code.go +++ b/cmd/web_experimentation/account-global-code/account-global-code.go @@ -12,7 +12,7 @@ var AccountGlobalCodeCmd = &cobra.Command{ Use: "account-global-code [get]", Short: "Get account global code", Aliases: []string{"agc"}, - Long: `Get account global code of your account`, + Long: `Get account global code`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/account-global-code/get.go b/cmd/web_experimentation/account-global-code/get.go index 9aba9e4..fadd154 100644 --- a/cmd/web_experimentation/account-global-code/get.go +++ b/cmd/web_experimentation/account-global-code/get.go @@ -17,7 +17,7 @@ var accountID string var getCmd = &cobra.Command{ Use: "get [-i | --id ]", Short: "Get global account code", - Long: `Get global account code from your account`, + Long: `Get global account code`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.AccountGlobalCodeRequester.HTTPGetAccountGlobalCode(accountID) if err != nil { diff --git a/cmd/web_experimentation/account/current.go b/cmd/web_experimentation/account/current.go index 52737e4..c3df613 100644 --- a/cmd/web_experimentation/account/current.go +++ b/cmd/web_experimentation/account/current.go @@ -19,7 +19,7 @@ import ( var currentCmd = &cobra.Command{ Use: "current", Short: "current an auth credential", - Long: `current an auth credential from your system`, + Long: `current an auth credential`, Run: func(cmd *cobra.Command, args []string) { var accountYaml models.AccountYaml diff --git a/cmd/web_experimentation/account/list.go b/cmd/web_experimentation/account/list.go index 66d7ae0..5aef9a8 100644 --- a/cmd/web_experimentation/account/list.go +++ b/cmd/web_experimentation/account/list.go @@ -16,7 +16,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "list all auth", - Long: `list all auth from your system`, + Long: `list all auth`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.AccountWERequester.HTTPListAccount() diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index a329eb8..b50bbd6 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -16,7 +16,7 @@ import ( var useCmd = &cobra.Command{ Use: "use", Short: "get an auth credential", - Long: `list an auth credential from your system`, + Long: `list an auth credential`, Run: func(cmd *cobra.Command, args []string) { if AccountID == "" { fmt.Fprintln(cmd.OutOrStdout(), "required flag account-id") diff --git a/cmd/web_experimentation/auth/get.go b/cmd/web_experimentation/auth/get.go index d05d01a..d0269bb 100644 --- a/cmd/web_experimentation/auth/get.go +++ b/cmd/web_experimentation/auth/get.go @@ -19,7 +19,7 @@ import ( var getCmd = &cobra.Command{ Use: "get", Short: "get an auth credential for web experimentation", - Long: `get an auth credential for web experimentation from your system`, + Long: `get an auth credential for web experimentation`, Run: func(cmd *cobra.Command, args []string) { var authYaml models.AuthYaml diff --git a/cmd/web_experimentation/auth/list.go b/cmd/web_experimentation/auth/list.go index a61e253..b4c037a 100644 --- a/cmd/web_experimentation/auth/list.go +++ b/cmd/web_experimentation/auth/list.go @@ -19,7 +19,7 @@ import ( var listCmd = &cobra.Command{ Use: "list", Short: "list all auth", - Long: `list all auth from your system`, + Long: `list all auth`, Run: func(cmd *cobra.Command, args []string) { var auths []models.Auth diff --git a/cmd/web_experimentation/campaign-global-code/campaign-global-code.go b/cmd/web_experimentation/campaign-global-code/campaign-global-code.go index e32a0f9..cb13cb4 100644 --- a/cmd/web_experimentation/campaign-global-code/campaign-global-code.go +++ b/cmd/web_experimentation/campaign-global-code/campaign-global-code.go @@ -12,7 +12,7 @@ var CampaignGlobalCodeCmd = &cobra.Command{ Use: "campaign-global-code [get]", Short: "Get campaign global code", Aliases: []string{"cgc"}, - Long: `Get campaign global code from your account`, + Long: `Get campaign global code`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/campaign-global-code/get.go b/cmd/web_experimentation/campaign-global-code/get.go new file mode 100644 index 0000000..3e02b09 --- /dev/null +++ b/cmd/web_experimentation/campaign-global-code/get.go @@ -0,0 +1,39 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign_global_code + +import ( + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var campaignID string + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ]", + Short: "Get campaign global code", + Long: `Get campaign global code`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.CampaignGlobalCodeRequester.HTTPGetCampaignGlobalCode(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), body) + + }, +} + +func init() { + getCmd.Flags().StringVarP(&campaignID, "id", "i", "", "id of the global code campaign you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + CampaignGlobalCodeCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/campaign/get.go b/cmd/web_experimentation/campaign/get.go index f1245d2..4a3df36 100644 --- a/cmd/web_experimentation/campaign/get.go +++ b/cmd/web_experimentation/campaign/get.go @@ -14,9 +14,9 @@ import ( // getCmd represents get command var getCmd = &cobra.Command{ - Use: "get [-i | --id ]", - Short: "Get a test", - Long: `Get a test in your account`, + Use: "get [-i | --id ]", + Short: "Get a campaign", + Long: `Get a campaign`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.CampaignWERequester.HTTPGetCampaign(CampaignID) if err != nil { @@ -28,7 +28,7 @@ var getCmd = &cobra.Command{ } func init() { - getCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the test you want to display") + getCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the campaign you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation-global-code/get.go b/cmd/web_experimentation/variation-global-code/get.go index 9569626..90235c8 100644 --- a/cmd/web_experimentation/variation-global-code/get.go +++ b/cmd/web_experimentation/variation-global-code/get.go @@ -21,7 +21,7 @@ type ModificationGlobalCode struct { var getCmd = &cobra.Command{ Use: "get [-i | --id ] [--test-id ]", Short: "Get variation global code", - Long: `Get variation global code in your account`, + Long: `Get variation global code`, Run: func(cmd *cobra.Command, args []string) { var modificationResp ModificationGlobalCode body, err := httprequest.ModificationRequester.HTTPGetModification(CampaignID) diff --git a/cmd/web_experimentation/variation-global-code/variation-global-code.go b/cmd/web_experimentation/variation-global-code/variation-global-code.go index 3de0bc7..632e51b 100644 --- a/cmd/web_experimentation/variation-global-code/variation-global-code.go +++ b/cmd/web_experimentation/variation-global-code/variation-global-code.go @@ -17,7 +17,7 @@ var VariationGlobalCodeCmd = &cobra.Command{ Use: "variation-global-code [get]", Short: "Get variable global code", Aliases: []string{"vgc"}, - Long: `Get variable global code from your account`, + Long: `Get variable global code`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/variation/get.go b/cmd/web_experimentation/variation/get.go index 7b25e79..876f4c4 100644 --- a/cmd/web_experimentation/variation/get.go +++ b/cmd/web_experimentation/variation/get.go @@ -16,7 +16,7 @@ import ( var getCmd = &cobra.Command{ Use: "get [--test-id=] [-i= | --id=]", Short: "Get a variation", - Long: `Get a variation in your campaign`, + Long: `Get a variation`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.VariationWERequester.HTTPGetVariation(CampaignID, VariationID) if err != nil { diff --git a/cmd/web_experimentation/variation/variation.go b/cmd/web_experimentation/variation/variation.go index 19546fe..baa6a16 100644 --- a/cmd/web_experimentation/variation/variation.go +++ b/cmd/web_experimentation/variation/variation.go @@ -20,7 +20,7 @@ var ( var VariationCmd = &cobra.Command{ Use: "variation [create|edit|get|delete]", Short: "Manage your variation", - Long: `Manage your variation in your test`, + Long: `Manage your variation`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 2cd2eaf..4cb91ca 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -25,10 +25,10 @@ import ( // WebExperimentationCmd represents the web experimentation command var WebExperimentationCmd = &cobra.Command{ - Use: "web-experimentation [campaign]", + Use: "web-experimentation [auth|account|campaign|global-code|variation]", Aliases: []string{"web-experimentation", "web-exp", "we"}, Short: "Manage resources related to the feature experimentation product", - Long: `Manage resources related to the feature experimentation product in your account`, + Long: `Manage resources related to the feature experimentation product`, PersistentPreRun: func(cmd *cobra.Command, args []string) { initConfig() }, From 8063b730bd01c092dd4f682bbe1a5c573ac2e47f Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 11 Apr 2024 13:11:40 +0000 Subject: [PATCH 22/48] fix test --- cmd/feature_experimentation/account/account_test.go | 4 ++-- .../account_environment/account_environment_test.go | 4 ++-- cmd/feature_experimentation/flag/flag_test.go | 4 ++-- cmd/feature_experimentation/goal/goal_test.go | 4 ++-- .../targeting_key/targeting_key_test.go | 4 ++-- cmd/feature_experimentation/variation/variation_test.go | 4 ++-- .../variation_group/variation_group_test.go | 4 ++-- cmd/web_experimentation/account/account_test.go | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cmd/feature_experimentation/account/account_test.go b/cmd/feature_experimentation/account/account_test.go index b4e1224..7a907dd 100644 --- a/cmd/feature_experimentation/account/account_test.go +++ b/cmd/feature_experimentation/account/account_test.go @@ -42,9 +42,9 @@ func TestAccountHelpCommand(t *testing.T) { func TestAccountUseCommand(t *testing.T) { failOutput, _ := utils.ExecuteCommand(AccountCmd, "use") - assert.Contains(t, failOutput, "Error: required flag(s) \"account-id\" not set") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") - successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-a=account_id") + successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-i=account_id") assert.Equal(t, "Account ID set to : account_id\n", successOutput) } diff --git a/cmd/feature_experimentation/account_environment/account_environment_test.go b/cmd/feature_experimentation/account_environment/account_environment_test.go index d438bb4..b9f3581 100644 --- a/cmd/feature_experimentation/account_environment/account_environment_test.go +++ b/cmd/feature_experimentation/account_environment/account_environment_test.go @@ -42,9 +42,9 @@ func TestAccountEnvironmentHelpCommand(t *testing.T) { func TestAccountEnvironmentUseCommand(t *testing.T) { failOutput, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "use") - assert.Contains(t, failOutput, "Error: required flag(s) \"account-environment-id\" not set") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") - successOutput, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "use", "--account-environment-id=account_environment_id") + successOutput, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "use", "--id=account_environment_id") assert.Equal(t, "Account Environment ID set to : account_environment_id\n", successOutput) } diff --git a/cmd/feature_experimentation/flag/flag_test.go b/cmd/feature_experimentation/flag/flag_test.go index e2fd743..9849f3a 100644 --- a/cmd/feature_experimentation/flag/flag_test.go +++ b/cmd/feature_experimentation/flag/flag_test.go @@ -29,12 +29,12 @@ var testFlagList []models.Flag func TestFlagCommand(t *testing.T) { output, _ := utils.ExecuteCommand(FlagCmd) - assert.Contains(t, output, "Manage your flags in your account") + assert.Contains(t, output, "Manage your flags") } func TestFlagHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(FlagCmd, "--help") - assert.Contains(t, output, "Manage your flags in your account") + assert.Contains(t, output, "Manage your flags") } func TestFlagGetCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/goal/goal_test.go b/cmd/feature_experimentation/goal/goal_test.go index c9652e4..4dfd296 100644 --- a/cmd/feature_experimentation/goal/goal_test.go +++ b/cmd/feature_experimentation/goal/goal_test.go @@ -30,12 +30,12 @@ var testGoalList []models.Goal func TestGoalCommand(t *testing.T) { output, _ := utils.ExecuteCommand(GoalCmd) - assert.Contains(t, output, "Manage your goals in your account") + assert.Contains(t, output, "Manage your goals") } func TestGoalHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(GoalCmd, "--help") - assert.Contains(t, output, "Manage your goals in your account") + assert.Contains(t, output, "Manage your goals") } func TestGoalGetCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/targeting_key/targeting_key_test.go b/cmd/feature_experimentation/targeting_key/targeting_key_test.go index 057e21e..6bb704b 100644 --- a/cmd/feature_experimentation/targeting_key/targeting_key_test.go +++ b/cmd/feature_experimentation/targeting_key/targeting_key_test.go @@ -30,12 +30,12 @@ var testTargetingKeyList []models.TargetingKey func TestTargetingKeyCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TargetingKeyCmd) - assert.Contains(t, output, "Manage your targeting keys in your account") + assert.Contains(t, output, "Manage your targeting keys") } func TestTargetingKeyHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TargetingKeyCmd, "--help") - assert.Contains(t, output, "Manage your targeting keys in your account") + assert.Contains(t, output, "Manage your targeting keys") } func TestTargetingKeyGetCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/variation/variation_test.go b/cmd/feature_experimentation/variation/variation_test.go index 61d75a2..73b135c 100644 --- a/cmd/feature_experimentation/variation/variation_test.go +++ b/cmd/feature_experimentation/variation/variation_test.go @@ -33,12 +33,12 @@ func TestVariationCommand(t *testing.T) { assert.Contains(t, output, "Error: required flag(s) \"campaign-id\", \"variation-group-id\" not set") output1, _ := utils.ExecuteCommand(VariationCmd, "--campaign-id=campaignID", "--variation-group-id=variationGroupID") - assert.Contains(t, output1, "Manage your variations in your variation group") + assert.Contains(t, output1, "Manage your variations") } func TestVariationHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(VariationCmd, "--help") - assert.Contains(t, output, "Manage your variations in your variation group") + assert.Contains(t, output, "Manage your variations") } func TestVariationGetCommand(t *testing.T) { diff --git a/cmd/feature_experimentation/variation_group/variation_group_test.go b/cmd/feature_experimentation/variation_group/variation_group_test.go index 1324147..1062743 100644 --- a/cmd/feature_experimentation/variation_group/variation_group_test.go +++ b/cmd/feature_experimentation/variation_group/variation_group_test.go @@ -33,12 +33,12 @@ func TestVariationGroupCommand(t *testing.T) { assert.Contains(t, output, "Error: required flag(s) \"campaign-id\" not set") output1, _ := utils.ExecuteCommand(VariationGroupCmd, "--campaign-id=campaignID") - assert.Contains(t, output1, "Manage your variation groups in your campaign") + assert.Contains(t, output1, "Manage your variation groups") } func TestVariationGroupHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(VariationGroupCmd, "--help") - assert.Contains(t, output, "Manage your variation groups in your campaign") + assert.Contains(t, output, "Manage your variation groups") } func TestVariationGroupGetCommand(t *testing.T) { diff --git a/cmd/web_experimentation/account/account_test.go b/cmd/web_experimentation/account/account_test.go index 5eeaac5..4299e77 100644 --- a/cmd/web_experimentation/account/account_test.go +++ b/cmd/web_experimentation/account/account_test.go @@ -42,9 +42,9 @@ func TestAccountHelpCommand(t *testing.T) { func TestAccountUseCommand(t *testing.T) { failOutput, _ := utils.ExecuteCommand(AccountCmd, "use") - assert.Contains(t, failOutput, "Error: required flag(s) \"account-id\" not set") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") - successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-a=account_id") + successOutput, _ := utils.ExecuteCommand(AccountCmd, "use", "-i=account_id") assert.Equal(t, "Account ID set to : account_id\n", successOutput) } From 668a9c2728d878f2e80768ee7b88404bef78c9ce Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 15 Apr 2024 09:22:54 +0200 Subject: [PATCH 23/48] fix error sdt and renaming and add some test --- .../account_global_code.go} | 0 .../account_global_code_test.go | 43 +++++++++++++++ .../get.go | 0 .../campaign_global_code.go} | 0 .../campaign_global_code_test.go | 43 +++++++++++++++ .../get.go | 0 .../global_code/global_code.go | 18 ------- cmd/web_experimentation/global_code/list.go | 33 ------------ .../variation/variation_test.go | 52 +++++++++++++++++++ .../get.go | 2 +- .../variation_global_code.go} | 0 .../variation_global_code_test.go | 43 +++++++++++++++ .../web_experimentation.go | 8 ++- utils/config/config.go | 2 +- utils/http_request/main.go | 1 - .../web_experimentation/global_code.go | 19 ------- .../web_experimentation/account.go | 34 +++++++++++- .../web_experimentation/modification.go | 47 +++++++++++++++++ .../web_experimentation/variation.go | 28 ++++++++++ 19 files changed, 293 insertions(+), 80 deletions(-) rename cmd/web_experimentation/{account-global-code/account-global-code.go => account_global_code/account_global_code.go} (100%) create mode 100644 cmd/web_experimentation/account_global_code/account_global_code_test.go rename cmd/web_experimentation/{account-global-code => account_global_code}/get.go (100%) rename cmd/web_experimentation/{campaign-global-code/campaign-global-code.go => campaign_global_code/campaign_global_code.go} (100%) create mode 100644 cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go rename cmd/web_experimentation/{campaign-global-code => campaign_global_code}/get.go (100%) delete mode 100644 cmd/web_experimentation/global_code/global_code.go delete mode 100644 cmd/web_experimentation/global_code/list.go create mode 100644 cmd/web_experimentation/variation/variation_test.go rename cmd/web_experimentation/{variation-global-code => variation_global_code}/get.go (93%) rename cmd/web_experimentation/{variation-global-code/variation-global-code.go => variation_global_code/variation_global_code.go} (100%) create mode 100644 cmd/web_experimentation/variation_global_code/variation_global_code_test.go delete mode 100644 utils/http_request/web_experimentation/global_code.go create mode 100644 utils/mock_function/web_experimentation/modification.go create mode 100644 utils/mock_function/web_experimentation/variation.go diff --git a/cmd/web_experimentation/account-global-code/account-global-code.go b/cmd/web_experimentation/account_global_code/account_global_code.go similarity index 100% rename from cmd/web_experimentation/account-global-code/account-global-code.go rename to cmd/web_experimentation/account_global_code/account_global_code.go diff --git a/cmd/web_experimentation/account_global_code/account_global_code_test.go b/cmd/web_experimentation/account_global_code/account_global_code_test.go new file mode 100644 index 0000000..5f6e554 --- /dev/null +++ b/cmd/web_experimentation/account_global_code/account_global_code_test.go @@ -0,0 +1,43 @@ +package account_global_code + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIAccount() + + m.Run() +} + +func TestAccountGlobalCodeCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountGlobalCodeCmd) + assert.Contains(t, output, "Get account global code") +} + +func TestAccountGlobalCodeHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "--help") + assert.Contains(t, output, "Get account global code") +} + +func TestAccountGlobalCodeGetCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "get", "-i=account_id") + assert.Equal(t, "console.log(\"test\")\n", successOutput) +} diff --git a/cmd/web_experimentation/account-global-code/get.go b/cmd/web_experimentation/account_global_code/get.go similarity index 100% rename from cmd/web_experimentation/account-global-code/get.go rename to cmd/web_experimentation/account_global_code/get.go diff --git a/cmd/web_experimentation/campaign-global-code/campaign-global-code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go similarity index 100% rename from cmd/web_experimentation/campaign-global-code/campaign-global-code.go rename to cmd/web_experimentation/campaign_global_code/campaign_global_code.go diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go new file mode 100644 index 0000000..694bd3b --- /dev/null +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go @@ -0,0 +1,43 @@ +package campaign_global_code + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APICampaign() + + m.Run() +} + +func TestCampaignGlobalCodeCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd) + assert.Contains(t, output, "Get campaign global code") +} + +func TestCampaignGlobalCodeHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "--help") + assert.Contains(t, output, "Get campaign global code") +} + +func TestCampaignGlobalCodeGetCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "get", "-i=100000") + assert.Equal(t, "console.log(\"Hello World!\")\n", successOutput) +} diff --git a/cmd/web_experimentation/campaign-global-code/get.go b/cmd/web_experimentation/campaign_global_code/get.go similarity index 100% rename from cmd/web_experimentation/campaign-global-code/get.go rename to cmd/web_experimentation/campaign_global_code/get.go diff --git a/cmd/web_experimentation/global_code/global_code.go b/cmd/web_experimentation/global_code/global_code.go deleted file mode 100644 index f2456d2..0000000 --- a/cmd/web_experimentation/global_code/global_code.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package global_code - -import ( - "github.com/spf13/cobra" -) - -// globalCodeCmd represents the global code command -var GlobalCodeCmd = &cobra.Command{ - Use: "global-code [get|list]", - Short: "Manage your tests", - Long: `Manage your tests`, - Run: func(cmd *cobra.Command, args []string) { - cmd.Help() - }, -} diff --git a/cmd/web_experimentation/global_code/list.go b/cmd/web_experimentation/global_code/list.go deleted file mode 100644 index fa4c1c8..0000000 --- a/cmd/web_experimentation/global_code/list.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package global_code - -import ( - "log" - - "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -// listCmd represents the list command -var listCmd = &cobra.Command{ - Use: "list", - Short: "List all global code", - Long: `List all global code`, - Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.GlobalCodeRequester.HTTPListGlobalCode() - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - utils.FormatItem([]string{"Id", "Code"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) - - }, -} - -func init() { - GlobalCodeCmd.AddCommand(listCmd) -} diff --git a/cmd/web_experimentation/variation/variation_test.go b/cmd/web_experimentation/variation/variation_test.go new file mode 100644 index 0000000..8b58203 --- /dev/null +++ b/cmd/web_experimentation/variation/variation_test.go @@ -0,0 +1,52 @@ +package variation + +import ( + "encoding/json" + "testing" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_we.APIVariation() + + m.Run() +} + +var testVariation models.VariationWE + +func TestVariationCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(VariationCmd) + assert.Contains(t, output, "Error: required flag(s) \"campaign-id\" not set") + + output1, _ := utils.ExecuteCommand(VariationCmd, "--campaign-id=100000") + assert.Contains(t, output1, "Manage your variation") + +} + +func TestVariationHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(VariationCmd, "--help") + assert.Contains(t, output, "Manage your variation") +} + +func TestVariationGetCommand(t *testing.T) { + + successOutput, _ := utils.ExecuteCommand(VariationCmd, "get", "-i=110000", "--campaign-id=100000") + + err := json.Unmarshal([]byte(successOutput), &testVariation) + + assert.Nil(t, err) + assert.Equal(t, mockfunction_we.TestVariation, testVariation) +} diff --git a/cmd/web_experimentation/variation-global-code/get.go b/cmd/web_experimentation/variation_global_code/get.go similarity index 93% rename from cmd/web_experimentation/variation-global-code/get.go rename to cmd/web_experimentation/variation_global_code/get.go index 90235c8..8d8b1a4 100644 --- a/cmd/web_experimentation/variation-global-code/get.go +++ b/cmd/web_experimentation/variation_global_code/get.go @@ -19,7 +19,7 @@ type ModificationGlobalCode struct { // getCmd represents get command var getCmd = &cobra.Command{ - Use: "get [-i | --id ] [--test-id ]", + Use: "get [-i | --id ] [--campaign-id ]", Short: "Get variation global code", Long: `Get variation global code`, Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/web_experimentation/variation-global-code/variation-global-code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go similarity index 100% rename from cmd/web_experimentation/variation-global-code/variation-global-code.go rename to cmd/web_experimentation/variation_global_code/variation_global_code.go diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go new file mode 100644 index 0000000..994b2b7 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go @@ -0,0 +1,43 @@ +package variation_global_code + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIModification() + + m.Run() +} + +func TestVariationGlobalCodeCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(VariationGlobalCodeCmd) + assert.Contains(t, output, "Get variation global code") +} + +func TestVariationGlobalCodeHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "--help") + assert.Contains(t, output, "Get variation global code") +} + +func TestVariationGlobalCodeGetCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get", "-i=110000", "--campaign-id=100000") + assert.Equal(t, "{\"js\":\"console.log(\\\"test modification\\\")\",\"css\":\".id{\\\"color\\\": \\\"black\\\"}\"}\n", successOutput) +} diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 4cb91ca..afea2f4 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -7,13 +7,12 @@ import ( "os" "github.com/flagship-io/flagship/cmd/web_experimentation/account" - account_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/account-global-code" + account_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/account_global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" - campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign-global-code" - "github.com/flagship-io/flagship/cmd/web_experimentation/global_code" + campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" - variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation-global-code" + variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation_global_code" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" "github.com/flagship-io/flagship/utils/http_request" @@ -39,7 +38,6 @@ var WebExperimentationCmd = &cobra.Command{ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(campaign.CampaignCmd) - WebExperimentationCmd.AddCommand(global_code.GlobalCodeCmd) WebExperimentationCmd.AddCommand(variation.VariationCmd) WebExperimentationCmd.AddCommand(auth.AuthCmd) WebExperimentationCmd.AddCommand(account.AccountCmd) diff --git a/utils/config/config.go b/utils/config/config.go index c00a691..a2b7203 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -111,7 +111,7 @@ func ReadAuth(product, AuthName string) *viper.Viper { v := viper.New() configFilepath := CredentialPath(product, AuthName) if _, err := os.Stat(configFilepath); errors.Is(err, os.ErrNotExist) { - fmt.Fprintf(os.Stdout, "error occurred: %v \n", err) + fmt.Fprintf(os.Stderr, "error occurred: %v \n", err) } v.SetConfigFile(configFilepath) v.MergeInConfig() diff --git a/utils/http_request/main.go b/utils/http_request/main.go index a341f5f..efa69e1 100644 --- a/utils/http_request/main.go +++ b/utils/http_request/main.go @@ -28,7 +28,6 @@ var PanicRequester feature_experimentation.PanicRequester = feature_experimentat // web experimentation var CampaignWERequester web_experimentation.CampaignWERequester = web_experimentation.CampaignWERequester{ResourceRequest: &ResourceRequester} -var GlobalCodeRequester web_experimentation.GlobalCodeRequester = web_experimentation.GlobalCodeRequester{ResourceRequest: &ResourceRequester} var AccountWERequester web_experimentation.AccountWERequester = web_experimentation.AccountWERequester{ResourceRequest: &ResourceRequester} var VariationWERequester web_experimentation.VariationWERequester = web_experimentation.VariationWERequester{ResourceRequest: &ResourceRequester} var CampaignGlobalCodeRequester web_experimentation.CampaignGlobalCodeRequester = web_experimentation.CampaignGlobalCodeRequester{ResourceRequest: &ResourceRequester} diff --git a/utils/http_request/web_experimentation/global_code.go b/utils/http_request/web_experimentation/global_code.go deleted file mode 100644 index b9ba852..0000000 --- a/utils/http_request/web_experimentation/global_code.go +++ /dev/null @@ -1,19 +0,0 @@ -package web_experimentation - -import ( - models "github.com/flagship-io/flagship/models/web_experimentation" - "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/http_request/common" -) - -type GlobalCodeRequester struct { - *common.ResourceRequest -} - -func (g *GlobalCodeRequester) HTTPListGlobalCode() ([]models.GlobalCode, error) { - return common.HTTPGetAllPagesWE[models.GlobalCode](utils.GetWebExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes") -} - -func (g *GlobalCodeRequester) HTTPGetGlobalCode(id string) (models.GlobalCode, error) { - return common.HTTPGetItem[models.GlobalCode](utils.GetFeatureExperimentationHost() + "/v1/accounts/" + g.AccountID + "/global-codes/" + id) -} diff --git a/utils/mock_function/web_experimentation/account.go b/utils/mock_function/web_experimentation/account.go index 638945c..fdd5f90 100644 --- a/utils/mock_function/web_experimentation/account.go +++ b/utils/mock_function/web_experimentation/account.go @@ -1,11 +1,41 @@ package web_experimentation import ( - "github.com/flagship-io/flagship/models" + "net/http" + + models_ "github.com/flagship-io/flagship/models" + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/jarcoal/httpmock" ) -var TestAccount = models.AccountJSON{ +var TestAccount = models_.AccountJSON{ CurrentUsedCredential: "test_auth", AccountID: "account_id", AccountEnvironmentID: "account_environment_id", } + +var TestGlobalCode = models.GlobalCode_{ + OnDomReady: true, + Value: "console.log(\"test\")", +} + +var accountID = "account_id" + +var TestAccountGlobalCode = models.AccountWE{ + Id: 100000, + Name: "account_name", + Identifier: "account_identifier", + Role: "account_role", + GlobalCode: TestGlobalCode, +} + +func APIAccount() { + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+accountID, + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestAccountGlobalCode) + return resp, nil + }, + ) +} diff --git a/utils/mock_function/web_experimentation/modification.go b/utils/mock_function/web_experimentation/modification.go new file mode 100644 index 0000000..92a8ab1 --- /dev/null +++ b/utils/mock_function/web_experimentation/modification.go @@ -0,0 +1,47 @@ +package web_experimentation + +import ( + "net/http" + "strconv" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/jarcoal/httpmock" +) + +var TestModificationsJS = models.Modification{ + Id: 120001, + Name: "modification", + Value: "console.log(\"test modification\")", + VariationID: 110000, + Type: "customScriptNew", +} + +var TestModificationsCSS = models.Modification{ + Id: 120001, + Name: "modification", + Value: ".id{\"color\": \"black\"}", + VariationID: 110000, + Type: "addCSS", +} + +var TestData = models.ModificationWE{ + GlobalModifications: []models.Modification{}, + Modifications: []models.Modification{TestModificationsJS, TestModificationsCSS}, +} + +var TestModification = models.ModificationDataWE{ + Data: TestData, +} + +func APIModification() { + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestModification) + return resp, nil + }, + ) + +} diff --git a/utils/mock_function/web_experimentation/variation.go b/utils/mock_function/web_experimentation/variation.go new file mode 100644 index 0000000..3f36f0a --- /dev/null +++ b/utils/mock_function/web_experimentation/variation.go @@ -0,0 +1,28 @@ +package web_experimentation + +import ( + "net/http" + "strconv" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/jarcoal/httpmock" +) + +var TestVariation = models.VariationWE{ + Id: 110000, + Name: "testVariationName", + Description: "testVariationDescription", +} + +func APIVariation() { + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/variations/"+strconv.Itoa(TestVariation.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestVariation) + return resp, nil + }, + ) + +} From 831b81e2da205f2e9b5ba2ae9ec1d08e0a872dc3 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 15 Apr 2024 11:17:17 +0200 Subject: [PATCH 24/48] add current cred auth & cmd generate for js & css file --- .../account/account.go | 2 +- .../account/current.go | 5 +- cmd/feature_experimentation/auth/current.go | 47 +++++++++++++ cmd/web_experimentation/auth/current.go | 47 +++++++++++++ .../variation_global_code/generate.go | 66 +++++++++++++++++++ .../variation_global_code/get.go | 51 +++++++++----- .../variation_global_code.go | 18 +---- .../variation-global-code.go | 6 +- 8 files changed, 202 insertions(+), 40 deletions(-) create mode 100644 cmd/feature_experimentation/auth/current.go create mode 100644 cmd/web_experimentation/auth/current.go create mode 100644 cmd/web_experimentation/variation_global_code/generate.go diff --git a/cmd/feature_experimentation/account/account.go b/cmd/feature_experimentation/account/account.go index 4b8de07..ca816c4 100644 --- a/cmd/feature_experimentation/account/account.go +++ b/cmd/feature_experimentation/account/account.go @@ -12,7 +12,7 @@ var ( // AccountCmd represents the account command var AccountCmd = &cobra.Command{ - Use: "account [use|list|current]", + Use: "account [use|current]", Short: "Manage your CLI authentication", Long: `Manage your CLI authentication`, Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index 797b8a5..067297c 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -18,8 +18,8 @@ import ( // getCmd represents the list command var currentCmd = &cobra.Command{ Use: "current", - Short: "current an auth credential", - Long: `current an auth credential`, + Short: "Get current running auth credential", + Long: `Get current running auth credential`, Run: func(cmd *cobra.Command, args []string) { var accountYaml models.AccountYaml @@ -38,7 +38,6 @@ var currentCmd = &cobra.Command{ account.CurrentUsedCredential = accountYaml.CurrentUsedCredential account.AccountID = accountYaml.AccountID - account.AccountEnvironmentID = accountYaml.AccountEnvironmentID utils.FormatItem([]string{"CurrentUsedCredential", "AccountID"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) diff --git a/cmd/feature_experimentation/auth/current.go b/cmd/feature_experimentation/auth/current.go new file mode 100644 index 0000000..e001e2f --- /dev/null +++ b/cmd/feature_experimentation/auth/current.go @@ -0,0 +1,47 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// currentCmd represents the current command +var currentCmd = &cobra.Command{ + Use: "current", + Short: "Get current running auth credential for feature experimentation", + Long: `Get current running auth credential for feature experimentation`, + Run: func(cmd *cobra.Command, args []string) { + var accountYaml models.AccountYaml + var account models.AccountJSON + + yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &accountYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + account.CurrentUsedCredential = accountYaml.CurrentUsedCredential + + utils.FormatItem([]string{"CurrentUsedCredential"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + AuthCmd.AddCommand(currentCmd) +} diff --git a/cmd/web_experimentation/auth/current.go b/cmd/web_experimentation/auth/current.go new file mode 100644 index 0000000..5a4d7d5 --- /dev/null +++ b/cmd/web_experimentation/auth/current.go @@ -0,0 +1,47 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package auth + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// currentCmd represents the current command +var currentCmd = &cobra.Command{ + Use: "current", + Short: "Get current running auth credential for web experimentation", + Long: `Get current running auth credential for web experimentation`, + Run: func(cmd *cobra.Command, args []string) { + var accountYaml models.AccountYaml + var account models.AccountJSON + + yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI)) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(yamlFile, &accountYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + account.CurrentUsedCredential = accountYaml.CurrentUsedCredential + + utils.FormatItem([]string{"CurrentUsedCredential"}, account, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + AuthCmd.AddCommand(currentCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/generate.go b/cmd/web_experimentation/variation_global_code/generate.go new file mode 100644 index 0000000..6937432 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/generate.go @@ -0,0 +1,66 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "fmt" + "log" + "os" + "strconv" + + "github.com/spf13/cobra" +) + +var modifFiles ModificationGlobalCode + +// generate represents generate command +var generateCmd = &cobra.Command{ + Use: "generate-file [-i | --id ] [--campaign-id ]", + Short: "Generate variation global code file", + Long: `Generate variation global code file`, + Run: func(cmd *cobra.Command, args []string) { + resp := GetCodeFiles(VariationID, CampaignID) + + if resp.JS != "" { + jsFilePath := strconv.Itoa(VariationID) + ".js" + + err := os.WriteFile(jsFilePath, []byte(resp.JS), os.ModePerm) + if err != nil { + fmt.Println("Error writing JavaScript file:", err) + return + } + + fmt.Fprintln(cmd.OutOrStdout(), "JavaScript code file generated successfully:", jsFilePath) + } + + if resp.CSS != "" { + cssFilePath := strconv.Itoa(VariationID) + ".css" + + err := os.WriteFile(cssFilePath, []byte(resp.CSS), os.ModePerm) + if err != nil { + fmt.Println("Error writing CSS file:", err) + return + } + + fmt.Fprintln(cmd.OutOrStdout(), "CSS code file generated successfully:", cssFilePath) + } + + }, +} + +func init() { + generateCmd.Flags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the global code campaign you want to display") + + if err := generateCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + generateCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") + + if err := generateCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + VariationGlobalCodeCmd.AddCommand(generateCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/get.go b/cmd/web_experimentation/variation_global_code/get.go index 8d8b1a4..a5dcd40 100644 --- a/cmd/web_experimentation/variation_global_code/get.go +++ b/cmd/web_experimentation/variation_global_code/get.go @@ -18,30 +18,47 @@ type ModificationGlobalCode struct { } // getCmd represents get command -var getCmd = &cobra.Command{ +var GetCmd = &cobra.Command{ Use: "get [-i | --id ] [--campaign-id ]", Short: "Get variation global code", Long: `Get variation global code`, Run: func(cmd *cobra.Command, args []string) { - var modificationResp ModificationGlobalCode - body, err := httprequest.ModificationRequester.HTTPGetModification(CampaignID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - for _, modification := range body { - if modification.VariationID == VariationID && modification.Type == "customScriptNew" { - modificationResp.JS = modification.Value - } - if modification.VariationID == VariationID && modification.Type == "addCSS" { - modificationResp.CSS = modification.Value - } - } + resp := GetCodeFiles(VariationID, CampaignID) - utils.FormatItem([]string{"JS", "CSS"}, modificationResp, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"JS", "CSS"}, resp, viper.GetString("output_format"), cmd.OutOrStdout()) }, } func init() { - VariationGlobalCodeCmd.AddCommand(getCmd) + GetCmd.Flags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the global code campaign you want to display") + + if err := GetCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + GetCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") + + if err := GetCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + VariationGlobalCodeCmd.AddCommand(GetCmd) +} + +func GetCodeFiles(variationID, campaignID int) ModificationGlobalCode { + var modificationResp ModificationGlobalCode + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == variationID && modification.Type == "customScriptNew" { + modificationResp.JS = modification.Value + } + if modification.VariationID == variationID && modification.Type == "addCSS" { + modificationResp.CSS = modification.Value + } + } + + return modificationResp } diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go index 632e51b..437e05b 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code.go @@ -4,12 +4,10 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package variation_global_code import ( - "log" - "github.com/spf13/cobra" ) -var CampaignID string +var CampaignID int var VariationID int // VariationGlobalCodeCmd represents the variation global code command @@ -22,17 +20,3 @@ var VariationGlobalCodeCmd = &cobra.Command{ cmd.Help() }, } - -func init() { - getCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") - - if err := getCmd.MarkFlagRequired("campaign-id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - - getCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") - - if err := getCmd.MarkFlagRequired("id"); err != nil { - log.Fatalf("error occurred: %v", err) - } -} diff --git a/utils/http_request/web_experimentation/variation-global-code.go b/utils/http_request/web_experimentation/variation-global-code.go index fceb887..7299576 100644 --- a/utils/http_request/web_experimentation/variation-global-code.go +++ b/utils/http_request/web_experimentation/variation-global-code.go @@ -1,6 +1,8 @@ package web_experimentation import ( + "strconv" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -10,7 +12,7 @@ type ModificationRequester struct { *common.ResourceRequest } -func (m *ModificationRequester) HTTPGetModification(id string) ([]models.Modification, error) { - resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + id + "/modifications") +func (m *ModificationRequester) HTTPGetModification(id int) ([]models.Modification, error) { + resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(id) + "/modifications") return resp.Data.Modifications, err } From b892285b88344e4d57d214a4498d417e8c16080c Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 18 Apr 2024 12:15:17 +0200 Subject: [PATCH 25/48] add get global account, campaign --- .../account_global_code.go | 36 ++++++++++ .../account_global_code/get.go | 16 +++-- .../campaign_global_code.go | 36 ++++++++++ .../campaign_global_code/get.go | 11 +++ .../variation_global_code/get.go | 11 ++- utils/config/config.go | 6 -- utils/config/config_global_code.go | 67 +++++++++++++++++++ utils/const.go | 14 +++- 8 files changed, 183 insertions(+), 14 deletions(-) create mode 100644 utils/config/config_global_code.go diff --git a/cmd/web_experimentation/account_global_code/account_global_code.go b/cmd/web_experimentation/account_global_code/account_global_code.go index 343415b..2c0888e 100644 --- a/cmd/web_experimentation/account_global_code/account_global_code.go +++ b/cmd/web_experimentation/account_global_code/account_global_code.go @@ -4,9 +4,17 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package account_global_code import ( + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" "github.com/spf13/cobra" + "github.com/spf13/viper" ) +var WorkingDir string + // AccountGlobalCodeCmd represents the account global code command var AccountGlobalCodeCmd = &cobra.Command{ Use: "account-global-code [get]", @@ -17,3 +25,31 @@ var AccountGlobalCodeCmd = &cobra.Command{ cmd.Help() }, } + +func init() { + cobra.OnInitialize(initConfig) + cobra.OnInitialize(initGlobalCodeDir) + AccountGlobalCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") + +} + +func initConfig() { + v := viper.New() + + homeDir, _ := os.UserHomeDir() + + v.BindPFlag("working_dir", AccountGlobalCodeCmd.PersistentFlags().Lookup("working-dir")) + + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") + v.MergeInConfig() + + err := v.WriteConfig() + if err != nil { + log.Fatalf("error occurred: %s", err) + } + viper.MergeConfigMap(v.AllSettings()) +} + +func initGlobalCodeDir() { + config.CheckWorkingDirectory(viper.GetString("working_dir")) +} diff --git a/cmd/web_experimentation/account_global_code/get.go b/cmd/web_experimentation/account_global_code/get.go index fadd154..24ad011 100644 --- a/cmd/web_experimentation/account_global_code/get.go +++ b/cmd/web_experimentation/account_global_code/get.go @@ -7,33 +7,41 @@ import ( "fmt" "log" + "github.com/flagship-io/flagship/utils/config" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" + "github.com/spf13/viper" ) var accountID string +var createFile bool // getCmd represents get command var getCmd = &cobra.Command{ Use: "get [-i | --id ]", - Short: "Get global account code", - Long: `Get global account code`, + Short: "Get account global code", + Long: `Get account global code`, Run: func(cmd *cobra.Command, args []string) { body, err := httprequest.AccountGlobalCodeRequester.HTTPGetAccountGlobalCode(accountID) if err != nil { log.Fatalf("error occurred: %v", err) } + if createFile { + accountCodeDir := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body) + fmt.Fprintln(cmd.OutOrStdout(), "Account code file generated successfully: ", accountCodeDir) + return + } fmt.Fprintln(cmd.OutOrStdout(), body) - }, } func init() { getCmd.Flags().StringVarP(&accountID, "id", "i", "", "id of the global code account you want to display") - if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } + getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains account global code") + AccountGlobalCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go index cb13cb4..6e03284 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go @@ -4,9 +4,17 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package campaign_global_code import ( + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" "github.com/spf13/cobra" + "github.com/spf13/viper" ) +var WorkingDir string + // CampaignGlobalCodeCmd represents the campaign global code command var CampaignGlobalCodeCmd = &cobra.Command{ Use: "campaign-global-code [get]", @@ -17,3 +25,31 @@ var CampaignGlobalCodeCmd = &cobra.Command{ cmd.Help() }, } + +func init() { + cobra.OnInitialize(initConfig) + cobra.OnInitialize(initGlobalCodeDir) + CampaignGlobalCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") + +} + +func initConfig() { + v := viper.New() + + homeDir, _ := os.UserHomeDir() + + v.BindPFlag("working_dir", CampaignGlobalCodeCmd.PersistentFlags().Lookup("working-dir")) + + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") + v.MergeInConfig() + + err := v.WriteConfig() + if err != nil { + log.Fatalf("error occurred: %s", err) + } + viper.MergeConfigMap(v.AllSettings()) +} + +func initGlobalCodeDir() { + config.CheckWorkingDirectory(viper.GetString("working_dir")) +} diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 3e02b09..9fd6b6c 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -7,11 +7,14 @@ import ( "fmt" "log" + "github.com/flagship-io/flagship/utils/config" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" + "github.com/spf13/viper" ) var campaignID string +var createFile bool // getCmd represents get command var getCmd = &cobra.Command{ @@ -24,6 +27,12 @@ var getCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } + if createFile { + accountCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, campaignID, body) + fmt.Fprintln(cmd.OutOrStdout(), "Campaign code file generated successfully: ", accountCodeDir) + return + } + fmt.Fprintln(cmd.OutOrStdout(), body) }, @@ -35,5 +44,7 @@ func init() { if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } + getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains campaign global code") + CampaignGlobalCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/variation_global_code/get.go b/cmd/web_experimentation/variation_global_code/get.go index a5dcd40..77d8434 100644 --- a/cmd/web_experimentation/variation_global_code/get.go +++ b/cmd/web_experimentation/variation_global_code/get.go @@ -13,8 +13,10 @@ import ( ) type ModificationGlobalCode struct { - JS string `json:"js,omitempty"` - CSS string `json:"css,omitempty"` + JS string `json:"js,omitempty"` + CSS string `json:"css,omitempty"` + VariationID int `json:"variation_id,omitempty"` + CampaignID int `json:"campaign_id,omitempty"` } // getCmd represents get command @@ -25,7 +27,7 @@ var GetCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { resp := GetCodeFiles(VariationID, CampaignID) - utils.FormatItem([]string{"JS", "CSS"}, resp, viper.GetString("output_format"), cmd.OutOrStdout()) + utils.FormatItem([]string{"VariationID", "CampaignID", "JS", "CSS"}, resp, viper.GetString("output_format"), cmd.OutOrStdout()) }, } @@ -60,5 +62,8 @@ func GetCodeFiles(variationID, campaignID int) ModificationGlobalCode { } } + modificationResp.CampaignID = campaignID + modificationResp.VariationID = variationID + return modificationResp } diff --git a/utils/config/config.go b/utils/config/config.go index a2b7203..638832b 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -15,12 +15,6 @@ import ( "github.com/spf13/viper" ) -type Config struct { - *viper.Viper -} - -var v = viper.New() - func Unset(key string) error { configMap := viper.AllSettings() delete(configMap, key) diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go new file mode 100644 index 0000000..489af8c --- /dev/null +++ b/utils/config/config_global_code.go @@ -0,0 +1,67 @@ +package config + +import ( + "errors" + "log" + "os" +) + +func CheckWorkingDirectory(workingDir string) string { + + if _, err := os.Stat(workingDir); errors.Is(err, os.ErrNotExist) { + if err != nil { + log.Fatalf("error occurred: %s", err) + } + } + + return workingDir +} + +func CheckGlobalCodeDirectory(workingDir string) string { + + wd := CheckWorkingDirectory(workingDir) + + gcWorkingDir := wd + "/abtasty" + + err := os.MkdirAll(gcWorkingDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + return gcWorkingDir +} + +func AccountGlobalCodeDirectory(workingDir, accountID, code string) string { + gcWorkingDir := CheckGlobalCodeDirectory(workingDir) + accountCodeDir := gcWorkingDir + "/" + accountID + + err := os.MkdirAll(accountCodeDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + jsFilePath := accountCodeDir + "/accountGlobalCode.js" + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) + if err != nil { + log.Fatalf("Error writing JavaScript file: %s", err) + } + return jsFilePath +} + +func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) string { + gcWorkingDir := CheckGlobalCodeDirectory(workingDir) + accountCodeDir := gcWorkingDir + "/" + accountID + campaignCodeDir := accountCodeDir + "/" + campaignID + + err := os.MkdirAll(campaignCodeDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + jsFilePath := campaignCodeDir + "/campaignGlobalCode.js" + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) + if err != nil { + log.Fatalf("Error writing JavaScript file: %s", err) + } + return jsFilePath +} diff --git a/utils/const.go b/utils/const.go index 5f49d25..3b3428c 100644 --- a/utils/const.go +++ b/utils/const.go @@ -1,6 +1,9 @@ package utils -import "os" +import ( + "log" + "os" +) func GetFeatureExperimentationHost() string { if os.Getenv("FS_STAGING") == "true" { @@ -34,6 +37,15 @@ func GetHostWebExperimentationAuth() string { return "https://api-auth.abtasty.com" } +func DefaultGlobalCodeWorkingDir() string { + wdDir, err := os.Getwd() + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + return wdDir +} + const FEATURE_EXPERIMENTATION = "fe" const WEB_EXPERIMENTATION = "we" const HOME_CLI = ".cli" From 03ecbcdc7f9deb423365eca9ae4028eaefb6ea0f Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 19 Apr 2024 09:48:37 +0200 Subject: [PATCH 26/48] add input params for resource loader --- cmd/feature_experimentation/resource/load.go | 61 +++++++++++++++++--- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index a129706..94f8d93 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -25,8 +25,11 @@ import ( var ( resourceFile string outputFile string + inputParams string ) +var inputParamsMap map[string]interface{} + type Data interface { Save(data string) ([]byte, error) Delete(id string) error @@ -225,14 +228,23 @@ var loadCmd = &cobra.Command{ Short: "Load your resources", Long: `Load your resources`, Run: func(cmd *cobra.Command, args []string) { - jsonBytes := ScriptResource(cmd, gResources) + if inputParams != "" { + err := json.Unmarshal([]byte(inputParams), &inputParamsMap) + if err != nil { + fmt.Fprintf(cmd.OutOrStderr(), "Error: %s", err) + return + } + } + jsonBytes := ScriptResource(cmd, gResources, inputParamsMap) if outputFile != "" { os.WriteFile(outputFile, jsonBytes, os.ModePerm) fmt.Fprintf(cmd.OutOrStdout(), "File created at %s\n", outputFile) return } + if viper.GetString("output_format") == "json" { + fmt.Fprintf(cmd.OutOrStdout(), "%s", string(jsonBytes)) + } - fmt.Fprintf(cmd.OutOrStdout(), "%s", string(jsonBytes)) }, } @@ -247,6 +259,8 @@ func init() { loadCmd.Flags().StringVarP(&outputFile, "output-file", "", "", "result of the command that contains all resource informations") + loadCmd.Flags().StringVarP(&inputParams, "input-params", "", "", "params to replace resource loader file") + ResourceCmd.AddCommand(loadCmd) } @@ -262,7 +276,7 @@ func initResource() { } } -func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { +func ScriptResource(cmd *cobra.Command, resources []Resource, inputParamsMap map[string]interface{}) []byte { resourceVariables := make(map[string]interface{}) var loadResultJSON []string @@ -324,6 +338,16 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { if ok { if strings.Contains(v, "$") { vTrim := strings.Trim(v, "$") + if inputParamsMap != nil { + vTrimL := strings.Split(vTrim, ".") + value, err := getNestedValue(inputParamsMap, vTrimL) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %s\n", err) + } + if value != nil { + resourceData[k] = value + } + } for k_, variable := range resourceVariables { script, _ := tengo.Eval(context.Background(), vTrim, map[string]interface{}{ k_: variable, @@ -361,13 +385,12 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { if httpMethod == "DELETE" { if resource.Name == Project || resource.Name == TargetingKey || resource.Name == Flag { - response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+url+"/"+fmt.Sprintf("%v", resourceData["id"]), nil) + _, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+url+"/"+fmt.Sprintf("%s", resourceData["id"]), nil) } if resource.Name == Goal || resource.Name == Campaign { - response, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+"/account_environments/"+cred.AccountEnvironmentID+url+"/"+fmt.Sprintf("%v", resourceData["id"]), nil) + _, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+"/account_environments/"+cred.AccountEnvironmentID+url+"/"+fmt.Sprintf("%s", resourceData["id"]), nil) } - if err == nil && viper.GetString("output_format") != "json" { response = []byte("The id: " + fmt.Sprintf("%v", resourceData["id"]) + " deleted successfully") } @@ -389,7 +412,7 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { } if responseData == nil { - fmt.Fprintln(os.Stderr, "error occurred not response data: "+string(response)) + fmt.Fprintf(os.Stderr, "error occurred not response data: %s\n", string(response)) continue } @@ -416,3 +439,27 @@ func ScriptResource(cmd *cobra.Command, resources []Resource) []byte { return jsonBytes } + +func getNestedValue(data map[string]interface{}, path []string) (interface{}, error) { + if len(path) == 0 { + return nil, fmt.Errorf("empty path") + } + + current := data + for i, key := range path { + value, ok := current[key] + if !ok { + continue + } + if i == len(path)-1 { + return value, nil + } + next, ok := value.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("value at key '%s' is not an object", key) + } + current = next + } + + return nil, nil +} From 1bf69d64ef9a11533edf624d1a84cf78f106dbe9 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 19 Apr 2024 09:48:52 +0200 Subject: [PATCH 27/48] fix regex for error request --- utils/http_request/common/request.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 5a016c4..739ce02 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -170,7 +170,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) return HTTPRequest[T](method, url, body) } - match, _ := regexp.MatchString("4..|5..", resp.Status) + match, _ := regexp.MatchString("4\\d\\d|5\\d\\d", resp.Status) if match { err := errors.New(string(respBody)) fmt.Fprintf(os.Stderr, "error occurred: %v", err) From 527e1bae1ea7ace80d305079193bde3980e2c4e2 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 23 Apr 2024 15:43:24 +0200 Subject: [PATCH 28/48] add create-subfiles for campaign & elementModificationCode & JS/CSS variation global code --- .../campaign_global_code.go | 1 + .../campaign_global_code/get.go | 48 ++++++++++-- .../element_modification_code.go | 58 ++++++++++++++ .../element_modification_code/get.go | 77 +++++++++++++++++++ .../variation_global_code/generate.go | 66 ---------------- .../variation_global_code/get-css.go | 71 +++++++++++++++++ .../variation_global_code/get-js.go | 71 +++++++++++++++++ .../variation_global_code/get.go | 69 ----------------- .../variation_global_code.go | 42 +++++++++- .../web_experimentation.go | 2 + models/web_experimentation/variation.go | 2 + utils/config/config_global_code.go | 67 ++++++++++++++++ 12 files changed, 430 insertions(+), 144 deletions(-) create mode 100644 cmd/web_experimentation/element_modification_code/element_modification_code.go create mode 100644 cmd/web_experimentation/element_modification_code/get.go delete mode 100644 cmd/web_experimentation/variation_global_code/generate.go create mode 100644 cmd/web_experimentation/variation_global_code/get-css.go create mode 100644 cmd/web_experimentation/variation_global_code/get-js.go delete mode 100644 cmd/web_experimentation/variation_global_code/get.go diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go index 6e03284..3ffb93d 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go @@ -14,6 +14,7 @@ import ( ) var WorkingDir string +var CampaignID string // CampaignGlobalCodeCmd represents the campaign global code command var CampaignGlobalCodeCmd = &cobra.Command{ diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 9fd6b6c..1faf497 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -6,6 +6,7 @@ package campaign_global_code import ( "fmt" "log" + "strconv" "github.com/flagship-io/flagship/utils/config" httprequest "github.com/flagship-io/flagship/utils/http_request" @@ -13,8 +14,8 @@ import ( "github.com/spf13/viper" ) -var campaignID string var createFile bool +var createSubFiles bool // getCmd represents get command var getCmd = &cobra.Command{ @@ -22,29 +23,64 @@ var getCmd = &cobra.Command{ Short: "Get campaign global code", Long: `Get campaign global code`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignGlobalCodeRequester.HTTPGetCampaignGlobalCode(campaignID) + + body, err := httprequest.CampaignGlobalCodeRequester.HTTPGetCampaignGlobalCode(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } if createFile { - accountCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, campaignID, body) - fmt.Fprintln(cmd.OutOrStdout(), "Campaign code file generated successfully: ", accountCodeDir) + campaignCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + fmt.Fprintln(cmd.OutOrStdout(), "Campaign code file generated successfully: ", campaignCodeDir) return } - fmt.Fprintln(cmd.OutOrStdout(), body) + // TODO + if createSubFiles { + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + campaignCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.Type == "customScriptNew" && modification.Selector == "" { + config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value) + continue + } + + if modification.Type == "addCSS" && modification.Selector == "" { + config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value) + continue + } + fileCode := config.AddHeaderSelectorComment(modification.Selector, modification.Value) + config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), strconv.Itoa(modification.Id), modification.Selector, fileCode) + } + + fmt.Fprintln(cmd.OutOrStdout(), "Sub files code generated successfully: ", campaignCodeDir) + + return + } + + fmt.Fprintln(cmd.OutOrStdout(), body) }, } func init() { - getCmd.Flags().StringVarP(&campaignID, "id", "i", "", "id of the global code campaign you want to display") + getCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the global code campaign you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains campaign global code") + getCmd.Flags().BoolVarP(&createSubFiles, "create-subfiles", "", false, "create a file that contains variations global code") CampaignGlobalCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/element_modification_code/element_modification_code.go b/cmd/web_experimentation/element_modification_code/element_modification_code.go new file mode 100644 index 0000000..c5d6fbf --- /dev/null +++ b/cmd/web_experimentation/element_modification_code/element_modification_code.go @@ -0,0 +1,58 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package element_modification_code + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +var WorkingDir string +var CampaignID string +var ModificationID string +var CreateFile bool + +// ElementModificationCodeCmd represents the variation global code command +var ElementModificationCodeCmd = &cobra.Command{ + Use: "element-modification-code [get]", + Short: "Get element modification code", + Aliases: []string{"emc"}, + Long: `Get element modification code`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func init() { + cobra.OnInitialize(initConfig) + cobra.OnInitialize(initGlobalCodeDir) + ElementModificationCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") + +} + +func initConfig() { + v := viper.New() + + homeDir, _ := os.UserHomeDir() + + v.BindPFlag("working_dir", ElementModificationCodeCmd.PersistentFlags().Lookup("working-dir")) + + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") + v.MergeInConfig() + + err := v.WriteConfig() + if err != nil { + log.Fatalf("error occurred: %s", err) + } + viper.MergeConfigMap(v.AllSettings()) +} + +func initGlobalCodeDir() { + config.CheckWorkingDirectory(viper.GetString("working_dir")) +} diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/element_modification_code/get.go new file mode 100644 index 0000000..0b5cc95 --- /dev/null +++ b/cmd/web_experimentation/element_modification_code/get.go @@ -0,0 +1,77 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package element_modification_code + +import ( + "fmt" + "log" + "strconv" + + "github.com/flagship-io/flagship/utils/config" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ] [--campaign-id ]", + Short: "Get element modification code", + Long: `Get element modification code`, + Run: func(cmd *cobra.Command, args []string) { + var code string + var selector string + var variationID int + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + modificationID, err := strconv.Atoi(ModificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.Id == modificationID && modification.Type == "customScriptNew" && modification.Selector != "" { + code = modification.Value + selector = modification.Selector + variationID = modification.VariationID + } + } + + fileCode := config.AddHeaderSelectorComment(selector, code) + + if CreateFile { + elementModificationCodeDir := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode) + fmt.Fprintln(cmd.OutOrStdout(), "Element code file generated successfully: ", elementModificationCodeDir) + return + } + + fmt.Fprintln(cmd.OutOrStdout(), string(fileCode)) + }, +} + +func init() { + getCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := getCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the global code vairation you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + + ElementModificationCodeCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/generate.go b/cmd/web_experimentation/variation_global_code/generate.go deleted file mode 100644 index 6937432..0000000 --- a/cmd/web_experimentation/variation_global_code/generate.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package variation_global_code - -import ( - "fmt" - "log" - "os" - "strconv" - - "github.com/spf13/cobra" -) - -var modifFiles ModificationGlobalCode - -// generate represents generate command -var generateCmd = &cobra.Command{ - Use: "generate-file [-i | --id ] [--campaign-id ]", - Short: "Generate variation global code file", - Long: `Generate variation global code file`, - Run: func(cmd *cobra.Command, args []string) { - resp := GetCodeFiles(VariationID, CampaignID) - - if resp.JS != "" { - jsFilePath := strconv.Itoa(VariationID) + ".js" - - err := os.WriteFile(jsFilePath, []byte(resp.JS), os.ModePerm) - if err != nil { - fmt.Println("Error writing JavaScript file:", err) - return - } - - fmt.Fprintln(cmd.OutOrStdout(), "JavaScript code file generated successfully:", jsFilePath) - } - - if resp.CSS != "" { - cssFilePath := strconv.Itoa(VariationID) + ".css" - - err := os.WriteFile(cssFilePath, []byte(resp.CSS), os.ModePerm) - if err != nil { - fmt.Println("Error writing CSS file:", err) - return - } - - fmt.Fprintln(cmd.OutOrStdout(), "CSS code file generated successfully:", cssFilePath) - } - - }, -} - -func init() { - generateCmd.Flags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the global code campaign you want to display") - - if err := generateCmd.MarkFlagRequired("campaign-id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - - generateCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") - - if err := generateCmd.MarkFlagRequired("id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - - VariationGlobalCodeCmd.AddCommand(generateCmd) -} diff --git a/cmd/web_experimentation/variation_global_code/get-css.go b/cmd/web_experimentation/variation_global_code/get-css.go new file mode 100644 index 0000000..deedc17 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/get-css.go @@ -0,0 +1,71 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "fmt" + "log" + "strconv" + + "github.com/flagship-io/flagship/utils/config" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// getCSSCmd represents get command +var getCSSCmd = &cobra.Command{ + Use: "get-css [-i | --id ] [--campaign-id ]", + Short: "Get variation global css code", + Long: `Get variation global css code`, + Run: func(cmd *cobra.Command, args []string) { + var cssCode string + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == variationID && modification.Type == "addCSS" && modification.Selector == "" { + cssCode = modification.Value + } + } + + if CreateFile { + campaignCodeDir := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, cssCode) + fmt.Fprintln(cmd.OutOrStdout(), "Variation code file generated successfully: ", campaignCodeDir) + return + } + + fmt.Fprintln(cmd.OutOrStdout(), cssCode) + }, +} + +func init() { + getCSSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := getCSSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getCSSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code vairation you want to display") + + if err := getCSSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getCSSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + + VariationGlobalCodeCmd.AddCommand(getCSSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go new file mode 100644 index 0000000..b603859 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -0,0 +1,71 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "fmt" + "log" + "strconv" + + "github.com/flagship-io/flagship/utils/config" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// getJsCmd represents get command +var getJSCmd = &cobra.Command{ + Use: "get-js [-i | --id ] [--campaign-id ]", + Short: "Get variation global js code", + Long: `Get variation global js code`, + Run: func(cmd *cobra.Command, args []string) { + var jsCode string + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == variationID && modification.Type == "customScriptNew" && modification.Selector == "" { + jsCode = modification.Value + } + } + + if CreateFile { + variationCodeDir := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, jsCode) + fmt.Fprintln(cmd.OutOrStdout(), "Variation code file generated successfully: ", variationCodeDir) + return + } + + fmt.Fprintln(cmd.OutOrStdout(), jsCode) + }, +} + +func init() { + getJSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := getJSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getJSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code vairation you want to display") + + if err := getJSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + getJSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + + VariationGlobalCodeCmd.AddCommand(getJSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/get.go b/cmd/web_experimentation/variation_global_code/get.go deleted file mode 100644 index 77d8434..0000000 --- a/cmd/web_experimentation/variation_global_code/get.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ -package variation_global_code - -import ( - "log" - - "github.com/flagship-io/flagship/utils" - httprequest "github.com/flagship-io/flagship/utils/http_request" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -type ModificationGlobalCode struct { - JS string `json:"js,omitempty"` - CSS string `json:"css,omitempty"` - VariationID int `json:"variation_id,omitempty"` - CampaignID int `json:"campaign_id,omitempty"` -} - -// getCmd represents get command -var GetCmd = &cobra.Command{ - Use: "get [-i | --id ] [--campaign-id ]", - Short: "Get variation global code", - Long: `Get variation global code`, - Run: func(cmd *cobra.Command, args []string) { - resp := GetCodeFiles(VariationID, CampaignID) - - utils.FormatItem([]string{"VariationID", "CampaignID", "JS", "CSS"}, resp, viper.GetString("output_format"), cmd.OutOrStdout()) - }, -} - -func init() { - GetCmd.Flags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the global code campaign you want to display") - - if err := GetCmd.MarkFlagRequired("campaign-id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - - GetCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the global code vairation you want to display") - - if err := GetCmd.MarkFlagRequired("id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - VariationGlobalCodeCmd.AddCommand(GetCmd) -} - -func GetCodeFiles(variationID, campaignID int) ModificationGlobalCode { - var modificationResp ModificationGlobalCode - body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - for _, modification := range body { - if modification.VariationID == variationID && modification.Type == "customScriptNew" { - modificationResp.JS = modification.Value - } - if modification.VariationID == variationID && modification.Type == "addCSS" { - modificationResp.CSS = modification.Value - } - } - - modificationResp.CampaignID = campaignID - modificationResp.VariationID = variationID - - return modificationResp -} diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go index 437e05b..879f91e 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code.go @@ -4,15 +4,23 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package variation_global_code import ( + "log" + "os" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" "github.com/spf13/cobra" + "github.com/spf13/viper" ) -var CampaignID int -var VariationID int +var WorkingDir string +var CampaignID string +var VariationID string +var CreateFile bool // VariationGlobalCodeCmd represents the variation global code command var VariationGlobalCodeCmd = &cobra.Command{ - Use: "variation-global-code [get]", + Use: "variation-global-code [get-js | get-css]", Short: "Get variable global code", Aliases: []string{"vgc"}, Long: `Get variable global code`, @@ -20,3 +28,31 @@ var VariationGlobalCodeCmd = &cobra.Command{ cmd.Help() }, } + +func init() { + cobra.OnInitialize(initConfig) + cobra.OnInitialize(initGlobalCodeDir) + VariationGlobalCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") + +} + +func initConfig() { + v := viper.New() + + homeDir, _ := os.UserHomeDir() + + v.BindPFlag("working_dir", VariationGlobalCodeCmd.PersistentFlags().Lookup("working-dir")) + + v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") + v.MergeInConfig() + + err := v.WriteConfig() + if err != nil { + log.Fatalf("error occurred: %s", err) + } + viper.MergeConfigMap(v.AllSettings()) +} + +func initGlobalCodeDir() { + config.CheckWorkingDirectory(viper.GetString("working_dir")) +} diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index afea2f4..0c05470 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -11,6 +11,7 @@ import ( "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" + "github.com/flagship-io/flagship/cmd/web_experimentation/element_modification_code" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation_global_code" "github.com/flagship-io/flagship/utils" @@ -44,6 +45,7 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(campaign_global_code.CampaignGlobalCodeCmd) WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) + WebExperimentationCmd.AddCommand(element_modification_code.ElementModificationCodeCmd) } func init() { diff --git a/models/web_experimentation/variation.go b/models/web_experimentation/variation.go index 4485f13..4573a8e 100644 --- a/models/web_experimentation/variation.go +++ b/models/web_experimentation/variation.go @@ -29,6 +29,8 @@ type Modification struct { Type string `json:"type"` Value string `json:"value"` VariationID int `json:"variation_id"` + Selector string `json:"selector"` + Engine string `json:"engine"` UpdatedBy UpdatedBy_ `json:"updated_by"` UpdatedAt DateTemplate `json:"updated_at"` } diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go index 489af8c..3bcd52a 100644 --- a/utils/config/config_global_code.go +++ b/utils/config/config_global_code.go @@ -65,3 +65,70 @@ func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) } return jsFilePath } + +func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variationID, code string) string { + gcWorkingDir := CheckGlobalCodeDirectory(workingDir) + accountCodeDir := gcWorkingDir + "/" + accountID + campaignCodeDir := accountCodeDir + "/" + campaignID + variationCodeDir := campaignCodeDir + "/" + variationID + + err := os.MkdirAll(variationCodeDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + jsFilePath := variationCodeDir + "/variationGlobalCode.js" + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) + if err != nil { + log.Fatalf("Error writing JavaScript file: %s", err) + } + return jsFilePath +} + +func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variationID, code string) string { + gcWorkingDir := CheckGlobalCodeDirectory(workingDir) + accountCodeDir := gcWorkingDir + "/" + accountID + campaignCodeDir := accountCodeDir + "/" + campaignID + variationCodeDir := campaignCodeDir + "/" + variationID + + err := os.MkdirAll(variationCodeDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + jsFilePath := variationCodeDir + "/variationGlobalCode.css" + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) + if err != nil { + log.Fatalf("Error writing CSS file: %s", err) + } + return jsFilePath +} + +func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte) string { + gcWorkingDir := CheckGlobalCodeDirectory(workingDir) + accountCodeDir := gcWorkingDir + "/" + accountID + campaignCodeDir := accountCodeDir + "/" + campaignID + variationCodeDir := campaignCodeDir + "/" + variationID + elementCodeDir := variationCodeDir + "/" + elementID + + err := os.MkdirAll(elementCodeDir, os.ModePerm) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + jsFilePath := elementCodeDir + "/element.js" + + err = os.WriteFile(jsFilePath, code, os.ModePerm) + if err != nil { + log.Fatalf("Error writing JavaScript file: %s", err) + } + return jsFilePath +} + +func AddHeaderSelectorComment(selector, code string) []byte { + selectorComment := "/* Selector: " + selector + " */\n" + headerComment := []byte(selectorComment) + + fileCode := append(headerComment, []byte(code)...) + return fileCode +} From 28230ec7374606d69989bd0754b2c332bd6344e5 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 23 Apr 2024 18:24:43 +0200 Subject: [PATCH 29/48] add/fix some test & text desc --- .../account/account_test.go | 4 +- .../account_global_code.go | 5 +- .../campaign_global_code.go | 5 +- .../element_modification_code.go | 5 +- .../element_modification_code_test.go | 47 +++++++++++++++++++ .../element_modification_code/get.go | 13 +++-- .../variation_global_code/get-css.go | 2 +- .../variation_global_code/get-js.go | 2 +- .../variation_global_code.go | 9 ++-- .../variation_global_code_test.go | 16 +++++-- utils/config/config_global_code.go | 13 +++-- .../variation-global-code.go | 9 +++- .../web_experimentation/modification.go | 29 +++++++++++- 13 files changed, 129 insertions(+), 30 deletions(-) create mode 100644 cmd/web_experimentation/element_modification_code/element_modification_code_test.go diff --git a/cmd/feature_experimentation/account/account_test.go b/cmd/feature_experimentation/account/account_test.go index 7a907dd..8256c48 100644 --- a/cmd/feature_experimentation/account/account_test.go +++ b/cmd/feature_experimentation/account/account_test.go @@ -31,12 +31,12 @@ var testAccount models.AccountJSON func TestAccountCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AccountCmd) - assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|current]") } func TestAccountHelpCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AccountCmd, "--help") - assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|list|current]") + assert.Contains(t, output, "Manage your CLI authentication\n\nUsage:\n account [use|current]") } func TestAccountUseCommand(t *testing.T) { diff --git a/cmd/web_experimentation/account_global_code/account_global_code.go b/cmd/web_experimentation/account_global_code/account_global_code.go index 2c0888e..9e333e6 100644 --- a/cmd/web_experimentation/account_global_code/account_global_code.go +++ b/cmd/web_experimentation/account_global_code/account_global_code.go @@ -51,5 +51,8 @@ func initConfig() { } func initGlobalCodeDir() { - config.CheckWorkingDirectory(viper.GetString("working_dir")) + _, err := config.CheckWorkingDirectory(viper.GetString("working_dir")) + if err != nil { + log.Fatalf("error occurred: %s", err) + } } diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go index 3ffb93d..760877c 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go @@ -52,5 +52,8 @@ func initConfig() { } func initGlobalCodeDir() { - config.CheckWorkingDirectory(viper.GetString("working_dir")) + _, err := config.CheckWorkingDirectory(viper.GetString("working_dir")) + if err != nil { + log.Fatalf("error occurred: %s", err) + } } diff --git a/cmd/web_experimentation/element_modification_code/element_modification_code.go b/cmd/web_experimentation/element_modification_code/element_modification_code.go index c5d6fbf..eef919a 100644 --- a/cmd/web_experimentation/element_modification_code/element_modification_code.go +++ b/cmd/web_experimentation/element_modification_code/element_modification_code.go @@ -54,5 +54,8 @@ func initConfig() { } func initGlobalCodeDir() { - config.CheckWorkingDirectory(viper.GetString("working_dir")) + _, err := config.CheckWorkingDirectory(viper.GetString("working_dir")) + if err != nil { + log.Fatalf("error occurred: %s", err) + } } diff --git a/cmd/web_experimentation/element_modification_code/element_modification_code_test.go b/cmd/web_experimentation/element_modification_code/element_modification_code_test.go new file mode 100644 index 0000000..8020cb9 --- /dev/null +++ b/cmd/web_experimentation/element_modification_code/element_modification_code_test.go @@ -0,0 +1,47 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ + +package element_modification_code + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIModification() + + m.Run() +} + +func TestElementModificationCodeCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(ElementModificationCodeCmd) + assert.Contains(t, output, "Get element modification code") +} + +func TestElementModificationCodeHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "--help") + assert.Contains(t, output, "Get element modification code") +} + +func TestElementModificationCodeGetCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "get", "-i=120003", "--campaign-id=100000") + assert.Equal(t, "console.log(\"test modification\")\n", successOutput) +} diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/element_modification_code/get.go index 0b5cc95..2eaca87 100644 --- a/cmd/web_experimentation/element_modification_code/get.go +++ b/cmd/web_experimentation/element_modification_code/get.go @@ -33,39 +33,38 @@ var getCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + body, err := httprequest.ModificationRequester.HTTPGetModificationByID(campaignID, modificationID) if err != nil { log.Fatalf("error occurred: %v", err) } for _, modification := range body { - if modification.Id == modificationID && modification.Type == "customScriptNew" && modification.Selector != "" { + if modification.Type == "customScriptNew" && modification.Selector != "" { code = modification.Value selector = modification.Selector variationID = modification.VariationID } } - fileCode := config.AddHeaderSelectorComment(selector, code) - if CreateFile { + fileCode := config.AddHeaderSelectorComment(selector, code) elementModificationCodeDir := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode) fmt.Fprintln(cmd.OutOrStdout(), "Element code file generated successfully: ", elementModificationCodeDir) return } - fmt.Fprintln(cmd.OutOrStdout(), string(fileCode)) + fmt.Fprintln(cmd.OutOrStdout(), string(code)) }, } func init() { - getCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + getCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the campaign") if err := getCmd.MarkFlagRequired("campaign-id"); err != nil { log.Fatalf("error occurred: %v", err) } - getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the global code vairation you want to display") + getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the global code modification you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation_global_code/get-css.go b/cmd/web_experimentation/variation_global_code/get-css.go index deedc17..af354c9 100644 --- a/cmd/web_experimentation/variation_global_code/get-css.go +++ b/cmd/web_experimentation/variation_global_code/get-css.go @@ -59,7 +59,7 @@ func init() { log.Fatalf("error occurred: %v", err) } - getCSSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code vairation you want to display") + getCSSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") if err := getCSSCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go index b603859..c4dc89a 100644 --- a/cmd/web_experimentation/variation_global_code/get-js.go +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -59,7 +59,7 @@ func init() { log.Fatalf("error occurred: %v", err) } - getJSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code vairation you want to display") + getJSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") if err := getJSCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go index 879f91e..81566e5 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code.go @@ -21,9 +21,9 @@ var CreateFile bool // VariationGlobalCodeCmd represents the variation global code command var VariationGlobalCodeCmd = &cobra.Command{ Use: "variation-global-code [get-js | get-css]", - Short: "Get variable global code", + Short: "Get variation global code", Aliases: []string{"vgc"}, - Long: `Get variable global code`, + Long: `Get variation global code`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, @@ -54,5 +54,8 @@ func initConfig() { } func initGlobalCodeDir() { - config.CheckWorkingDirectory(viper.GetString("working_dir")) + _, err := config.CheckWorkingDirectory(viper.GetString("working_dir")) + if err != nil { + log.Fatalf("error occurred: %s", err) + } } diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go index 994b2b7..c3dcc3b 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go @@ -34,10 +34,18 @@ func TestVariationGlobalCodeHelpCommand(t *testing.T) { assert.Contains(t, output, "Get variation global code") } -func TestVariationGlobalCodeGetCommand(t *testing.T) { - failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get") +func TestVariationGlobalCodeGetJSCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get-js") assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") - successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get", "-i=110000", "--campaign-id=100000") - assert.Equal(t, "{\"js\":\"console.log(\\\"test modification\\\")\",\"css\":\".id{\\\"color\\\": \\\"black\\\"}\"}\n", successOutput) + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get-js", "-i=110000", "--campaign-id=100000") + assert.Equal(t, "console.log(\"test modification\")\n", successOutput) +} + +func TestVariationGlobalCodeGetCSSCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get-css") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get-css", "-i=110000", "--campaign-id=100000") + assert.Equal(t, ".id{\"color\": \"black\"}\n", successOutput) } diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go index 3bcd52a..a9191d8 100644 --- a/utils/config/config_global_code.go +++ b/utils/config/config_global_code.go @@ -6,24 +6,27 @@ import ( "os" ) -func CheckWorkingDirectory(workingDir string) string { +func CheckWorkingDirectory(workingDir string) (string, error) { if _, err := os.Stat(workingDir); errors.Is(err, os.ErrNotExist) { if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } } - return workingDir + return workingDir, nil } func CheckGlobalCodeDirectory(workingDir string) string { - wd := CheckWorkingDirectory(workingDir) + wd, err := CheckWorkingDirectory(workingDir) + if err != nil { + log.Fatalf("error occurred: %s", err) + } gcWorkingDir := wd + "/abtasty" - err := os.MkdirAll(gcWorkingDir, os.ModePerm) + err = os.MkdirAll(gcWorkingDir, os.ModePerm) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/utils/http_request/web_experimentation/variation-global-code.go b/utils/http_request/web_experimentation/variation-global-code.go index 7299576..257675f 100644 --- a/utils/http_request/web_experimentation/variation-global-code.go +++ b/utils/http_request/web_experimentation/variation-global-code.go @@ -12,7 +12,12 @@ type ModificationRequester struct { *common.ResourceRequest } -func (m *ModificationRequester) HTTPGetModification(id int) ([]models.Modification, error) { - resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(id) + "/modifications") +func (m *ModificationRequester) HTTPGetModification(campaignID int) ([]models.Modification, error) { + resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(campaignID) + "/modifications") + return resp.Data.Modifications, err +} + +func (m *ModificationRequester) HTTPGetModificationByID(campaignID int, id int) ([]models.Modification, error) { + resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(campaignID) + "/modifications?ids=" + strconv.Itoa(id)) return resp.Data.Modifications, err } diff --git a/utils/mock_function/web_experimentation/modification.go b/utils/mock_function/web_experimentation/modification.go index 92a8ab1..57f1798 100644 --- a/utils/mock_function/web_experimentation/modification.go +++ b/utils/mock_function/web_experimentation/modification.go @@ -19,25 +19,50 @@ var TestModificationsJS = models.Modification{ } var TestModificationsCSS = models.Modification{ - Id: 120001, + Id: 120002, Name: "modification", Value: ".id{\"color\": \"black\"}", VariationID: 110000, Type: "addCSS", } +var TestElementModification = models.Modification{ + Id: 120003, + Name: "modification", + Value: "console.log(\"test modification\")", + VariationID: 110000, + Selector: "document.querySelector()", + Type: "customScriptNew", +} + var TestData = models.ModificationWE{ GlobalModifications: []models.Modification{}, Modifications: []models.Modification{TestModificationsJS, TestModificationsCSS}, } -var TestModification = models.ModificationDataWE{ +var TestModifData = models.ModificationWE{ + GlobalModifications: []models.Modification{}, + Modifications: []models.Modification{TestElementModification}, +} + +var TestModifications = models.ModificationDataWE{ Data: TestData, } +var TestModification = models.ModificationDataWE{ + Data: TestModifData, +} + func APIModification() { httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestModifications) + return resp, nil + }, + ) + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications?ids="+strconv.Itoa(TestElementModification.Id), func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestModification) return resp, nil From 3f68bc6bb32c11a39da089b01e59e43e0fbd1146 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 24 Apr 2024 17:56:35 +0200 Subject: [PATCH 30/48] add some unit & command test --- Makefile | 4 +- .../account/current.go | 7 +- .../account_environment_test.go | 19 +- .../account_environment/current.go | 7 +- cmd/feature_experimentation/auth/current.go | 7 +- cmd/feature_experimentation/auth/delete.go | 12 +- cmd/feature_experimentation/auth/get.go | 7 +- cmd/feature_experimentation/auth/list.go | 7 +- cmd/web_experimentation/account/current.go | 7 +- .../account_global_code/get.go | 5 +- cmd/web_experimentation/auth/current.go | 7 +- cmd/web_experimentation/auth/delete.go | 12 +- cmd/web_experimentation/auth/get.go | 7 +- cmd/web_experimentation/auth/list.go | 7 +- .../campaign_global_code/get.go | 11 +- .../element_modification_code/get.go | 6 +- .../variation_global_code/get-css.go | 6 +- .../variation_global_code/get-js.go | 5 +- utils/config/config_global_code.go | 88 +++-- utils/config/config_global_code_test.go | 335 ++++++++++++++++++ .../feature_experimentation/main_test.go | 1 + .../account_environment.go | 56 +++ .../feature_experimentation/auth.go | 8 +- .../mock_function/web_experimentation/auth.go | 8 +- 24 files changed, 576 insertions(+), 63 deletions(-) create mode 100644 utils/config/config_global_code_test.go create mode 100644 utils/mock_function/feature_experimentation/account_environment.go diff --git a/Makefile b/Makefile index 0a90b0e..864c969 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ build: test: SHELL:=/bin/bash test: mkdir -p coverage - go test -v -race `go list ./... | grep -v cmd/feature_experimentation/analyze/code-samples` -coverprofile coverage/cover.out.tmp - cat coverage/cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze/code-samples" > coverage/cover.out + go test -v -race `go list ./... | grep -v cmd/feature_experimentation/analyze | grep -v cmd/feature_experimentation/resource` -coverprofile coverage/cover.out.tmp + cat coverage/cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze" | grep -v "mock_\|cmd/feature_experimentation/resource" > coverage/cover.out go tool cover -html=coverage/cover.out -o coverage/cover.html go tool cover -func=coverage/cover.out \ No newline at end of file diff --git a/cmd/feature_experimentation/account/current.go b/cmd/feature_experimentation/account/current.go index 067297c..95e6823 100644 --- a/cmd/feature_experimentation/account/current.go +++ b/cmd/feature_experimentation/account/current.go @@ -25,7 +25,12 @@ var currentCmd = &cobra.Command{ var accountYaml models.AccountYaml var account models.AccountJSON - yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/feature_experimentation/account_environment/account_environment_test.go b/cmd/feature_experimentation/account_environment/account_environment_test.go index b9f3581..c7980a3 100644 --- a/cmd/feature_experimentation/account_environment/account_environment_test.go +++ b/cmd/feature_experimentation/account_environment/account_environment_test.go @@ -5,11 +5,11 @@ import ( "testing" "github.com/flagship-io/flagship/models" + models_fe "github.com/flagship-io/flagship/models/feature_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" - "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -22,12 +22,14 @@ func TestMain(m *testing.M) { mockfunction.SetMock(&http_request.ResourceRequester) - mockfunction_fe.APIToken() + mockfunction_fe.APIAccountEnvironment() m.Run() } var testAccount models.AccountJSON +var testAccountEnvironment models_fe.AccountEnvironmentFE +var testAccountEnvironmentList []models_fe.AccountEnvironmentFE func TestAccountEnvironmentCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AccountEnvironmentCmd) @@ -56,5 +58,16 @@ func TestAccountEnvironmentCurrentCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, web_experimentation.TestAccount.AccountEnvironmentID, testAccount.AccountEnvironmentID) + assert.Equal(t, mockfunction_fe.TestAccountEnvironment.Id, testAccount.AccountEnvironmentID) +} + +func TestAccountEnvironmentListCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AccountEnvironmentCmd, "list") + + err := json.Unmarshal([]byte(output), &testAccountEnvironmentList) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_fe.TestAccountEnvironmentList, testAccountEnvironmentList) } diff --git a/cmd/feature_experimentation/account_environment/current.go b/cmd/feature_experimentation/account_environment/current.go index 4afc191..9098995 100644 --- a/cmd/feature_experimentation/account_environment/current.go +++ b/cmd/feature_experimentation/account_environment/current.go @@ -25,7 +25,12 @@ var currentCmd = &cobra.Command{ var accountYaml models.AccountYaml var account models.AccountJSON - yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/feature_experimentation/auth/current.go b/cmd/feature_experimentation/auth/current.go index e001e2f..6923635 100644 --- a/cmd/feature_experimentation/auth/current.go +++ b/cmd/feature_experimentation/auth/current.go @@ -24,7 +24,12 @@ var currentCmd = &cobra.Command{ var accountYaml models.AccountYaml var account models.AccountJSON - yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI)) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/feature_experimentation/auth/delete.go b/cmd/feature_experimentation/auth/delete.go index 7ab9229..775e2d8 100644 --- a/cmd/feature_experimentation/auth/delete.go +++ b/cmd/feature_experimentation/auth/delete.go @@ -20,9 +20,17 @@ var deleteCmd = &cobra.Command{ Long: `Delete an auth`, Run: func(cmd *cobra.Command, args []string) { - config.CheckABTastyHomeDirectory() + _, err := config.CheckABTastyHomeDirectory() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %s", err) + } - if err := os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username)); err != nil { + if err := os.Remove(credPath); err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/feature_experimentation/auth/get.go b/cmd/feature_experimentation/auth/get.go index 5545d39..26e9267 100644 --- a/cmd/feature_experimentation/auth/get.go +++ b/cmd/feature_experimentation/auth/get.go @@ -25,7 +25,12 @@ var getCmd = &cobra.Command{ var authYaml models.AuthYaml var auth models.Auth - yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username)) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/feature_experimentation/auth/list.go b/cmd/feature_experimentation/auth/list.go index fda5543..e4709e9 100644 --- a/cmd/feature_experimentation/auth/list.go +++ b/cmd/feature_experimentation/auth/list.go @@ -32,7 +32,12 @@ var listCmd = &cobra.Command{ if fileName != "" { var authYaml models.AuthYaml var auth models.Auth - yamlFile, err := os.ReadFile(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, fileName)) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, fileName) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/account/current.go b/cmd/web_experimentation/account/current.go index c3df613..9d0c192 100644 --- a/cmd/web_experimentation/account/current.go +++ b/cmd/web_experimentation/account/current.go @@ -25,7 +25,12 @@ var currentCmd = &cobra.Command{ var accountYaml models.AccountYaml var account models.AccountJSON - yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI)) + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/account_global_code/get.go b/cmd/web_experimentation/account_global_code/get.go index 24ad011..7f564f9 100644 --- a/cmd/web_experimentation/account_global_code/get.go +++ b/cmd/web_experimentation/account_global_code/get.go @@ -28,7 +28,10 @@ var getCmd = &cobra.Command{ } if createFile { - accountCodeDir := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body) + accountCodeDir, err := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body) + if err != nil { + log.Fatalf("error occurred: %s", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Account code file generated successfully: ", accountCodeDir) return } diff --git a/cmd/web_experimentation/auth/current.go b/cmd/web_experimentation/auth/current.go index 5a4d7d5..2856ca7 100644 --- a/cmd/web_experimentation/auth/current.go +++ b/cmd/web_experimentation/auth/current.go @@ -24,7 +24,12 @@ var currentCmd = &cobra.Command{ var accountYaml models.AccountYaml var account models.AccountJSON - yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI)) + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/auth/delete.go b/cmd/web_experimentation/auth/delete.go index 4ef3909..9f5390d 100644 --- a/cmd/web_experimentation/auth/delete.go +++ b/cmd/web_experimentation/auth/delete.go @@ -20,9 +20,17 @@ var deleteCmd = &cobra.Command{ Long: `Delete an auth`, Run: func(cmd *cobra.Command, args []string) { - config.CheckABTastyHomeDirectory() + _, err := config.CheckABTastyHomeDirectory() + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } - if err := os.Remove(config.CredentialPath(utils.WEB_EXPERIMENTATION, Username)); err != nil { + if err := os.Remove(credPath); err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/auth/get.go b/cmd/web_experimentation/auth/get.go index d0269bb..72f0e40 100644 --- a/cmd/web_experimentation/auth/get.go +++ b/cmd/web_experimentation/auth/get.go @@ -25,7 +25,12 @@ var getCmd = &cobra.Command{ var authYaml models.AuthYaml var auth models.Auth - yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, Username)) + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/auth/list.go b/cmd/web_experimentation/auth/list.go index b4c037a..dde2fa7 100644 --- a/cmd/web_experimentation/auth/list.go +++ b/cmd/web_experimentation/auth/list.go @@ -32,7 +32,12 @@ var listCmd = &cobra.Command{ if fileName != "" { var authYaml models.AuthYaml var auth models.Auth - yamlFile, err := os.ReadFile(config.CredentialPath(utils.WEB_EXPERIMENTATION, fileName)) + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, fileName) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + yamlFile, err := os.ReadFile(credPath) if err != nil { log.Fatalf("error occurred: %s", err) } diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 1faf497..5966f11 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -30,7 +30,10 @@ var getCmd = &cobra.Command{ } if createFile { - campaignCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + campaignCodeDir, err := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + if err != nil { + log.Fatalf("error occurred: %v", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Campaign code file generated successfully: ", campaignCodeDir) return } @@ -42,8 +45,10 @@ var getCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - campaignCodeDir := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) - + campaignCodeDir, err := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + if err != nil { + log.Fatalf("error occurred: %v", err) + } body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) if err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/element_modification_code/get.go index 2eaca87..2f816d0 100644 --- a/cmd/web_experimentation/element_modification_code/get.go +++ b/cmd/web_experimentation/element_modification_code/get.go @@ -48,7 +48,11 @@ var getCmd = &cobra.Command{ if CreateFile { fileCode := config.AddHeaderSelectorComment(selector, code) - elementModificationCodeDir := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode) + elementModificationCodeDir, err := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "Element code file generated successfully: ", elementModificationCodeDir) return } diff --git a/cmd/web_experimentation/variation_global_code/get-css.go b/cmd/web_experimentation/variation_global_code/get-css.go index af354c9..a32d440 100644 --- a/cmd/web_experimentation/variation_global_code/get-css.go +++ b/cmd/web_experimentation/variation_global_code/get-css.go @@ -43,7 +43,11 @@ var getCSSCmd = &cobra.Command{ } if CreateFile { - campaignCodeDir := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, cssCode) + campaignCodeDir, err := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, cssCode) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "Variation code file generated successfully: ", campaignCodeDir) return } diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go index c4dc89a..ebf9ee3 100644 --- a/cmd/web_experimentation/variation_global_code/get-js.go +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -43,7 +43,10 @@ var getJSCmd = &cobra.Command{ } if CreateFile { - variationCodeDir := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, jsCode) + variationCodeDir, err := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, jsCode) + if err != nil { + log.Fatalf("error occurred: %v", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Variation code file generated successfully: ", variationCodeDir) return } diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go index a9191d8..9b00add 100644 --- a/utils/config/config_global_code.go +++ b/utils/config/config_global_code.go @@ -2,7 +2,6 @@ package config import ( "errors" - "log" "os" ) @@ -17,115 +16,132 @@ func CheckWorkingDirectory(workingDir string) (string, error) { return workingDir, nil } -func CheckGlobalCodeDirectory(workingDir string) string { - +func CheckGlobalCodeDirectory(workingDir string) (string, error) { wd, err := CheckWorkingDirectory(workingDir) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } gcWorkingDir := wd + "/abtasty" err = os.MkdirAll(gcWorkingDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } - return gcWorkingDir + return gcWorkingDir, nil } -func AccountGlobalCodeDirectory(workingDir, accountID, code string) string { - gcWorkingDir := CheckGlobalCodeDirectory(workingDir) +func AccountGlobalCodeDirectory(workingDir, accountID, code string) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) + if err != nil { + return "", err + } accountCodeDir := gcWorkingDir + "/" + accountID - err := os.MkdirAll(accountCodeDir, os.ModePerm) + err = os.MkdirAll(accountCodeDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } jsFilePath := accountCodeDir + "/accountGlobalCode.js" err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { - log.Fatalf("Error writing JavaScript file: %s", err) + return "", err } - return jsFilePath + return jsFilePath, nil } -func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) string { - gcWorkingDir := CheckGlobalCodeDirectory(workingDir) +func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) + if err != nil { + return "", err + } accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID - err := os.MkdirAll(campaignCodeDir, os.ModePerm) + err = os.MkdirAll(campaignCodeDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } jsFilePath := campaignCodeDir + "/campaignGlobalCode.js" err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { - log.Fatalf("Error writing JavaScript file: %s", err) + return "", err } - return jsFilePath + + return jsFilePath, nil } -func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variationID, code string) string { - gcWorkingDir := CheckGlobalCodeDirectory(workingDir) +func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variationID, code string) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) + if err != nil { + return "", err + } accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID variationCodeDir := campaignCodeDir + "/" + variationID - err := os.MkdirAll(variationCodeDir, os.ModePerm) + err = os.MkdirAll(variationCodeDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } jsFilePath := variationCodeDir + "/variationGlobalCode.js" err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { - log.Fatalf("Error writing JavaScript file: %s", err) + return "", err } - return jsFilePath + return jsFilePath, nil } -func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variationID, code string) string { - gcWorkingDir := CheckGlobalCodeDirectory(workingDir) +func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variationID, code string) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) + if err != nil { + return "", err + } + accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID variationCodeDir := campaignCodeDir + "/" + variationID - err := os.MkdirAll(variationCodeDir, os.ModePerm) + err = os.MkdirAll(variationCodeDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } jsFilePath := variationCodeDir + "/variationGlobalCode.css" err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { - log.Fatalf("Error writing CSS file: %s", err) + return "", err } - return jsFilePath + return jsFilePath, nil } -func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte) string { - gcWorkingDir := CheckGlobalCodeDirectory(workingDir) +func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) + if err != nil { + return "", err + } + accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID variationCodeDir := campaignCodeDir + "/" + variationID elementCodeDir := variationCodeDir + "/" + elementID - err := os.MkdirAll(elementCodeDir, os.ModePerm) + err = os.MkdirAll(elementCodeDir, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } jsFilePath := elementCodeDir + "/element.js" err = os.WriteFile(jsFilePath, code, os.ModePerm) if err != nil { - log.Fatalf("Error writing JavaScript file: %s", err) + return "", err } - return jsFilePath + return jsFilePath, nil } func AddHeaderSelectorComment(selector, code string) []byte { diff --git a/utils/config/config_global_code_test.go b/utils/config/config_global_code_test.go new file mode 100644 index 0000000..0549a36 --- /dev/null +++ b/utils/config/config_global_code_test.go @@ -0,0 +1,335 @@ +package config + +import ( + "log" + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +type TestStruct struct { + name string + workingDir string + want string + code string + accountID string + campaignID string + variationID string + elementID string + selector string + wantErr bool +} + +var ( + mockAccountID = "123456" + mockCampaignID = "100000" + mockVariationID = "200000" + mockElementID = "300000" + mockSelector = "document.querySelector('main')" +) + +func TestMain(m *testing.M) { + currentDir, err := os.Getwd() + if err != nil { + log.Fatalf("Failed to get current working directory: %v", err) + } + + defer os.RemoveAll(currentDir + "/abtasty") + + m.Run() +} + +func TestCheckWorkingDirectory(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + want: currentDir, + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + want: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := CheckWorkingDirectory(tt.workingDir) + if (err != nil) != tt.wantErr { + t.Errorf("CheckWorkingDirectory() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("CheckWorkingDirectory() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCheckGlobalCodeDirectory(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + want: currentDir + "/abtasty", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + want: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := CheckGlobalCodeDirectory(tt.workingDir) + if (err != nil) != tt.wantErr { + t.Errorf("CheckGlobalCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("CheckGlobalCodeDirectory() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestAccountGlobalCodeDirectory(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: mockAccountID, + want: currentDir + "/abtasty/" + mockAccountID + "/accountGlobalCode.js", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: mockAccountID, + want: "", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := AccountGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.code) + if (err != nil) != tt.wantErr { + t.Errorf("AccountGlobalCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Errorf("AccountGlobalCodeDirectory() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCampaignGlobalCodeDirectory(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: "123456", + campaignID: "100000", + want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/campaignGlobalCode.js", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: "123456", + campaignID: "100000", + want: "", + wantErr: true, + }, + } + + for i, tt := range tests { + if i == 0 { + t.Run(tt.name, func(t *testing.T) { + got, err := CampaignGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.code) + if (err != nil) != tt.wantErr { + t.Errorf("CampaignGlobalCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Errorf("CampaignGlobalCodeDirectory() = %v, want %v", got, tt.want) + } + }) + + } + } +} + +func TestVariationGlobalCodeDirectoryJS(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/" + mockVariationID + "/variationGlobalCode.js", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: "console.log('Hello, World!')", // Content of JavaScript file + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + want: "", + wantErr: true, + }, + } + + for i, tt := range tests { + if i == 0 { + t.Run(tt.name, func(t *testing.T) { + got, err := VariationGlobalCodeDirectoryJS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code) + if (err != nil) != tt.wantErr { + t.Errorf("VariationGlobalCodeDirectoryJS() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Errorf("VariationGlobalCodeDirectoryJS() = %v, want %v", got, tt.want) + } + }) + + } + } +} + +func TestVariationGlobalCodeDirectoryCSS(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + code: ".id{ \"color\" : black}", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/" + mockVariationID + "/variationGlobalCode.css", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: ".id{ \"color\" : black}", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + want: "", + wantErr: true, + }, + } + + for i, tt := range tests { + if i == 0 { + t.Run(tt.name, func(t *testing.T) { + got, err := VariationGlobalCodeDirectoryCSS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code) + if (err != nil) != tt.wantErr { + t.Errorf("VariationGlobalCodeDirectoryCSS() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Errorf("VariationGlobalCodeDirectoryCSS() = %v, want %v", got, tt.want) + } + }) + + } + } +} + +func TestElementModificationCodeDirectory(t *testing.T) { + currentDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current working directory: %v", err) + } + + tests := []TestStruct{ + { + name: "ExistingDirectory", + workingDir: currentDir, + code: "console.log('Hello, World!')", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + elementID: mockElementID, + selector: mockSelector, + want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/" + mockVariationID + "/" + mockElementID + "/element.js", + wantErr: false, + }, + { + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: "console.log('Hello, World!')", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + elementID: mockElementID, + selector: mockSelector, + want: "", + wantErr: true, + }, + } + + for i, tt := range tests { + if i == 0 { + t.Run(tt.name, func(t *testing.T) { + got, err := ElementModificationCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.elementID, tt.selector, []byte(tt.code)) + if (err != nil) != tt.wantErr { + t.Errorf("ElementModificationCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) + } + if got != tt.want { + t.Errorf("ElementModificationCodeDirectory() = %v, want %v", got, tt.want) + } + }) + + } + } +} + +func TestAddHeaderSelectorComment(t *testing.T) { + fileCode := AddHeaderSelectorComment("example selector", "console.log('Hello World !')") + fileContent := []byte("/* Selector: example selector */\nconsole.log('Hello World !')") + assert.Equal(t, fileContent, fileCode) +} diff --git a/utils/http_request/feature_experimentation/main_test.go b/utils/http_request/feature_experimentation/main_test.go index 40068eb..74a2d5b 100644 --- a/utils/http_request/feature_experimentation/main_test.go +++ b/utils/http_request/feature_experimentation/main_test.go @@ -20,6 +20,7 @@ func TestMain(m *testing.M) { mockfunction.APIProject() mockfunction.APICampaign() + mockfunction.APIAccountEnvironment() mockfunction.APIFlag() mockfunction.APIGoal() mockfunction.APITargetingKey() diff --git a/utils/mock_function/feature_experimentation/account_environment.go b/utils/mock_function/feature_experimentation/account_environment.go new file mode 100644 index 0000000..99ae801 --- /dev/null +++ b/utils/mock_function/feature_experimentation/account_environment.go @@ -0,0 +1,56 @@ +package feature_experimentation + +import ( + "net/http" + + models_fe "github.com/flagship-io/flagship/models/feature_experimentation" + "github.com/flagship-io/flagship/utils" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + "github.com/jarcoal/httpmock" +) + +var TestAccountEnvironment = models_fe.AccountEnvironmentFE{ + Id: "account_environment_id", + Environment: "account_environment_name", + IsMain: true, + Panic: false, + SingleAssignment: false, +} + +var TestAccountEnvironment1 = models_fe.AccountEnvironmentFE{ + Id: "account_environment_id1", + Environment: "account_environment_name1", + IsMain: true, + Panic: false, + SingleAssignment: false, +} + +var TestAccountEnvironmentList = []models_fe.AccountEnvironmentFE{ + TestAccountEnvironment, TestAccountEnvironment1, +} + +func APIAccountEnvironment() { + + resp := utils.HTTPListResponseFE[models_fe.AccountEnvironmentFE]{ + Items: TestAccountEnvironmentList, + CurrentItemsCount: 2, + CurrentPage: 1, + TotalCount: 2, + ItemsPerPage: 10, + LastPage: 1, + } + + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, resp) + return resp, nil + }, + ) + + httpmock.RegisterResponder("GET", utils.GetFeatureExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/account_environments/"+TestAccountEnvironment.Id, + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestAccountEnvironment) + return resp, nil + }, + ) +} diff --git a/utils/mock_function/feature_experimentation/auth.go b/utils/mock_function/feature_experimentation/auth.go index f070e6a..233d3cd 100644 --- a/utils/mock_function/feature_experimentation/auth.go +++ b/utils/mock_function/feature_experimentation/auth.go @@ -1,6 +1,7 @@ package feature_experimentation import ( + "log" "os" "github.com/flagship-io/flagship/models" @@ -17,5 +18,10 @@ var TestAuth = models.Auth{ } func InitMockAuth() { - os.Remove(config.CredentialPath(utils.FEATURE_EXPERIMENTATION, "test_auth")) + credPath, err := config.CredentialPath(utils.FEATURE_EXPERIMENTATION, "test_auth") + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + os.Remove(credPath) } diff --git a/utils/mock_function/web_experimentation/auth.go b/utils/mock_function/web_experimentation/auth.go index 40d88f4..3e1de73 100644 --- a/utils/mock_function/web_experimentation/auth.go +++ b/utils/mock_function/web_experimentation/auth.go @@ -1,6 +1,7 @@ package web_experimentation import ( + "log" "os" "github.com/flagship-io/flagship/models" @@ -17,5 +18,10 @@ var TestAuth = models.Auth{ } func InitMockAuth() { - os.Remove(config.CredentialPath(utils.WEB_EXPERIMENTATION, "test_auth")) + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, "test_auth") + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + os.Remove(credPath) } From 2e533acf75b8a9b6f6cb02cbe2f1504937bea4ac Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 24 Apr 2024 18:42:44 +0200 Subject: [PATCH 31/48] add some unit test --- utils/config/config_global_code_test.go | 12 --- utils/config/config_test.go | 133 ++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 utils/config/config_test.go diff --git a/utils/config/config_global_code_test.go b/utils/config/config_global_code_test.go index 0549a36..2009562 100644 --- a/utils/config/config_global_code_test.go +++ b/utils/config/config_global_code_test.go @@ -1,7 +1,6 @@ package config import ( - "log" "os" "testing" @@ -29,17 +28,6 @@ var ( mockSelector = "document.querySelector('main')" ) -func TestMain(m *testing.M) { - currentDir, err := os.Getwd() - if err != nil { - log.Fatalf("Failed to get current working directory: %v", err) - } - - defer os.RemoveAll(currentDir + "/abtasty") - - m.Run() -} - func TestCheckWorkingDirectory(t *testing.T) { currentDir, err := os.Getwd() if err != nil { diff --git a/utils/config/config_test.go b/utils/config/config_test.go new file mode 100644 index 0000000..d5204f5 --- /dev/null +++ b/utils/config/config_test.go @@ -0,0 +1,133 @@ +package config + +import ( + "errors" + "fmt" + "log" + "os" + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/stretchr/testify/assert" +) + +var ( + product = "test_product" + username = "test_user" + clientID = "client_id" + clientSecret = "client_secret" + accessToken = "access_token" + refreshToken = "refresh_token" +) +var authResponse = models.TokenResponse{ + AccessToken: accessToken, + RefreshToken: refreshToken, +} + +func TestMain(m *testing.M) { + + currentDir, err := os.Getwd() + if err != nil { + log.Fatalf("Failed to get current working directory: %v", err) + } + + homeDir, err := os.UserHomeDir() + if err != nil { + log.Fatalf("Failed to get user home directory: %v", err) + } + + if _, err := os.Stat(homeDir + "/.flagship/credentials/" + product); errors.Is(err, os.ErrNotExist) { + os.MkdirAll(homeDir+"/.flagship/credentials/"+product, os.ModePerm) + } + + defer os.RemoveAll(currentDir + "/abtasty") + defer os.RemoveAll(homeDir + "/.flagship/credentials/" + product) + + m.Run() +} + +func TestCheckABTastyHomeDirectory(t *testing.T) { + homeDir, err := os.UserHomeDir() + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + abtastyHome, err := CheckABTastyHomeDirectory() + if err != nil { + t.Errorf("CheckABTastyHomeDirectory() error = %v", err) + } + + assert.Equal(t, homeDir, abtastyHome) + assert.Equal(t, homeDir+"/.flagship/credentials/"+utils.FEATURE_EXPERIMENTATION, abtastyHome+"/.flagship/credentials/"+utils.FEATURE_EXPERIMENTATION) + assert.Equal(t, homeDir+"/.flagship/credentials/"+utils.WEB_EXPERIMENTATION, abtastyHome+"/.flagship/credentials/"+utils.WEB_EXPERIMENTATION) + assert.Equal(t, homeDir+"/.flagship/credentials/"+product, abtastyHome+"/.flagship/credentials/"+product) + +} + +func TestCredentialPath(t *testing.T) { + + // Save initial state + homeDir, err := os.UserHomeDir() + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + filepath, err := CredentialPath(product, username) + if err != nil { + t.Errorf("CredentialPath() error = %v", err) + } + + // Assertions + expectedPath := homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml" + assert.Equal(t, expectedPath, filepath) + +} + +func TestGetUsernames(t *testing.T) { + + // Create authentication response + + // Execute the function + CreateAuthFile(product, username, clientID, clientSecret, authResponse) + + // Execute the function + fileNames, err := GetUsernames(product) + if err != nil { + t.Errorf("GetUsernames() error = %v", err) + } + + // Assertions + if len(fileNames) != 1 || fileNames[0] != "test_user" { + t.Errorf("GetUsernames() returned unexpected file names: %v", fileNames) + } +} + +func TestCreateAuthFile(t *testing.T) { + + // Save initial state + homeDir, err := os.UserHomeDir() + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + // Execute the function + CreateAuthFile(product, username, clientID, clientSecret, authResponse) + + // Read the content of the created file + fileContent, err := os.ReadFile(homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml") + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + // Assert the content of the file + expectedContent := fmt.Sprintf(`client_id: %s +client_secret: %s +refresh_token: %s +token: %s +username: %s +`, clientID, clientSecret, refreshToken, accessToken, username) + + assert.Equal(t, expectedContent, string(fileContent)) + +} From f9877c39523f59f38ec4314aa968b7ca3d6a0bf1 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 25 Apr 2024 17:53:02 +0200 Subject: [PATCH 32/48] add some test for utils config and functions --- cmd/feature_experimentation/account/use.go | 5 +- .../account_environment/use.go | 5 +- cmd/feature_experimentation/auth/login.go | 60 +++++-- .../feature_experimentation.go | 6 +- .../account/account_test.go | 15 +- cmd/web_experimentation/account/use.go | 5 +- cmd/web_experimentation/auth/login.go | 17 +- .../web_experimentation.go | 7 +- utils/config/config.go | 122 ++++++++----- utils/config/config_test.go | 169 ++++++++++++++++-- utils/functions_test.go | 26 +++ utils/http_request/common/request.go | 5 +- .../web_experimentation/account.go | 2 +- .../web_experimentation/account.go | 17 ++ 14 files changed, 379 insertions(+), 82 deletions(-) create mode 100644 utils/functions_test.go diff --git a/cmd/feature_experimentation/account/use.go b/cmd/feature_experimentation/account/use.go index 87b2279..14312d9 100644 --- a/cmd/feature_experimentation/account/use.go +++ b/cmd/feature_experimentation/account/use.go @@ -23,7 +23,10 @@ var useCmd = &cobra.Command{ return } - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) + err := config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountID) + if err != nil { + log.Fatalf("error occurred: %s", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Account ID set to : "+AccountID) diff --git a/cmd/feature_experimentation/account_environment/use.go b/cmd/feature_experimentation/account_environment/use.go index 701ec0f..090ddba 100644 --- a/cmd/feature_experimentation/account_environment/use.go +++ b/cmd/feature_experimentation/account_environment/use.go @@ -23,7 +23,10 @@ var useCmd = &cobra.Command{ return } - config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) + err := config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, AccountEnvironmentID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Account Environment ID set to : "+AccountEnvironmentID) diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 8506a43..3f7a0f7 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -5,6 +5,7 @@ package auth import ( "fmt" + "log" "slices" "github.com/flagship-io/flagship/utils" @@ -41,7 +42,11 @@ var loginCmd = &cobra.Command{ } if credentialsFile != "" { - v := config.ReadCredentialsFromFile(credentialsFile) + v, err := config.ReadCredentialsFromFile(credentialsFile) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + if v.GetString("username") == "" || v.GetString("client_id") == "" || v.GetString("client_secret") == "" || v.GetString("account_id") == "" { fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") return @@ -51,12 +56,29 @@ var loginCmd = &cobra.Command{ fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) return } - config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) - config.SelectAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("username")) - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_id")) + + err = config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SelectAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("username")) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SetAccountID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_id")) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + if v.GetString("account_environment_id") != "" { - config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_environment_id")) + err := config.SetAccountEnvID(utils.FEATURE_EXPERIMENTATION, v.GetString("account_environment_id")) + if err != nil { + log.Fatalf("error occurred: %v", err) + } } + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") return } @@ -69,8 +91,15 @@ var loginCmd = &cobra.Command{ } if slices.Contains(existingCredentials, Username) { if AccountId != "" { - config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + err := config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + if err != nil { + log.Fatalf("error occurred: %s", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) return @@ -94,9 +123,20 @@ var loginCmd = &cobra.Command{ return } - config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) - config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) - config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + err = config.CreateAuthFile(utils.FEATURE_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SetAccountID(utils.FEATURE_EXPERIMENTATION, AccountId) + if err != nil { + log.Fatalf("error occurred: %s", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") } diff --git a/cmd/feature_experimentation/feature_experimentation.go b/cmd/feature_experimentation/feature_experimentation.go index 1742ca5..c453f47 100644 --- a/cmd/feature_experimentation/feature_experimentation.go +++ b/cmd/feature_experimentation/feature_experimentation.go @@ -4,6 +4,7 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package feature_experimentation import ( + "log" "os" "github.com/flagship-io/flagship/cmd/feature_experimentation/account" @@ -74,7 +75,10 @@ func initConfig() { v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION + "/.cli.yaml") v.MergeInConfig() if v.GetString("current_used_credential") != "" { - vL := config.ReadAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("current_used_credential")) + vL, err := config.ReadAuth(utils.FEATURE_EXPERIMENTATION, v.GetString("current_used_credential")) + if err != nil { + log.Fatalf("error occurred: %v", err) + } v.MergeConfigMap(vL.AllSettings()) } diff --git a/cmd/web_experimentation/account/account_test.go b/cmd/web_experimentation/account/account_test.go index 4299e77..b14b066 100644 --- a/cmd/web_experimentation/account/account_test.go +++ b/cmd/web_experimentation/account/account_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/flagship-io/flagship/models" + models_we "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" @@ -22,12 +23,13 @@ func TestMain(m *testing.M) { mockfunction.SetMock(&http_request.ResourceRequester) - mockfunction_we.APIToken() + mockfunction_we.APIAccount() m.Run() } var testAccount models.AccountJSON +var testAccounts []models_we.AccountWE func TestAccountCommand(t *testing.T) { output, _ := utils.ExecuteCommand(AccountCmd) @@ -58,3 +60,14 @@ func TestAccountCurrentCommand(t *testing.T) { assert.Equal(t, web_experimentation.TestAccount.AccountID, testAccount.AccountID) } + +func TestAccountListCommand(t *testing.T) { + + output, _ := utils.ExecuteCommand(AccountCmd, "list") + + err := json.Unmarshal([]byte(output), &testAccounts) + + assert.Nil(t, err) + + assert.Equal(t, web_experimentation.TestAccountGlobalCode.Id, testAccounts[0].Id) +} diff --git a/cmd/web_experimentation/account/use.go b/cmd/web_experimentation/account/use.go index b50bbd6..8a2af14 100644 --- a/cmd/web_experimentation/account/use.go +++ b/cmd/web_experimentation/account/use.go @@ -23,7 +23,10 @@ var useCmd = &cobra.Command{ return } - config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) + err := config.SetAccountID(utils.WEB_EXPERIMENTATION, AccountID) + if err != nil { + log.Fatalf("error occurred: %s", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Account ID set to : "+AccountID) diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index ad0d5ee..ac322fd 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -121,7 +121,10 @@ var loginCmd = &cobra.Command{ log.Fatalf("error occurred: %s", err) } if slices.Contains(existingCredentials, Username) { - config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + err := config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) return @@ -140,8 +143,16 @@ var loginCmd = &cobra.Command{ if authenticationResponse.AccessToken == "" { log.Fatal("Credentials not valid.") } - config.CreateAuthFile(utils.WEB_EXPERIMENTATION, Username, "", "", authenticationResponse) - config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + + err = config.CreateAuthFile(utils.WEB_EXPERIMENTATION, Username, "", "", authenticationResponse) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 0c05470..ef22cfc 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -4,6 +4,7 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package web_experimentation import ( + "log" "os" "github.com/flagship-io/flagship/cmd/web_experimentation/account" @@ -60,7 +61,11 @@ func initConfig() { v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") v.MergeInConfig() if v.GetString("current_used_credential") != "" { - vL := config.ReadAuth(utils.WEB_EXPERIMENTATION, v.GetString("current_used_credential")) + vL, err := config.ReadAuth(utils.WEB_EXPERIMENTATION, v.GetString("current_used_credential")) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + v.MergeConfigMap(vL.AllSettings()) } diff --git a/utils/config/config.go b/utils/config/config.go index 638832b..38477b1 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -1,11 +1,8 @@ package config import ( - "bytes" - "encoding/json" "errors" "fmt" - "log" "os" "path/filepath" "regexp" @@ -15,49 +12,46 @@ import ( "github.com/spf13/viper" ) -func Unset(key string) error { - configMap := viper.AllSettings() - delete(configMap, key) - encodedConfig, _ := json.MarshalIndent(configMap, "", " ") - err := viper.ReadConfig(bytes.NewReader(encodedConfig)) - if err != nil { - return err - } - viper.WriteConfig() - return nil -} - func CheckABTastyHomeDirectory() (string, error) { homeDir, err := os.UserHomeDir() if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.FEATURE_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.FEATURE_EXPERIMENTATION, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } } if _, err := os.Stat(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION); errors.Is(err, os.ErrNotExist) { err := os.MkdirAll(homeDir+"/.flagship/credentials/"+utils.WEB_EXPERIMENTATION, os.ModePerm) if err != nil { - log.Fatalf("error occurred: %s", err) + return "", err } } return homeDir, err } -func CredentialPath(product, username string) string { - homeDir, _ := CheckABTastyHomeDirectory() +func CredentialPath(product, username string) (string, error) { + homeDir, err := CheckABTastyHomeDirectory() + if err != nil { + return "", err + } + filepath, err := filepath.Abs(homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml") if err != nil { - log.Fatalf("error occured: %s", err) + return "", err } - return filepath + + return filepath, nil } func GetUsernames(product string) ([]string, error) { homeDir, err := CheckABTastyHomeDirectory() + if err != nil { + return nil, err + } + r := regexp.MustCompile(`(?P[^/]+)\.yaml`) var fileNames []string @@ -77,7 +71,8 @@ func GetUsernames(product string) ([]string, error) { match := r.FindStringSubmatch(v.Name()) userName := r.SubexpIndex("Username") if len(match) == 0 { - log.Fatalln("Error: File not found") + err := errors.New("Error: File not found") + return nil, err } fileNames = append(fileNames, match[userName]) @@ -85,9 +80,12 @@ func GetUsernames(product string) ([]string, error) { return fileNames, nil } -func CreateAuthFile(product, username, clientId, clientSecret string, authenticationResponse models.TokenResponse) { +func CreateAuthFile(product, username, clientId, clientSecret string, authenticationResponse models.TokenResponse) error { v := viper.New() - filepath := CredentialPath(product, username) + filepath, err := CredentialPath(product, username) + if err != nil { + return err + } v.Set("username", username) v.Set("client_id", clientId) @@ -95,78 +93,104 @@ func CreateAuthFile(product, username, clientId, clientSecret string, authentica v.Set("token", authenticationResponse.AccessToken) v.Set("refresh_token", authenticationResponse.RefreshToken) - err := v.WriteConfigAs(filepath) + err = v.WriteConfigAs(filepath) if err != nil { - log.Fatalf("error occurred: %v", err) + return err } + + return nil } -func ReadAuth(product, AuthName string) *viper.Viper { +func ReadAuth(product, AuthName string) (*viper.Viper, error) { v := viper.New() - configFilepath := CredentialPath(product, AuthName) + configFilepath, err := CredentialPath(product, AuthName) + if err != nil { + return nil, err + } + if _, err := os.Stat(configFilepath); errors.Is(err, os.ErrNotExist) { fmt.Fprintf(os.Stderr, "error occurred: %v \n", err) } v.SetConfigFile(configFilepath) v.MergeInConfig() - return v + return v, nil } -func SelectAuth(product, AuthName string) { +func SelectAuth(product, AuthName string) error { var v = viper.New() - filepath := CredentialPath(product, utils.HOME_CLI) + filepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + return err + } + v.Set("current_used_credential", AuthName) - err := v.WriteConfigAs(filepath) + err = v.WriteConfigAs(filepath) if err != nil { - log.Fatalf("error occurred: %v", err) + return err } + return nil } -func SetAccountID(product, accountID string) { +func SetAccountID(product, accountID string) error { var v = viper.New() - configFilepath := CredentialPath(product, utils.HOME_CLI) + configFilepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + return err + } + v.SetConfigFile(configFilepath) v.MergeInConfig() v.Set("account_id", accountID) - err := v.WriteConfigAs(configFilepath) + err = v.WriteConfigAs(configFilepath) if err != nil { - log.Fatalf("error occurred: %v", err) + return err } + + return nil } -func SetAccountEnvID(product, accountEnvID string) { +func SetAccountEnvID(product, accountEnvID string) error { var v = viper.New() - configFilepath := CredentialPath(product, utils.HOME_CLI) + configFilepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + return err + } + v.SetConfigFile(configFilepath) v.MergeInConfig() v.Set("account_environment_id", accountEnvID) - err := v.WriteConfigAs(configFilepath) + err = v.WriteConfigAs(configFilepath) if err != nil { - log.Fatalf("error occurred: %v", err) + return err } + + return nil } -func ReadCredentialsFromFile(AuthFile string) *viper.Viper { +func ReadCredentialsFromFile(AuthFile string) (*viper.Viper, error) { var v = viper.New() v.SetConfigFile(AuthFile) err := v.MergeInConfig() if err != nil { - log.Fatalf("error occurred: %v", err) + return nil, err } - return v + return v, nil } -func WriteToken(product, AuthName string, authenticationResponse models.TokenResponse) { +func WriteToken(product, AuthName string, authenticationResponse models.TokenResponse) error { v := viper.New() - configFilepath := CredentialPath(product, AuthName) + configFilepath, err := CredentialPath(product, AuthName) + if err != nil { + return err + } v.SetConfigFile(configFilepath) @@ -174,8 +198,10 @@ func WriteToken(product, AuthName string, authenticationResponse models.TokenRes v.Set("token", authenticationResponse.AccessToken) v.Set("refresh_token", authenticationResponse.RefreshToken) - err := v.WriteConfigAs(configFilepath) + err = v.WriteConfigAs(configFilepath) if err != nil { - log.Fatalf("error occurred: %v", err) + return err } + + return nil } diff --git a/utils/config/config_test.go b/utils/config/config_test.go index d5204f5..b202fb4 100644 --- a/utils/config/config_test.go +++ b/utils/config/config_test.go @@ -19,6 +19,8 @@ var ( clientSecret = "client_secret" accessToken = "access_token" refreshToken = "refresh_token" + accountID = "account_id" + accountEnvID = "account_environment_id" ) var authResponse = models.TokenResponse{ AccessToken: accessToken, @@ -67,7 +69,6 @@ func TestCheckABTastyHomeDirectory(t *testing.T) { func TestCredentialPath(t *testing.T) { - // Save initial state homeDir, err := os.UserHomeDir() if err != nil { t.Fatalf("Failed to get user home directory: %v", err) @@ -78,7 +79,6 @@ func TestCredentialPath(t *testing.T) { t.Errorf("CredentialPath() error = %v", err) } - // Assertions expectedPath := homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml" assert.Equal(t, expectedPath, filepath) @@ -86,18 +86,16 @@ func TestCredentialPath(t *testing.T) { func TestGetUsernames(t *testing.T) { - // Create authentication response - - // Execute the function - CreateAuthFile(product, username, clientID, clientSecret, authResponse) + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Errorf("GetUsernames() error = %v", err) + } - // Execute the function fileNames, err := GetUsernames(product) if err != nil { t.Errorf("GetUsernames() error = %v", err) } - // Assertions if len(fileNames) != 1 || fileNames[0] != "test_user" { t.Errorf("GetUsernames() returned unexpected file names: %v", fileNames) } @@ -105,22 +103,21 @@ func TestGetUsernames(t *testing.T) { func TestCreateAuthFile(t *testing.T) { - // Save initial state homeDir, err := os.UserHomeDir() if err != nil { t.Fatalf("Failed to get user home directory: %v", err) } - // Execute the function - CreateAuthFile(product, username, clientID, clientSecret, authResponse) + err = CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } - // Read the content of the created file fileContent, err := os.ReadFile(homeDir + "/.flagship/credentials/" + product + "/" + username + ".yaml") if err != nil { t.Fatalf("Failed to read file: %v", err) } - // Assert the content of the file expectedContent := fmt.Sprintf(`client_id: %s client_secret: %s refresh_token: %s @@ -131,3 +128,149 @@ username: %s assert.Equal(t, expectedContent, string(fileContent)) } + +func TestReadAuth(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + v, err := ReadAuth(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, v.GetString("client_id"), clientID) + assert.Equal(t, v.GetString("client_secret"), clientSecret) + assert.Equal(t, v.GetString("username"), username) + assert.Equal(t, v.GetString("token"), authResponse.AccessToken) + assert.Equal(t, v.GetString("refresh_token"), authResponse.RefreshToken) +} + +func TestSelectAuth(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + err = SelectAuth(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + filepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + yamlFile, err := os.ReadFile(filepath) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, string(yamlFile), "current_used_credential: test_user\n") +} + +func TestSetAccountID(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + err = SelectAuth(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + err = SetAccountID(product, accountID) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + filepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + yamlFile, err := os.ReadFile(filepath) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, string(yamlFile), "account_id: account_id\ncurrent_used_credential: test_user\n") +} + +func TestSetAccountEnvironmentID(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + err = SelectAuth(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + err = SetAccountEnvID(product, accountEnvID) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + filepath, err := CredentialPath(product, utils.HOME_CLI) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + yamlFile, err := os.ReadFile(filepath) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, string(yamlFile), "account_environment_id: account_environment_id\ncurrent_used_credential: test_user\n") +} + +func TestReadCredentialsFromFile(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + filepath, err := CredentialPath(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + v, err := ReadCredentialsFromFile(filepath) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, v.GetString("client_id"), clientID) + assert.Equal(t, v.GetString("client_secret"), clientSecret) + assert.Equal(t, v.GetString("username"), username) + assert.Equal(t, v.GetString("token"), authResponse.AccessToken) + assert.Equal(t, v.GetString("refresh_token"), authResponse.RefreshToken) +} + +func TestWriteToken(t *testing.T) { + err := CreateAuthFile(product, username, clientID, clientSecret, models.TokenResponse{}) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + err = WriteToken(product, username, authResponse) + if err != nil { + t.Fatalf("Failed to get user home directory: %v", err) + } + + v, err := ReadAuth(product, username) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + + assert.Equal(t, v.GetString("client_id"), clientID) + assert.Equal(t, v.GetString("client_secret"), clientSecret) + assert.Equal(t, v.GetString("username"), username) + assert.Equal(t, v.GetString("token"), authResponse.AccessToken) + assert.Equal(t, v.GetString("refresh_token"), authResponse.RefreshToken) +} diff --git a/utils/functions_test.go b/utils/functions_test.go new file mode 100644 index 0000000..6d286d0 --- /dev/null +++ b/utils/functions_test.go @@ -0,0 +1,26 @@ +package utils + +import ( + "fmt" + "testing" + + "github.com/spf13/cobra" +) + +func TestExecuteCommand(t *testing.T) { + mockCmd := &cobra.Command{ + Run: func(cmd *cobra.Command, args []string) { + fmt.Fprintln(cmd.OutOrStdout(), "Hello, World!") + }, + } + + output, err := ExecuteCommand(mockCmd) + if err != nil { + t.Errorf("ExecuteCommand() error = %v", err) + } + + expectedOutput := "Hello, World!\n" + if output != expectedOutput { + t.Errorf("ExecuteCommand() returned unexpected output. Got: %s, Want: %s", output, expectedOutput) + } +} diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 739ce02..e4767a4 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -87,7 +87,10 @@ func regenerateToken(product, configName string) { } cred.RefreshToken = authenticationResponse.RefreshToken cred.Token = authenticationResponse.AccessToken - config.WriteToken(product, configName, authenticationResponse) + err := config.WriteToken(product, configName, authenticationResponse) + if err != nil { + log.Fatalf("error occurred: %v", err) + } } diff --git a/utils/http_request/web_experimentation/account.go b/utils/http_request/web_experimentation/account.go index fa7666f..ba2b4e2 100644 --- a/utils/http_request/web_experimentation/account.go +++ b/utils/http_request/web_experimentation/account.go @@ -11,5 +11,5 @@ type AccountWERequester struct { } func (a *AccountWERequester) HTTPListAccount() ([]models.AccountWE, error) { - return common.HTTPGetAllPagesWE[models.AccountWE](utils.GetWebExperimentationHost() + "/v1/accounts/") + return common.HTTPGetAllPagesWE[models.AccountWE](utils.GetWebExperimentationHost() + "/v1/accounts") } diff --git a/utils/mock_function/web_experimentation/account.go b/utils/mock_function/web_experimentation/account.go index fdd5f90..c5569a0 100644 --- a/utils/mock_function/web_experimentation/account.go +++ b/utils/mock_function/web_experimentation/account.go @@ -32,10 +32,27 @@ var TestAccountGlobalCode = models.AccountWE{ func APIAccount() { + resp := utils.HTTPListResponseWE[models.AccountWE]{ + Data: []models.AccountWE{TestAccountGlobalCode}, + Pagination: utils.Pagination{ + Total: 1, + Pages: 2, + MaxPerPage: 10, + Page: 1, + }, + } + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts/"+accountID, func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, TestAccountGlobalCode) return resp, nil }, ) + + httpmock.RegisterResponder("GET", utils.GetWebExperimentationHost()+"/v1/accounts", + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, resp) + return resp, nil + }, + ) } From 0cc07662f4c8848099c0aeeaad4ad28211961e2c Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 10:50:49 +0200 Subject: [PATCH 33/48] add grant_type client_credentials to WE and add some test --- cmd/feature_experimentation/auth/login.go | 3 +- cmd/web_experimentation/auth/auth_test.go | 19 +- cmd/web_experimentation/auth/login.go | 164 +++++++----------- models/token.go | 3 +- utils/http_request/common/token.go | 26 +++ .../mock_function/web_experimentation/auth.go | 5 +- .../web_experimentation/token.go | 3 +- 7 files changed, 109 insertions(+), 114 deletions(-) diff --git a/cmd/feature_experimentation/auth/login.go b/cmd/feature_experimentation/auth/login.go index 3f7a0f7..82028ef 100644 --- a/cmd/feature_experimentation/auth/login.go +++ b/cmd/feature_experimentation/auth/login.go @@ -32,7 +32,7 @@ func checkSingleFlag(bool1, bool2 bool) bool { // createCmd represents the create command var loginCmd = &cobra.Command{ - Use: "login [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=]", + Use: "login [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=] [-a | --account-id=]", Short: "login", Long: `login`, Run: func(cmd *cobra.Command, args []string) { @@ -89,6 +89,7 @@ var loginCmd = &cobra.Command{ fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) return } + if slices.Contains(existingCredentials, Username) { if AccountId != "" { err := config.SelectAuth(utils.FEATURE_EXPERIMENTATION, Username) diff --git a/cmd/web_experimentation/auth/auth_test.go b/cmd/web_experimentation/auth/auth_test.go index 3e1d978..e9b542f 100644 --- a/cmd/web_experimentation/auth/auth_test.go +++ b/cmd/web_experimentation/auth/auth_test.go @@ -31,17 +31,28 @@ var testAuth models.Auth var testAuthList []models.Auth func TestAuthCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(AuthCmd) + output, err := utils.ExecuteCommand(AuthCmd) + + assert.Nil(t, err) assert.Contains(t, output, "Manage your CLI authentication for web experimentation\n\nUsage:\n authentication [login|get|list|delete]") } func TestAuthHelpCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(AuthCmd, "--help") + output, err := utils.ExecuteCommand(AuthCmd, "--help") + + assert.Nil(t, err) assert.Contains(t, output, "Manage your CLI authentication for web experimentation\n\nUsage:\n authentication [login|get|list|delete]") } func TestAuthLoginCommand(t *testing.T) { - successOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_auth", "--password=password", "--totp=00000") + + failOutput, _ := utils.ExecuteCommand(AuthCmd, "login", "-u=test_auth", "--client-id=CI", "--client-secret=CS") + + assert.Equal(t, "Error while login, required fields (username, client ID, client secret, account id)\n", failOutput) + + successOutput, err := utils.ExecuteCommand(AuthCmd, "login", "-u=test_auth", "--client-id=CI", "--client-secret=CS", "--account-id=AI") + + assert.Nil(t, err) assert.Equal(t, "Credential created successfully\n", successOutput) } @@ -70,7 +81,7 @@ func TestAuthGetCommand(t *testing.T) { assert.Nil(t, err) - //assert.Equal(t, feature_experimentation.TestAuth, testAuth) + assert.Equal(t, web_experimentation.TestAuth, testAuth) } func TestAuthDeleteCommand(t *testing.T) { diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index ac322fd..ea9deca 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -6,12 +6,7 @@ package auth import ( "fmt" "log" - "net/http" - "os" - "os/exec" - "runtime" "slices" - "time" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/config" @@ -20,10 +15,8 @@ import ( ) var ( - browser bool - password string - redirectUri string - totp string + credentialsFile string + accountId string ) func checkSingleFlag(bool1, bool2 bool) bool { @@ -38,113 +31,93 @@ func checkSingleFlag(bool1, bool2 bool) bool { return count == 1 } -func openLink(url string) error { - var cmd *exec.Cmd - switch runtime.GOOS { - case "linux": - cmd = exec.Command("xdg-open", url) - case "darwin": - cmd = exec.Command("open", url) - case "windows": - cmd = exec.Command("cmd", "/c", "start", url) - default: - return fmt.Errorf("unsupported operating system") - } - err := cmd.Run() - return err -} - // createCmd represents the create command var loginCmd = &cobra.Command{ - Use: "login [--browser] [-i | --client-id=] [-s | --client-secret=] | [-u | --username=] [--password ]", + Use: "login [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=] [-a | --account-id=]", Short: "login", Long: `login`, Run: func(cmd *cobra.Command, args []string) { - if !checkSingleFlag(browser, Username != "") { + if !checkSingleFlag(credentialsFile != "", Username != "") { log.Fatalf("error occurred: %s", "1 flag is required. (browser, username)") } - if browser { - codeChan := make(chan string) - clientID := utils.CLIENT_ID - clientSecret := utils.CLIENT_SECRET - - if ClientID != "" { - clientID = ClientID + if credentialsFile != "" { + v, err := config.ReadCredentialsFromFile(credentialsFile) + if err != nil { + log.Fatalf("error occurred: %v", err) } - if ClientSecret != "" { - clientSecret = ClientSecret + if v.GetString("username") == "" || v.GetString("client_id") == "" || v.GetString("client_secret") == "" || v.GetString("account_id") == "" { + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") + return } - - var url = fmt.Sprintf("https://auth.abtasty.com/authorize?client_id=%s&client_secret=%s&redirect_uri=http://localhost:8010/auth/callback", clientID, clientSecret) - - if err := openLink(url); err != nil { - log.Fatalf("Error opening link: %s", err) + authenticationResponse, err := common.HTTPCreateTokenWE(v.GetString("client_id"), v.GetString("client_secret"), v.GetString("account_id")) + if err != nil { + fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) + return } - go func() { - http.HandleFunc("/auth/callback", func(w http.ResponseWriter, r *http.Request) { - handleCallback(w, r, codeChan) - }) - - if err := http.ListenAndServe("127.0.0.1:8010", nil); err != nil { - log.Fatalf("Error starting callback server: %s", err) - } - }() - - code := <-codeChan - - if code != "" { - authenticationResponse, err := common.HTTPCreateTokenWEAuthorizationCode(clientID, clientSecret, code) - if err != nil { - log.Fatalf("error occurred: %s", err) - return - } + err = config.CreateAuthFile(utils.WEB_EXPERIMENTATION, v.GetString("username"), v.GetString("client_id"), v.GetString("client_secret"), authenticationResponse) + if err != nil { + log.Fatalf("error occurred: %v", err) + } - if authenticationResponse.AccessToken == "" { - log.Fatal("Credentials not valid.") - } - // Waiting for fix to implemente route to get username "/users/me" - // add flag for redirect uri (for vscode etc...) + err = config.SelectAuth(utils.WEB_EXPERIMENTATION, v.GetString("username")) + if err != nil { + log.Fatalf("error occurred: %v", err) + } - fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") - return + err = config.SetAccountID(utils.WEB_EXPERIMENTATION, v.GetString("account_id")) + if err != nil { + log.Fatalf("error occurred: %s", err) } - fmt.Fprintln(cmd.OutOrStderr(), "Error occurred.") + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") + return } if Username != "" { existingCredentials, err := config.GetUsernames(utils.WEB_EXPERIMENTATION) if err != nil { - log.Fatalf("error occurred: %s", err) + fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) + return } + if slices.Contains(existingCredentials, Username) { - err := config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) - if err != nil { - log.Fatalf("error occurred: %v", err) + if accountId != "" { + err := config.SelectAuth(utils.WEB_EXPERIMENTATION, Username) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + err = config.SetAccountID(utils.WEB_EXPERIMENTATION, accountId) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) + return } - - fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (account id)") return } - if password == "" || totp == "" { - fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (password, totp)") + if ClientID == "" || ClientSecret == "" || accountId == "" { + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") return } - authenticationResponse, err := common.HTTPCreateTokenWEPassword(utils.CLIENT_ID, utils.CLIENT_SECRET, Username, password, totp) + authenticationResponse, err := common.HTTPCreateTokenWE(ClientID, ClientSecret, accountId) if err != nil { - log.Fatalf("error occurred: %s", err) + fmt.Fprintln(cmd.OutOrStderr(), err) return } if authenticationResponse.AccessToken == "" { - log.Fatal("Credentials not valid.") + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, client_id or client_secret not valid") + return } - err = config.CreateAuthFile(utils.WEB_EXPERIMENTATION, Username, "", "", authenticationResponse) + err = config.CreateAuthFile(utils.WEB_EXPERIMENTATION, Username, ClientID, ClientSecret, authenticationResponse) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -154,6 +127,11 @@ var loginCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } + err = config.SetAccountID(utils.WEB_EXPERIMENTATION, accountId) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") } @@ -162,32 +140,12 @@ var loginCmd = &cobra.Command{ func init() { + loginCmd.Flags().StringVarP(&Username, "username", "u", "", "username") + loginCmd.Flags().StringVarP(&ClientID, "client-id", "i", "", "client ID of an auth") loginCmd.Flags().StringVarP(&ClientSecret, "client-secret", "s", "", "client secret of an auth") - - loginCmd.Flags().BoolVarP(&browser, "browser", "", false, "generate link for browser") - loginCmd.Flags().StringVarP(&Username, "username", "u", "", "username") - loginCmd.Flags().StringVarP(&redirectUri, "redirect-uri", "", "http://abtasty.com", "redirect uri") - loginCmd.Flags().StringVarP(&password, "password", "", "", "password") - loginCmd.Flags().StringVarP(&totp, "totp", "", "", "totp") + loginCmd.Flags().StringVarP(&accountId, "account-id", "a", "", "account id of an auth") + loginCmd.Flags().StringVarP(&credentialsFile, "credential-file", "p", "", "config file to create") AuthCmd.AddCommand(loginCmd) } - -func handleCallback(w http.ResponseWriter, r *http.Request, codeChan chan<- string) { - code := r.URL.Query().Get("code") - if code == "" { - http.Error(w, "No token found in URL", http.StatusBadRequest) - os.Exit(0) - return - } - - codeChan <- code - - http.Redirect(w, r, redirectUri, http.StatusSeeOther) - - go func() { - time.Sleep(5 * time.Second) - close(codeChan) - }() -} diff --git a/models/token.go b/models/token.go index e7c347a..b0a0a03 100644 --- a/models/token.go +++ b/models/token.go @@ -41,11 +41,12 @@ type TokenFE struct { type TokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` } type ClientCredentialsRequest struct { GrantType string `json:"grant_type"` - Scope string `json:"scope"` + Scope string `json:"scope,omitempty"` ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"` } diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index cec8771..77fbb44 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -85,6 +85,32 @@ func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenRe return authenticationResponse, err } +func HTTPCreateTokenWE(clientId, clientSecret, accountId string) (models.TokenResponse, error) { + var authenticationResponse models.TokenResponse + authRequest := models.ClientCredentialsRequest{ + ClientID: clientId, + ClientSecret: clientSecret, + GrantType: "client_credentials", + } + + authRequestJSON, err := json.Marshal(authRequest) + if err != nil { + return models.TokenResponse{}, err + } + + respBody, err := HTTPRequest[models.TokenFE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) + if err != nil { + return models.TokenResponse{}, err + } + + err = json.Unmarshal(respBody, &authenticationResponse) + if err != nil { + return models.TokenResponse{}, err + } + + return authenticationResponse, err +} + func HTTPCreateTokenWEAuthorizationCode(client_id, client_secret, code string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.AuthorizationCodeRequest{ diff --git a/utils/mock_function/web_experimentation/auth.go b/utils/mock_function/web_experimentation/auth.go index 3e1de73..48c5224 100644 --- a/utils/mock_function/web_experimentation/auth.go +++ b/utils/mock_function/web_experimentation/auth.go @@ -11,10 +11,9 @@ import ( var TestAuth = models.Auth{ Username: "test_auth", - ClientID: "", - ClientSecret: "", + ClientID: "CI", + ClientSecret: "CS", Token: "testAccessToken", - RefreshToken: "testRefreshToken", } func InitMockAuth() { diff --git a/utils/mock_function/web_experimentation/token.go b/utils/mock_function/web_experimentation/token.go index 64c2a2b..032990c 100644 --- a/utils/mock_function/web_experimentation/token.go +++ b/utils/mock_function/web_experimentation/token.go @@ -20,8 +20,7 @@ func APIToken() { token := "token" testAuthenticationResponse := models.TokenResponse{ - AccessToken: "testAccessToken", - RefreshToken: "testRefreshToken", + AccessToken: "testAccessToken", } httpmock.RegisterResponder("GET", utils.GetHostWebExperimentationAuth()+"/v1/token?access_token="+token, From 31a7ba35ecf9d71ee2a39d5453dc00d6ce9608c4 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 14:12:36 +0200 Subject: [PATCH 34/48] remove client_credentials --- utils/const.go | 2 -- utils/http_request/common/request.go | 14 +++++++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/utils/const.go b/utils/const.go index 3b3428c..27b763b 100644 --- a/utils/const.go +++ b/utils/const.go @@ -49,5 +49,3 @@ func DefaultGlobalCodeWorkingDir() string { const FEATURE_EXPERIMENTATION = "fe" const WEB_EXPERIMENTATION = "we" const HOME_CLI = ".cli" -const CLIENT_ID = "590_397jchm4asqo04g0ogcggcoo88wo44sg0c0owk0448gkwck8s8" -const CLIENT_SECRET = "5xc41rk3etwc404o8scs0s8c0sogcgc48g4sk0ggc44so4w00c" diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index e4767a4..33a8bfa 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -75,19 +75,27 @@ func Init(credL RequestConfig) { func regenerateToken(product, configName string) { var authenticationResponse models.TokenResponse + var err error if product == utils.FEATURE_EXPERIMENTATION { - authenticationResponse, _ = HTTPRefreshTokenFE(cred.ClientID, cred.RefreshToken) + authenticationResponse, err = HTTPRefreshTokenFE(cred.ClientID, cred.RefreshToken) + if err != nil { + log.Fatalf("error occurred: %v", err) + } } else { - authenticationResponse, _ = HTTPRefreshTokenWE(utils.CLIENT_ID, utils.CLIENT_SECRET, cred.RefreshToken) + authenticationResponse, err = HTTPCreateTokenWE(cred.ClientID, cred.ClientSecret, cred.AccountID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } } if authenticationResponse.AccessToken == "" { log.Fatal("client_id or client_secret not valid") } + cred.RefreshToken = authenticationResponse.RefreshToken cred.Token = authenticationResponse.AccessToken - err := config.WriteToken(product, configName, authenticationResponse) + err = config.WriteToken(product, configName, authenticationResponse) if err != nil { log.Fatalf("error occurred: %v", err) } From 1ccfe6e4c8eb29f550b60c0df196cb93fc2c5abf Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 15:59:12 +0200 Subject: [PATCH 35/48] fix ci test coverage --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4f023d1..a1ac577 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,9 +15,9 @@ jobs: - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Run tests - run: go test -race `go list ./... | grep -v cmd/analyze/code-samples | grep -v cmd/configuration | grep -v utils/http_request` -coverprofile cover.out.tmp + run: go test -v -race `go list ./... | grep -v cmd/feature_experimentation/analyze | grep -v cmd/feature_experimentation/resource` -coverprofile coverage/cover.out.tmp - name: Removes mocks from tests - run: cat cover.out.tmp | grep -v "mock_\|cmd/analyze/code-samples-example|cmd/configuration|utils/http_request" > cover.out + run: cat coverage/cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze" | grep -v "mock_\|cmd/feature_experimentation/resource" > coverage/cover.out - uses: codecov/codecov-action@v2 with: file: ./cover.out From 85462ce9b9c5783193075ed0542e8eaac2d94b34 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 16:04:03 +0200 Subject: [PATCH 36/48] fix ci test coverage --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1ac577..3868492 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,9 +15,9 @@ jobs: - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Run tests - run: go test -v -race `go list ./... | grep -v cmd/feature_experimentation/analyze | grep -v cmd/feature_experimentation/resource` -coverprofile coverage/cover.out.tmp + run: go test -race `go list ./... | grep -v cmd/feature_experimentation/analyze | grep -v cmd/feature_experimentation/resource` -coverprofile cover.out.tmp - name: Removes mocks from tests - run: cat coverage/cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze" | grep -v "mock_\|cmd/feature_experimentation/resource" > coverage/cover.out + run: cat cover.out.tmp | grep -v "mock_\|cmd/feature_experimentation/analyze" | grep -v "mock_\|cmd/feature_experimentation/resource" > cover.out - uses: codecov/codecov-action@v2 with: file: ./cover.out From 26843c5dc9cc71342a8f44d4a47ed928b826bd21 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 16:27:55 +0200 Subject: [PATCH 37/48] add some tests and renaming --- .../feature_experimentation_test.go | 29 ++++++++++++++ .../campaign_global_code/get.go | 2 +- .../element_modification_code/get.go | 2 +- .../variation_global_code/get-css.go | 2 +- .../variation_global_code/get-js.go | 2 +- .../web_experimentation.go | 4 +- .../web_experimentation_test.go | 29 ++++++++++++++ utils/const.go | 2 +- .../account_environment_test.go | 39 +++++++++++++++++++ .../account-global-code_test.go | 21 ++++++++++ .../web_experimentation/account_test.go | 24 ++++++++++++ .../campaign-global-code_test.go | 21 ++++++++++ .../web_experimentation/main_test.go | 2 + ...riation-global-code.go => modification.go} | 4 +- .../web_experimentation/modification_test.go | 34 ++++++++++++++++ 15 files changed, 208 insertions(+), 9 deletions(-) create mode 100644 cmd/feature_experimentation/feature_experimentation_test.go create mode 100644 cmd/web_experimentation/web_experimentation_test.go create mode 100644 utils/http_request/feature_experimentation/account_environment_test.go create mode 100644 utils/http_request/web_experimentation/account-global-code_test.go create mode 100644 utils/http_request/web_experimentation/account_test.go create mode 100644 utils/http_request/web_experimentation/campaign-global-code_test.go rename utils/http_request/web_experimentation/{variation-global-code.go => modification.go} (84%) create mode 100644 utils/http_request/web_experimentation/modification_test.go diff --git a/cmd/feature_experimentation/feature_experimentation_test.go b/cmd/feature_experimentation/feature_experimentation_test.go new file mode 100644 index 0000000..93369c3 --- /dev/null +++ b/cmd/feature_experimentation/feature_experimentation_test.go @@ -0,0 +1,29 @@ +package feature_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_fe.InitMockAuth() + + m.Run() +} + +func TestAccountCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(FeatureExperimentationCmd) + assert.Contains(t, output, "Manage resources related to the feature experimentation product") +} + +func TestAccountHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(FeatureExperimentationCmd, "--help") + assert.Contains(t, output, "Manage resources related to the feature experimentation product") +} diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 5966f11..5dc586a 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -49,7 +49,7 @@ var getCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } - body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/element_modification_code/get.go index 2f816d0..c50eee5 100644 --- a/cmd/web_experimentation/element_modification_code/get.go +++ b/cmd/web_experimentation/element_modification_code/get.go @@ -33,7 +33,7 @@ var getCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - body, err := httprequest.ModificationRequester.HTTPGetModificationByID(campaignID, modificationID) + body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID, modificationID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/variation_global_code/get-css.go b/cmd/web_experimentation/variation_global_code/get-css.go index a32d440..b83156e 100644 --- a/cmd/web_experimentation/variation_global_code/get-css.go +++ b/cmd/web_experimentation/variation_global_code/get-css.go @@ -31,7 +31,7 @@ var getCSSCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go index ebf9ee3..d7d7aa4 100644 --- a/cmd/web_experimentation/variation_global_code/get-js.go +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -31,7 +31,7 @@ var getJSCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - body, err := httprequest.ModificationRequester.HTTPGetModification(campaignID) + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index ef22cfc..dd87817 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -28,8 +28,8 @@ import ( var WebExperimentationCmd = &cobra.Command{ Use: "web-experimentation [auth|account|campaign|global-code|variation]", Aliases: []string{"web-experimentation", "web-exp", "we"}, - Short: "Manage resources related to the feature experimentation product", - Long: `Manage resources related to the feature experimentation product`, + Short: "Manage resources related to the web experimentation product", + Long: `Manage resources related to the web experimentation product`, PersistentPreRun: func(cmd *cobra.Command, args []string) { initConfig() }, diff --git a/cmd/web_experimentation/web_experimentation_test.go b/cmd/web_experimentation/web_experimentation_test.go new file mode 100644 index 0000000..0532650 --- /dev/null +++ b/cmd/web_experimentation/web_experimentation_test.go @@ -0,0 +1,29 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_fe.InitMockAuth() + + m.Run() +} + +func TestAccountCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(WebExperimentationCmd) + assert.Contains(t, output, "Manage resources related to the web experimentation product") +} + +func TestAccountHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(WebExperimentationCmd, "--help") + assert.Contains(t, output, "Manage resources related to the web experimentation product") +} diff --git a/utils/const.go b/utils/const.go index 27b763b..362adfe 100644 --- a/utils/const.go +++ b/utils/const.go @@ -31,7 +31,7 @@ func GetHostFeatureExperimentationAuth() string { func GetHostWebExperimentationAuth() string { if os.Getenv("FS_STAGING") == "true" { - return "https://api-auth.abtasty.com" + return "https://staging-api-auth.abtasty.com" } return "https://api-auth.abtasty.com" diff --git a/utils/http_request/feature_experimentation/account_environment_test.go b/utils/http_request/feature_experimentation/account_environment_test.go new file mode 100644 index 0000000..b5c6f09 --- /dev/null +++ b/utils/http_request/feature_experimentation/account_environment_test.go @@ -0,0 +1,39 @@ +package feature_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/stretchr/testify/assert" +) + +var accountEnvironmentFERequester = AccountEnvironmentFERequester{&common.ResourceRequest{AccountID: "account_id", AccountEnvironmentID: "account_environment_id"}} + +func TestHTTPGetAccountEnvironment(t *testing.T) { + respBody, err := accountEnvironmentFERequester.HTTPGetAccountEnvironment("account_environment_id") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "account_environment_id", respBody.Id) + assert.Equal(t, "account_environment_name", respBody.Environment) + assert.Equal(t, true, respBody.IsMain) + assert.Equal(t, false, respBody.SingleAssignment) +} + +func TestHTTPListAccountEnvironment(t *testing.T) { + respBody, err := accountEnvironmentFERequester.HTTPListAccountEnvironment("account_id") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "account_environment_id", respBody[0].Id) + assert.Equal(t, "account_environment_name", respBody[0].Environment) + assert.Equal(t, true, respBody[0].IsMain) + assert.Equal(t, false, respBody[0].SingleAssignment) + + assert.Equal(t, "account_environment_id1", respBody[1].Id) + assert.Equal(t, "account_environment_name1", respBody[1].Environment) + assert.Equal(t, true, respBody[1].IsMain) + assert.Equal(t, false, respBody[1].SingleAssignment) +} diff --git a/utils/http_request/web_experimentation/account-global-code_test.go b/utils/http_request/web_experimentation/account-global-code_test.go new file mode 100644 index 0000000..40ad021 --- /dev/null +++ b/utils/http_request/web_experimentation/account-global-code_test.go @@ -0,0 +1,21 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/stretchr/testify/assert" +) + +var accountGlobalCodeRequester = AccountGlobalCodeRequester{&common.ResourceRequest{AccountID: "account_id"}} + +func TestHTTPAccountGlobalCode(t *testing.T) { + + respBody, err := accountGlobalCodeRequester.HTTPGetAccountGlobalCode("account_id") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "console.log(\"test\")", respBody) + +} diff --git a/utils/http_request/web_experimentation/account_test.go b/utils/http_request/web_experimentation/account_test.go new file mode 100644 index 0000000..d46a6b4 --- /dev/null +++ b/utils/http_request/web_experimentation/account_test.go @@ -0,0 +1,24 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/stretchr/testify/assert" +) + +var accountWERequester = AccountWERequester{&common.ResourceRequest{AccountID: "account_id"}} + +func TestHTTPListAccount(t *testing.T) { + + respBody, err := accountWERequester.HTTPListAccount() + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, 100000, respBody[0].Id) + assert.Equal(t, "account_name", respBody[0].Name) + assert.Equal(t, "account_identifier", respBody[0].Identifier) + assert.Equal(t, "account_role", respBody[0].Role) + +} diff --git a/utils/http_request/web_experimentation/campaign-global-code_test.go b/utils/http_request/web_experimentation/campaign-global-code_test.go new file mode 100644 index 0000000..dc8d1fb --- /dev/null +++ b/utils/http_request/web_experimentation/campaign-global-code_test.go @@ -0,0 +1,21 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/stretchr/testify/assert" +) + +var campaignGlobalCodeRequester = CampaignGlobalCodeRequester{&common.ResourceRequest{AccountID: "account_id"}} + +func TestHTTPCampaignGlobalCode(t *testing.T) { + + respBody, err := campaignGlobalCodeRequester.HTTPGetCampaignGlobalCode("100000") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, "console.log(\"Hello World!\")", respBody) + +} diff --git a/utils/http_request/web_experimentation/main_test.go b/utils/http_request/web_experimentation/main_test.go index d983b31..045c644 100644 --- a/utils/http_request/web_experimentation/main_test.go +++ b/utils/http_request/web_experimentation/main_test.go @@ -19,6 +19,8 @@ func TestMain(m *testing.M) { common.Init(mockfunction_.Auth) mockfunction.APICampaign() + mockfunction.APIModification() + mockfunction.APIAccount() mockfunction.APIToken() m.Run() diff --git a/utils/http_request/web_experimentation/variation-global-code.go b/utils/http_request/web_experimentation/modification.go similarity index 84% rename from utils/http_request/web_experimentation/variation-global-code.go rename to utils/http_request/web_experimentation/modification.go index 257675f..2b6feff 100644 --- a/utils/http_request/web_experimentation/variation-global-code.go +++ b/utils/http_request/web_experimentation/modification.go @@ -12,12 +12,12 @@ type ModificationRequester struct { *common.ResourceRequest } -func (m *ModificationRequester) HTTPGetModification(campaignID int) ([]models.Modification, error) { +func (m *ModificationRequester) HTTPListModification(campaignID int) ([]models.Modification, error) { resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(campaignID) + "/modifications") return resp.Data.Modifications, err } -func (m *ModificationRequester) HTTPGetModificationByID(campaignID int, id int) ([]models.Modification, error) { +func (m *ModificationRequester) HTTPGetModification(campaignID int, id int) ([]models.Modification, error) { resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(campaignID) + "/modifications?ids=" + strconv.Itoa(id)) return resp.Data.Modifications, err } diff --git a/utils/http_request/web_experimentation/modification_test.go b/utils/http_request/web_experimentation/modification_test.go new file mode 100644 index 0000000..fe9c5d4 --- /dev/null +++ b/utils/http_request/web_experimentation/modification_test.go @@ -0,0 +1,34 @@ +package web_experimentation + +import ( + "testing" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/stretchr/testify/assert" +) + +var modificationRequester = ModificationRequester{&common.ResourceRequest{AccountID: "account_id"}} + +func TestHTTPListModification(t *testing.T) { + + respBody, err := modificationRequester.HTTPListModification(100000) + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, web_experimentation.TestModifications.Data.Modifications, respBody) + +} + +func TestHTTPGetModification(t *testing.T) { + + respBody, err := modificationRequester.HTTPGetModification(100000, 120003) + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, []models.Modification{web_experimentation.TestModification.Data.Modifications[0]}, respBody) + +} From 5b579d545a1a37da30fe9c42349cc8baee56446c Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Fri, 26 Apr 2024 16:57:38 +0200 Subject: [PATCH 38/48] add we variation test --- cmd/feature_experimentation/token/info.go | 2 +- utils/http_request/common/token.go | 38 ++++--------------- .../web_experimentation/main_test.go | 1 + .../web_experimentation/variation_test.go | 22 +++++++++++ 4 files changed, 31 insertions(+), 32 deletions(-) create mode 100644 utils/http_request/web_experimentation/variation_test.go diff --git a/cmd/feature_experimentation/token/info.go b/cmd/feature_experimentation/token/info.go index 7ed5f46..f3af226 100644 --- a/cmd/feature_experimentation/token/info.go +++ b/cmd/feature_experimentation/token/info.go @@ -18,7 +18,7 @@ var infoCmd = &cobra.Command{ Short: "Get the information related to your token", Long: `Get the information related to your token`, Run: func(cmd *cobra.Command, args []string) { - body, err := common.HTTPCheckToken() + body, err := common.HTTPCheckTokenFE() if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 77fbb44..8bb8c2e 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -33,7 +33,7 @@ func HTTPRefreshTokenFE(client_id, refresh_token string) (models.TokenResponse, return authenticationResponse, err } -func HTTPRefreshTokenWE(client_id, client_secret, refresh_token string) (models.TokenResponse, error) { +/* func HTTPRefreshTokenWE(client_id, client_secret, refresh_token string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.RefreshTokenRequestWE{ ClientID: client_id, @@ -57,7 +57,7 @@ func HTTPRefreshTokenWE(client_id, client_secret, refresh_token string) (models. } return authenticationResponse, err -} +} */ func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse @@ -111,7 +111,7 @@ func HTTPCreateTokenWE(clientId, clientSecret, accountId string) (models.TokenRe return authenticationResponse, err } -func HTTPCreateTokenWEAuthorizationCode(client_id, client_secret, code string) (models.TokenResponse, error) { +/* func HTTPCreateTokenWEAuthorizationCode(client_id, client_secret, code string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse authRequest := models.AuthorizationCodeRequest{ ClientID: client_id, @@ -135,9 +135,9 @@ func HTTPCreateTokenWEAuthorizationCode(client_id, client_secret, code string) ( } return authenticationResponse, err -} +} */ -func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfaCode string) (models.TokenResponse, error) { +/* func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfaCode string) (models.TokenResponse, error) { var authenticationResponse models.TokenResponse var mfaResponse models.MfaRequestWE var mfmResponse models.MfaRequestWE @@ -209,32 +209,8 @@ func HTTPCreateTokenWEPassword(client_id, client_secret, username, password, mfa return authenticationResponse, err } +*/ -func HTTPRefreshToken_(product, client_id, refresh_token string) (models.TokenResponse, error) { - var authenticationResponse models.TokenResponse - authRequest := models.RefreshTokenRequestFE{ - ClientID: client_id, - GrantType: "refresh_token", - RefreshToken: refresh_token, - } - authRequestJSON, err := json.Marshal(authRequest) - if err != nil { - return models.TokenResponse{}, err - } - - respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) - if err != nil { - return models.TokenResponse{}, err - } - - err = json.Unmarshal(respBody, &authenticationResponse) - if err != nil { - return models.TokenResponse{}, err - } - - return authenticationResponse, err -} - -func HTTPCheckToken() (models.TokenFE, error) { +func HTTPCheckTokenFE() (models.TokenFE, error) { return HTTPGetItem[models.TokenFE](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + cred.Token) } diff --git a/utils/http_request/web_experimentation/main_test.go b/utils/http_request/web_experimentation/main_test.go index 045c644..e438783 100644 --- a/utils/http_request/web_experimentation/main_test.go +++ b/utils/http_request/web_experimentation/main_test.go @@ -20,6 +20,7 @@ func TestMain(m *testing.M) { mockfunction.APICampaign() mockfunction.APIModification() + mockfunction.APIVariation() mockfunction.APIAccount() mockfunction.APIToken() diff --git a/utils/http_request/web_experimentation/variation_test.go b/utils/http_request/web_experimentation/variation_test.go new file mode 100644 index 0000000..5362c85 --- /dev/null +++ b/utils/http_request/web_experimentation/variation_test.go @@ -0,0 +1,22 @@ +package web_experimentation + +import ( + "testing" + + "github.com/flagship-io/flagship/utils/http_request/common" + "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/stretchr/testify/assert" +) + +var variationRequester = VariationWERequester{&common.ResourceRequest{AccountID: "account_id"}} + +func TestHTTPGetVariation(t *testing.T) { + + respBody, err := variationRequester.HTTPGetVariation(100000, 110000) + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, web_experimentation.TestVariation, respBody) + +} From d9365c0e38286d8e1c2ff9e4aa1d201f9494654e Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 29 Apr 2024 13:33:20 +0200 Subject: [PATCH 39/48] add we token info and some tests --- .../token/token_test.go | 8 +-- cmd/web_experimentation/token/info.go | 72 +++++++++++++++++++ cmd/web_experimentation/token/token.go | 20 ++++++ .../web_experimentation.go | 2 + models/auth.go | 2 + models/token.go | 9 +-- utils/config/config.go | 4 +- utils/config/config_test.go | 9 ++- utils/http_request/common/request.go | 5 +- utils/http_request/common/token.go | 10 +-- .../feature_experimentation/token.go | 4 +- .../web_experimentation/token.go | 6 +- 12 files changed, 122 insertions(+), 29 deletions(-) create mode 100644 cmd/web_experimentation/token/info.go create mode 100644 cmd/web_experimentation/token/token.go diff --git a/cmd/feature_experimentation/token/token_test.go b/cmd/feature_experimentation/token/token_test.go index 85f128e..15204a6 100644 --- a/cmd/feature_experimentation/token/token_test.go +++ b/cmd/feature_experimentation/token/token_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/assert" ) -var _testToken models.TokenFE +var testToken models.Token func TestMain(m *testing.M) { @@ -26,8 +26,6 @@ func TestMain(m *testing.M) { m.Run() } -var testToken models.TokenFE - func TestTokenCommand(t *testing.T) { output, _ := utils.ExecuteCommand(TokenCmd) assert.Contains(t, output, "Manage your token\n") @@ -40,10 +38,10 @@ func TestTokenHelpCommand(t *testing.T) { func TestTokenInfoCommand(t *testing.T) { successOutput, _ := utils.ExecuteCommand(TokenCmd, "info") - err := json.Unmarshal([]byte(successOutput), &_testToken) + err := json.Unmarshal([]byte(successOutput), &testToken) assert.Nil(t, err) - assert.Equal(t, mockfunction_fe.TestToken, _testToken) + assert.Equal(t, mockfunction_fe.TestToken, testToken) } diff --git a/cmd/web_experimentation/token/info.go b/cmd/web_experimentation/token/info.go new file mode 100644 index 0000000..3bb3d67 --- /dev/null +++ b/cmd/web_experimentation/token/info.go @@ -0,0 +1,72 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package token + +import ( + "log" + "os" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/config" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "gopkg.in/yaml.v2" +) + +// infoCmd represents the info command +var infoCmd = &cobra.Command{ + Use: "info", + Short: "Get the information related to your token", + Long: `Get the information related to your token`, + Run: func(cmd *cobra.Command, args []string) { + var accountYaml models.AccountYaml + var credYaml models.AuthYaml + + // Home account + credPath, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, utils.HOME_CLI) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + homeFile, err := os.ReadFile(credPath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + err = yaml.Unmarshal(homeFile, &accountYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Current Cred + credPathCurr, err := config.CredentialPath(utils.WEB_EXPERIMENTATION, accountYaml.CurrentUsedCredential) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + currentCredFile, err := os.ReadFile(credPathCurr) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + // Unmarshal the YAML data into the struct + err = yaml.Unmarshal(currentCredFile, &credYaml) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + body := models.Token{ + ClientID: credYaml.ClientID, + AccountID: accountYaml.AccountID, + Scope: credYaml.Scope, + } + utils.FormatItem([]string{"ClientID", "AccountID", "Scope"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + TokenCmd.AddCommand(infoCmd) +} diff --git a/cmd/web_experimentation/token/token.go b/cmd/web_experimentation/token/token.go new file mode 100644 index 0000000..32ba720 --- /dev/null +++ b/cmd/web_experimentation/token/token.go @@ -0,0 +1,20 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com + +*/ + +package token + +import ( + "github.com/spf13/cobra" +) + +// TokenCmd represents the token command +var TokenCmd = &cobra.Command{ + Use: "token [info]", + Short: "Manage your token", + Long: `Manage your token`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index dd87817..327b8b1 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -13,6 +13,7 @@ import ( "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/element_modification_code" + "github.com/flagship-io/flagship/cmd/web_experimentation/token" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation_global_code" "github.com/flagship-io/flagship/utils" @@ -47,6 +48,7 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) WebExperimentationCmd.AddCommand(element_modification_code.ElementModificationCodeCmd) + WebExperimentationCmd.AddCommand(token.TokenCmd) } func init() { diff --git a/models/auth.go b/models/auth.go index 0699da9..100521d 100644 --- a/models/auth.go +++ b/models/auth.go @@ -6,6 +6,7 @@ type Auth struct { ClientSecret string `json:"client_secret"` Token string `json:"token"` RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` } type AuthYaml struct { @@ -14,6 +15,7 @@ type AuthYaml struct { ClientSecret string `yaml:"client_secret"` Token string `yaml:"token"` RefreshToken string `yaml:"refresh_token"` + Scope string `yaml:"scope"` } type AccountYaml struct { diff --git a/models/token.go b/models/token.go index b0a0a03..b3e5c37 100644 --- a/models/token.go +++ b/models/token.go @@ -1,12 +1,5 @@ package models -type TokenWE struct { - ClientID string `json:"client_id"` - AccountID string `json:"account"` - ExpiresIn int `json:"expires_in"` - Scope string `json:"scope"` -} - type MfaRequestWE struct { MfaToken string `json:"mfa_token"` MfaMethods []string `json:"mfa_methods"` @@ -31,7 +24,7 @@ type MultiFactorMethodResponseWE struct { GrantType string `json:"grant_type"` } -type TokenFE struct { +type Token struct { ClientID string `json:"client_id"` AccountID string `json:"account"` ExpiresIn int `json:"expires_in"` diff --git a/utils/config/config.go b/utils/config/config.go index 38477b1..9936589 100644 --- a/utils/config/config.go +++ b/utils/config/config.go @@ -92,6 +92,7 @@ func CreateAuthFile(product, username, clientId, clientSecret string, authentica v.Set("client_secret", clientSecret) v.Set("token", authenticationResponse.AccessToken) v.Set("refresh_token", authenticationResponse.RefreshToken) + v.Set("scope", authenticationResponse.Scope) err = v.WriteConfigAs(filepath) if err != nil { @@ -185,7 +186,7 @@ func ReadCredentialsFromFile(AuthFile string) (*viper.Viper, error) { return v, nil } -func WriteToken(product, AuthName string, authenticationResponse models.TokenResponse) error { +func RewriteToken(product, AuthName string, authenticationResponse models.TokenResponse) error { v := viper.New() configFilepath, err := CredentialPath(product, AuthName) if err != nil { @@ -197,6 +198,7 @@ func WriteToken(product, AuthName string, authenticationResponse models.TokenRes v.MergeInConfig() v.Set("token", authenticationResponse.AccessToken) v.Set("refresh_token", authenticationResponse.RefreshToken) + v.Set("scope", authenticationResponse.Scope) err = v.WriteConfigAs(configFilepath) if err != nil { diff --git a/utils/config/config_test.go b/utils/config/config_test.go index b202fb4..3738c39 100644 --- a/utils/config/config_test.go +++ b/utils/config/config_test.go @@ -19,12 +19,14 @@ var ( clientSecret = "client_secret" accessToken = "access_token" refreshToken = "refresh_token" + scope = "scope" accountID = "account_id" accountEnvID = "account_environment_id" ) var authResponse = models.TokenResponse{ AccessToken: accessToken, RefreshToken: refreshToken, + Scope: scope, } func TestMain(m *testing.M) { @@ -121,9 +123,10 @@ func TestCreateAuthFile(t *testing.T) { expectedContent := fmt.Sprintf(`client_id: %s client_secret: %s refresh_token: %s +scope: %s token: %s username: %s -`, clientID, clientSecret, refreshToken, accessToken, username) +`, clientID, clientSecret, refreshToken, scope, accessToken, username) assert.Equal(t, expectedContent, string(fileContent)) @@ -252,13 +255,13 @@ func TestReadCredentialsFromFile(t *testing.T) { assert.Equal(t, v.GetString("refresh_token"), authResponse.RefreshToken) } -func TestWriteToken(t *testing.T) { +func TestRewriteToken(t *testing.T) { err := CreateAuthFile(product, username, clientID, clientSecret, models.TokenResponse{}) if err != nil { t.Fatalf("Failed to get user home directory: %v", err) } - err = WriteToken(product, username, authResponse) + err = RewriteToken(product, username, authResponse) if err != nil { t.Fatalf("Failed to get user home directory: %v", err) } diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 33a8bfa..7a1bbab 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -62,6 +62,7 @@ type RequestConfig struct { AccountID string `mapstructure:"account_id"` AccountEnvironmentID string `mapstructure:"account_environment_id"` Token string `mapstructure:"token"` + Scope string `mapstructure:"scope"` RefreshToken string `mapstructure:"refresh_token"` CurrentUsedCredential string `mapstructure:"current_used_credential"` OutputFormat string `mapstructure:"output_format"` @@ -95,7 +96,7 @@ func regenerateToken(product, configName string) { cred.RefreshToken = authenticationResponse.RefreshToken cred.Token = authenticationResponse.AccessToken - err = config.WriteToken(product, configName, authenticationResponse) + err = config.RewriteToken(product, configName, authenticationResponse) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -124,7 +125,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) } if cred.Product == utils.FEATURE_EXPERIMENTATION { - if (cred.Username == "" || cred.AccountID == "") && resourceType != reflect.TypeOf(models.TokenFE{}) { + if (cred.Username == "" || cred.AccountID == "") && resourceType != reflect.TypeOf(models.Token{}) { log.Fatalf("username and account_id required, Please authenticate your CLI") } // for resource loader diff --git a/utils/http_request/common/token.go b/utils/http_request/common/token.go index 8bb8c2e..8487492 100644 --- a/utils/http_request/common/token.go +++ b/utils/http_request/common/token.go @@ -20,7 +20,7 @@ func HTTPRefreshTokenFE(client_id, refresh_token string) (models.TokenResponse, return models.TokenResponse{}, err } - respBody, err := HTTPRequest[models.TokenWE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) + respBody, err := HTTPRequest[models.Token](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+cred.AccountID+"/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -72,7 +72,7 @@ func HTTPCreateTokenFE(clientId, clientSecret, accountId string) (models.TokenRe return models.TokenResponse{}, err } - respBody, err := HTTPRequest[models.TokenFE](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+accountId+"/token?expires_in=86400", authRequestJSON) + respBody, err := HTTPRequest[models.Token](http.MethodPost, utils.GetHostFeatureExperimentationAuth()+"/"+accountId+"/token?expires_in=43200", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -98,7 +98,7 @@ func HTTPCreateTokenWE(clientId, clientSecret, accountId string) (models.TokenRe return models.TokenResponse{}, err } - respBody, err := HTTPRequest[models.TokenFE](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) + respBody, err := HTTPRequest[models.Token](http.MethodPost, utils.GetHostWebExperimentationAuth()+"/v1/token", authRequestJSON) if err != nil { return models.TokenResponse{}, err } @@ -211,6 +211,6 @@ func HTTPCreateTokenWE(clientId, clientSecret, accountId string) (models.TokenRe } */ -func HTTPCheckTokenFE() (models.TokenFE, error) { - return HTTPGetItem[models.TokenFE](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + cred.Token) +func HTTPCheckTokenFE() (models.Token, error) { + return HTTPGetItem[models.Token](utils.GetHostFeatureExperimentationAuth() + "/token?access_token=" + cred.Token) } diff --git a/utils/mock_function/feature_experimentation/token.go b/utils/mock_function/feature_experimentation/token.go index 74211da..8d8cb1a 100644 --- a/utils/mock_function/feature_experimentation/token.go +++ b/utils/mock_function/feature_experimentation/token.go @@ -9,11 +9,11 @@ import ( "github.com/jarcoal/httpmock" ) -var TestToken = models.TokenFE{ +var TestToken = models.Token{ ClientID: "client_id", AccountID: "account_id", ExpiresIn: 0, - Scope: "*", + Scope: "scope", } func APIToken() { diff --git a/utils/mock_function/web_experimentation/token.go b/utils/mock_function/web_experimentation/token.go index 032990c..1ee894f 100644 --- a/utils/mock_function/web_experimentation/token.go +++ b/utils/mock_function/web_experimentation/token.go @@ -8,11 +8,11 @@ import ( "github.com/jarcoal/httpmock" ) -var TestToken = models.TokenWE{ +var TestToken = models.Token{ ClientID: "client_id", AccountID: "account_id", - ExpiresIn: 0, - Scope: "*", + ExpiresIn: 10, + Scope: "scope", } func APIToken() { From ab83830b7b137747b026a20bbe065a6531eb0e96 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Mon, 29 Apr 2024 13:40:40 +0200 Subject: [PATCH 40/48] fix test --- cmd/web_experimentation/auth/auth_test.go | 2 +- cmd/web_experimentation/token/token_test.go | 36 +++++++++++++++++++ .../web_experimentation_test.go | 4 +-- utils/config/default.go | 2 +- .../feature_experimentation/token.go | 2 +- 5 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 cmd/web_experimentation/token/token_test.go diff --git a/cmd/web_experimentation/auth/auth_test.go b/cmd/web_experimentation/auth/auth_test.go index e9b542f..d3abe2c 100644 --- a/cmd/web_experimentation/auth/auth_test.go +++ b/cmd/web_experimentation/auth/auth_test.go @@ -18,7 +18,7 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - //defer mockfunction_we.InitMockAuth() + defer mockfunction_we.InitMockAuth() mockfunction.SetMock(&http_request.ResourceRequester) diff --git a/cmd/web_experimentation/token/token_test.go b/cmd/web_experimentation/token/token_test.go new file mode 100644 index 0000000..63dadfd --- /dev/null +++ b/cmd/web_experimentation/token/token_test.go @@ -0,0 +1,36 @@ +package token + +import ( + "testing" + + "github.com/flagship-io/flagship/models" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +var testToken models.Token + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_we.APIToken() + m.Run() +} + +func TestTokenCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(TokenCmd) + assert.Contains(t, output, "Manage your token\n") +} + +func TestTokenHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(TokenCmd, "--help") + assert.Contains(t, output, "Manage your token\n") +} diff --git a/cmd/web_experimentation/web_experimentation_test.go b/cmd/web_experimentation/web_experimentation_test.go index 0532650..4265ff5 100644 --- a/cmd/web_experimentation/web_experimentation_test.go +++ b/cmd/web_experimentation/web_experimentation_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/flagship-io/flagship/utils" - mockfunction_fe "github.com/flagship-io/flagship/utils/mock_function/feature_experimentation" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" ) @@ -13,7 +13,7 @@ func TestMain(m *testing.M) { httpmock.Activate() defer httpmock.DeactivateAndReset() - defer mockfunction_fe.InitMockAuth() + defer mockfunction_we.InitMockAuth() m.Run() } diff --git a/utils/config/default.go b/utils/config/default.go index ff2791f..291f696 100644 --- a/utils/config/default.go +++ b/utils/config/default.go @@ -5,7 +5,7 @@ import "github.com/flagship-io/flagship/cmd/version" const ( OutputFormat = "table" GrantType = "client_credentials" - Expiration = 86400 + Expiration = 43200 Scope = "*" ClientID = "clientID" ClientSecret = "clientSecret" diff --git a/utils/mock_function/feature_experimentation/token.go b/utils/mock_function/feature_experimentation/token.go index 8d8cb1a..fa992d9 100644 --- a/utils/mock_function/feature_experimentation/token.go +++ b/utils/mock_function/feature_experimentation/token.go @@ -32,7 +32,7 @@ func APIToken() { }, ) - httpmock.RegisterResponder("POST", utils.GetHostFeatureExperimentationAuth()+"/"+mockfunction.Auth.AccountID+"/token?expires_in=86400", + httpmock.RegisterResponder("POST", utils.GetHostFeatureExperimentationAuth()+"/"+mockfunction.Auth.AccountID+"/token?expires_in=43200", func(req *http.Request) (*http.Response, error) { resp, _ := httpmock.NewJsonResponse(200, testAuthenticationResponse) return resp, nil From f123ad849f9c85f2e831dfcf8b72d01be9f35255 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 30 Apr 2024 10:51:51 +0200 Subject: [PATCH 41/48] add override for existing global & modification code --- .../account_global_code/get.go | 4 +- .../campaign_global_code/get.go | 27 +++++--- .../element_modification_code/get.go | 9 ++- .../variation_global_code/get-css.go | 5 +- .../variation_global_code/get-js.go | 5 +- .../variation_global_code.go | 1 + .../web_experimentation.go | 3 +- utils/config/config_global_code.go | 64 ++++++++++++++++--- utils/config/config_global_code_test.go | 10 +-- 9 files changed, 95 insertions(+), 33 deletions(-) diff --git a/cmd/web_experimentation/account_global_code/get.go b/cmd/web_experimentation/account_global_code/get.go index 7f564f9..c59af1c 100644 --- a/cmd/web_experimentation/account_global_code/get.go +++ b/cmd/web_experimentation/account_global_code/get.go @@ -15,6 +15,7 @@ import ( var accountID string var createFile bool +var override bool // getCmd represents get command var getCmd = &cobra.Command{ @@ -28,7 +29,7 @@ var getCmd = &cobra.Command{ } if createFile { - accountCodeDir, err := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body) + accountCodeDir, err := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body, override) if err != nil { log.Fatalf("error occurred: %s", err) } @@ -45,6 +46,7 @@ func init() { log.Fatalf("error occurred: %v", err) } getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains account global code") + getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing account global code file") AccountGlobalCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 5dc586a..70e6e72 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -16,6 +16,7 @@ import ( var createFile bool var createSubFiles bool +var override bool // getCmd represents get command var getCmd = &cobra.Command{ @@ -23,14 +24,13 @@ var getCmd = &cobra.Command{ Short: "Get campaign global code", Long: `Get campaign global code`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.CampaignGlobalCodeRequester.HTTPGetCampaignGlobalCode(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } if createFile { - campaignCodeDir, err := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + campaignCodeDir, err := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body, override) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -38,17 +38,17 @@ var getCmd = &cobra.Command{ return } - // TODO if createSubFiles { campaignID, err := strconv.Atoi(CampaignID) if err != nil { log.Fatalf("error occurred: %v", err) } - campaignCodeDir, err := config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body) + _, err = config.CampaignGlobalCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, body, override) if err != nil { log.Fatalf("error occurred: %v", err) } + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) if err != nil { log.Fatalf("error occurred: %v", err) @@ -56,21 +56,26 @@ var getCmd = &cobra.Command{ for _, modification := range body { if modification.Type == "customScriptNew" && modification.Selector == "" { - config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value) + _, err := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value, override) + if err != nil { + log.Fatalf("error occurred: %v", err) + } continue } if modification.Type == "addCSS" && modification.Selector == "" { - config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value) + _, err := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), modification.Value, override) + if err != nil { + log.Fatalf("error occurred: %v", err) + } continue } fileCode := config.AddHeaderSelectorComment(modification.Selector, modification.Value) - config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), strconv.Itoa(modification.Id), modification.Selector, fileCode) + config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), strconv.Itoa(modification.Id), modification.Selector, fileCode, override) } - fmt.Fprintln(cmd.OutOrStdout(), "Sub files code generated successfully: ", campaignCodeDir) - + fmt.Fprintln(cmd.OutOrStdout(), "Sub files code generated successfully: "+viper.GetString("working_dir")+"/abtasty") return } @@ -85,7 +90,9 @@ func init() { log.Fatalf("error occurred: %v", err) } getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains campaign global code") - getCmd.Flags().BoolVarP(&createSubFiles, "create-subfiles", "", false, "create a file that contains variations global code") + getCmd.Flags().BoolVarP(&createSubFiles, "create-subfiles", "", false, "create a file that contains campaign and variations global code") + + getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing campaign global code file") CampaignGlobalCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/element_modification_code/get.go index c50eee5..421708a 100644 --- a/cmd/web_experimentation/element_modification_code/get.go +++ b/cmd/web_experimentation/element_modification_code/get.go @@ -14,6 +14,8 @@ import ( "github.com/spf13/viper" ) +var override bool + // getCmd represents get command var getCmd = &cobra.Command{ Use: "get [-i | --id ] [--campaign-id ]", @@ -48,7 +50,7 @@ var getCmd = &cobra.Command{ if CreateFile { fileCode := config.AddHeaderSelectorComment(selector, code) - elementModificationCodeDir, err := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode) + elementModificationCodeDir, err := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode, override) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -68,13 +70,14 @@ func init() { log.Fatalf("error occurred: %v", err) } - getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the global code modification you want to display") + getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the element modification code you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } - getCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + getCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains element modification global code") + getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing element modification code file") ElementModificationCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/variation_global_code/get-css.go b/cmd/web_experimentation/variation_global_code/get-css.go index b83156e..837765c 100644 --- a/cmd/web_experimentation/variation_global_code/get-css.go +++ b/cmd/web_experimentation/variation_global_code/get-css.go @@ -43,7 +43,7 @@ var getCSSCmd = &cobra.Command{ } if CreateFile { - campaignCodeDir, err := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, cssCode) + campaignCodeDir, err := config.VariationGlobalCodeDirectoryCSS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, cssCode, Override) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -69,7 +69,8 @@ func init() { log.Fatalf("error occurred: %v", err) } - getCSSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + getCSSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains variation global code") + getCSSCmd.Flags().BoolVarP(&Override, "override", "", false, "override existing variation global code file") VariationGlobalCodeCmd.AddCommand(getCSSCmd) } diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go index d7d7aa4..79a575e 100644 --- a/cmd/web_experimentation/variation_global_code/get-js.go +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -43,7 +43,7 @@ var getJSCmd = &cobra.Command{ } if CreateFile { - variationCodeDir, err := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, jsCode) + variationCodeDir, err := config.VariationGlobalCodeDirectoryJS(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, VariationID, jsCode, Override) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -68,7 +68,8 @@ func init() { log.Fatalf("error occurred: %v", err) } - getJSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains campaign global code") + getJSCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains variation global code") + getJSCmd.Flags().BoolVarP(&Override, "override", "", false, "override existing variation global code file") VariationGlobalCodeCmd.AddCommand(getJSCmd) } diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go index 81566e5..5706e55 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code.go @@ -17,6 +17,7 @@ var WorkingDir string var CampaignID string var VariationID string var CreateFile bool +var Override bool // VariationGlobalCodeCmd represents the variation global code command var VariationGlobalCodeCmd = &cobra.Command{ diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 327b8b1..9fcadf0 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -8,7 +8,6 @@ import ( "os" "github.com/flagship-io/flagship/cmd/web_experimentation/account" - account_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/account_global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" @@ -45,7 +44,7 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(auth.AuthCmd) WebExperimentationCmd.AddCommand(account.AccountCmd) WebExperimentationCmd.AddCommand(campaign_global_code.CampaignGlobalCodeCmd) - WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) + //WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) WebExperimentationCmd.AddCommand(element_modification_code.ElementModificationCodeCmd) WebExperimentationCmd.AddCommand(token.TokenCmd) diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go index 9b00add..ef20e1d 100644 --- a/utils/config/config_global_code.go +++ b/utils/config/config_global_code.go @@ -2,6 +2,7 @@ package config import ( "errors" + "fmt" "os" ) @@ -32,11 +33,13 @@ func CheckGlobalCodeDirectory(workingDir string) (string, error) { return gcWorkingDir, nil } -func AccountGlobalCodeDirectory(workingDir, accountID, code string) (string, error) { +func AccountGlobalCodeDirectory(workingDir, accountID, code string, override bool) (string, error) { + gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err } + accountCodeDir := gcWorkingDir + "/" + accountID err = os.MkdirAll(accountCodeDir, os.ModePerm) @@ -45,18 +48,28 @@ func AccountGlobalCodeDirectory(workingDir, accountID, code string) (string, err } jsFilePath := accountCodeDir + "/accountGlobalCode.js" + if _, err := os.Stat(jsFilePath); err == nil { + if !override { + fmt.Fprintln(os.Stderr, "File already exists: "+jsFilePath) + return jsFilePath, nil + } + } + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { return "", err } + + fmt.Fprintln(os.Stdout, "File created: "+jsFilePath) return jsFilePath, nil } -func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) (string, error) { +func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string, override bool) (string, error) { gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err } + accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID @@ -66,19 +79,28 @@ func CampaignGlobalCodeDirectory(workingDir, accountID, campaignID, code string) } jsFilePath := campaignCodeDir + "/campaignGlobalCode.js" + if _, err := os.Stat(jsFilePath); err == nil { + if !override { + fmt.Fprintln(os.Stderr, "File already exists: "+jsFilePath) + return jsFilePath, nil + } + } + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { return "", err } + fmt.Fprintln(os.Stdout, "File created: "+jsFilePath) return jsFilePath, nil } -func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variationID, code string) (string, error) { +func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variationID, code string, override bool) (string, error) { gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err } + accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID variationCodeDir := campaignCodeDir + "/" + variationID @@ -89,14 +111,23 @@ func VariationGlobalCodeDirectoryJS(workingDir, accountID, campaignID, variation } jsFilePath := variationCodeDir + "/variationGlobalCode.js" + if _, err := os.Stat(jsFilePath); err == nil { + if !override { + fmt.Fprintln(os.Stderr, "File already exists: "+jsFilePath) + return jsFilePath, nil + } + } + err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) if err != nil { return "", err } + + fmt.Fprintln(os.Stdout, "File created: "+jsFilePath) return jsFilePath, nil } -func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variationID, code string) (string, error) { +func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variationID, code string, override bool) (string, error) { gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err @@ -111,15 +142,24 @@ func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variatio return "", err } - jsFilePath := variationCodeDir + "/variationGlobalCode.css" - err = os.WriteFile(jsFilePath, []byte(code), os.ModePerm) + filePath := variationCodeDir + "/variationGlobalCode.css" + if _, err := os.Stat(filePath); err == nil { + if !override { + fmt.Fprintln(os.Stderr, "File already exists: "+filePath) + return filePath, nil + } + } + + err = os.WriteFile(filePath, []byte(code), os.ModePerm) if err != nil { return "", err } - return jsFilePath, nil + + fmt.Fprintln(os.Stdout, "File created: "+filePath) + return filePath, nil } -func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte) (string, error) { +func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte, override bool) (string, error) { gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err @@ -136,11 +176,19 @@ func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variati } jsFilePath := elementCodeDir + "/element.js" + if _, err := os.Stat(jsFilePath); err == nil { + if !override { + fmt.Fprintln(os.Stderr, "File already exists: "+jsFilePath) + return jsFilePath, nil + } + } err = os.WriteFile(jsFilePath, code, os.ModePerm) if err != nil { return "", err } + + fmt.Fprintln(os.Stdout, "File created: "+jsFilePath) return jsFilePath, nil } diff --git a/utils/config/config_global_code_test.go b/utils/config/config_global_code_test.go index 2009562..72e47b5 100644 --- a/utils/config/config_global_code_test.go +++ b/utils/config/config_global_code_test.go @@ -123,7 +123,7 @@ func TestAccountGlobalCodeDirectory(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got, err := AccountGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.code) + got, err := AccountGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.code, true) if (err != nil) != tt.wantErr { t.Errorf("AccountGlobalCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) } @@ -164,7 +164,7 @@ func TestCampaignGlobalCodeDirectory(t *testing.T) { for i, tt := range tests { if i == 0 { t.Run(tt.name, func(t *testing.T) { - got, err := CampaignGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.code) + got, err := CampaignGlobalCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.code, true) if (err != nil) != tt.wantErr { t.Errorf("CampaignGlobalCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) } @@ -209,7 +209,7 @@ func TestVariationGlobalCodeDirectoryJS(t *testing.T) { for i, tt := range tests { if i == 0 { t.Run(tt.name, func(t *testing.T) { - got, err := VariationGlobalCodeDirectoryJS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code) + got, err := VariationGlobalCodeDirectoryJS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code, true) if (err != nil) != tt.wantErr { t.Errorf("VariationGlobalCodeDirectoryJS() error = %v, wantErr %v", err, tt.wantErr) } @@ -254,7 +254,7 @@ func TestVariationGlobalCodeDirectoryCSS(t *testing.T) { for i, tt := range tests { if i == 0 { t.Run(tt.name, func(t *testing.T) { - got, err := VariationGlobalCodeDirectoryCSS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code) + got, err := VariationGlobalCodeDirectoryCSS(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.code, true) if (err != nil) != tt.wantErr { t.Errorf("VariationGlobalCodeDirectoryCSS() error = %v, wantErr %v", err, tt.wantErr) } @@ -303,7 +303,7 @@ func TestElementModificationCodeDirectory(t *testing.T) { for i, tt := range tests { if i == 0 { t.Run(tt.name, func(t *testing.T) { - got, err := ElementModificationCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.elementID, tt.selector, []byte(tt.code)) + got, err := ElementModificationCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.elementID, tt.selector, []byte(tt.code), true) if (err != nil) != tt.wantErr { t.Errorf("ElementModificationCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) } From 4633c794b8132ae6e5ac016c43095a1ebd002ef4 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 30 Apr 2024 15:24:01 +0200 Subject: [PATCH 42/48] add modification resource and rename modification-code --- .../campaign_global_code.go | 1 - .../campaign_global_code/get.go | 2 +- .../element_modification_code_test.go | 47 ----------- cmd/web_experimentation/modification/get.go | 37 +++++++++ cmd/web_experimentation/modification/list.go | 31 ++++++++ .../modification/modification.go | 35 +++++++++ .../get.go | 18 ++--- .../modification_code.go} | 19 +++-- .../variation_global_code/get-js.go | 1 + .../variation_global_code/info-css.go | 64 +++++++++++++++ .../variation_global_code/info-js.go | 64 +++++++++++++++ .../variation_global_code.go | 1 - .../web_experimentation.go | 6 +- utils/config/config_global_code.go | 4 +- utils/config/config_global_code_test.go | 78 +++++++++---------- .../campaign-global-code.go | 5 ++ 16 files changed, 301 insertions(+), 112 deletions(-) delete mode 100644 cmd/web_experimentation/element_modification_code/element_modification_code_test.go create mode 100644 cmd/web_experimentation/modification/get.go create mode 100644 cmd/web_experimentation/modification/list.go create mode 100644 cmd/web_experimentation/modification/modification.go rename cmd/web_experimentation/{element_modification_code => modification_code}/get.go (73%) rename cmd/web_experimentation/{element_modification_code/element_modification_code.go => modification_code/modification_code.go} (61%) create mode 100644 cmd/web_experimentation/variation_global_code/info-css.go create mode 100644 cmd/web_experimentation/variation_global_code/info-js.go diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go index 760877c..1a1806d 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go @@ -31,7 +31,6 @@ func init() { cobra.OnInitialize(initConfig) cobra.OnInitialize(initGlobalCodeDir) CampaignGlobalCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") - } func initConfig() { diff --git a/cmd/web_experimentation/campaign_global_code/get.go b/cmd/web_experimentation/campaign_global_code/get.go index 70e6e72..9106db8 100644 --- a/cmd/web_experimentation/campaign_global_code/get.go +++ b/cmd/web_experimentation/campaign_global_code/get.go @@ -72,7 +72,7 @@ var getCmd = &cobra.Command{ } fileCode := config.AddHeaderSelectorComment(modification.Selector, modification.Value) - config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), strconv.Itoa(modification.Id), modification.Selector, fileCode, override) + config.ModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modification.VariationID), strconv.Itoa(modification.Id), modification.Selector, fileCode, override) } fmt.Fprintln(cmd.OutOrStdout(), "Sub files code generated successfully: "+viper.GetString("working_dir")+"/abtasty") diff --git a/cmd/web_experimentation/element_modification_code/element_modification_code_test.go b/cmd/web_experimentation/element_modification_code/element_modification_code_test.go deleted file mode 100644 index 8020cb9..0000000 --- a/cmd/web_experimentation/element_modification_code/element_modification_code_test.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright © 2022 Flagship Team flagship@abtasty.com -*/ - -package element_modification_code - -import ( - "testing" - - "github.com/flagship-io/flagship/utils" - "github.com/flagship-io/flagship/utils/http_request" - mockfunction "github.com/flagship-io/flagship/utils/mock_function" - mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" - "github.com/jarcoal/httpmock" - "github.com/stretchr/testify/assert" -) - -func TestMain(m *testing.M) { - - httpmock.Activate() - defer httpmock.DeactivateAndReset() - defer mockfunction_we.InitMockAuth() - - mockfunction.SetMock(&http_request.ResourceRequester) - - mockfunction_we.APIModification() - - m.Run() -} - -func TestElementModificationCodeCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(ElementModificationCodeCmd) - assert.Contains(t, output, "Get element modification code") -} - -func TestElementModificationCodeHelpCommand(t *testing.T) { - output, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "--help") - assert.Contains(t, output, "Get element modification code") -} - -func TestElementModificationCodeGetCommand(t *testing.T) { - failOutput, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "get") - assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") - - successOutput, _ := utils.ExecuteCommand(ElementModificationCodeCmd, "get", "-i=120003", "--campaign-id=100000") - assert.Equal(t, "console.log(\"test modification\")\n", successOutput) -} diff --git a/cmd/web_experimentation/modification/get.go b/cmd/web_experimentation/modification/get.go new file mode 100644 index 0000000..2f43dd5 --- /dev/null +++ b/cmd/web_experimentation/modification/get.go @@ -0,0 +1,37 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package modification + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// getCmd represents get command +var getCmd = &cobra.Command{ + Use: "get [-i | --id ] [--campaign-id ]", + Short: "Get a modification", + Long: `Get a modification`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.ModificationRequester.HTTPGetModification(CampaignID, ModificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "Name", "Type", "VariationID", "Selector", "Engine", "Value"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + + }, +} + +func init() { + getCmd.Flags().IntVarP(&ModificationID, "id", "i", 0, "id of the modification you want to display") + + if err := getCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + ModificationCmd.AddCommand(getCmd) +} diff --git a/cmd/web_experimentation/modification/list.go b/cmd/web_experimentation/modification/list.go new file mode 100644 index 0000000..f6e4e78 --- /dev/null +++ b/cmd/web_experimentation/modification/list.go @@ -0,0 +1,31 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package modification + +import ( + "log" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// listCmd represents the list command +var listCmd = &cobra.Command{ + Use: "list [--campaign-id ]", + Short: "List all modifications", + Long: `List all modifications of a campaign`, + Run: func(cmd *cobra.Command, args []string) { + body, err := httprequest.ModificationRequester.HTTPListModification(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + utils.FormatItem([]string{"Id", "Name", "Type", "VariationID", "Selector", "Engine", "Value"}, body, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + ModificationCmd.AddCommand(listCmd) +} diff --git a/cmd/web_experimentation/modification/modification.go b/cmd/web_experimentation/modification/modification.go new file mode 100644 index 0000000..0b5b869 --- /dev/null +++ b/cmd/web_experimentation/modification/modification.go @@ -0,0 +1,35 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package modification + +import ( + "log" + + "github.com/spf13/cobra" +) + +var ( + CampaignID int + ModificationID int + Status string + DataRaw string +) + +// modificationCmd represents the modification command +var ModificationCmd = &cobra.Command{ + Use: "modification [get|list|delete|switch]", + Short: "Manage your modifications", + Long: `Manage your modifications`, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + }, +} + +func init() { + ModificationCmd.PersistentFlags().IntVarP(&CampaignID, "campaign-id", "", 0, "id of the campaign where you want to manage your modifications") + + if err := ModificationCmd.MarkPersistentFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } +} diff --git a/cmd/web_experimentation/element_modification_code/get.go b/cmd/web_experimentation/modification_code/get.go similarity index 73% rename from cmd/web_experimentation/element_modification_code/get.go rename to cmd/web_experimentation/modification_code/get.go index 421708a..02f7ee2 100644 --- a/cmd/web_experimentation/element_modification_code/get.go +++ b/cmd/web_experimentation/modification_code/get.go @@ -1,7 +1,7 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com */ -package element_modification_code +package modification_code import ( "fmt" @@ -19,8 +19,8 @@ var override bool // getCmd represents get command var getCmd = &cobra.Command{ Use: "get [-i | --id ] [--campaign-id ]", - Short: "Get element modification code", - Long: `Get element modification code`, + Short: "Get modification code", + Long: `Get modification code`, Run: func(cmd *cobra.Command, args []string) { var code string var selector string @@ -50,12 +50,12 @@ var getCmd = &cobra.Command{ if CreateFile { fileCode := config.AddHeaderSelectorComment(selector, code) - elementModificationCodeDir, err := config.ElementModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode, override) + modificationCodeDir, err := config.ModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode, override) if err != nil { log.Fatalf("error occurred: %v", err) } - fmt.Fprintln(cmd.OutOrStdout(), "Element code file generated successfully: ", elementModificationCodeDir) + fmt.Fprintln(cmd.OutOrStdout(), "modification code file generated successfully: ", modificationCodeDir) return } @@ -70,14 +70,14 @@ func init() { log.Fatalf("error occurred: %v", err) } - getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the element modification code you want to display") + getCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the modification code you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } - getCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains element modification global code") - getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing element modification code file") + getCmd.Flags().BoolVarP(&CreateFile, "create-file", "", false, "create a file that contains modification global code") + getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing modification code file") - ElementModificationCodeCmd.AddCommand(getCmd) + ModificationCodeCmd.AddCommand(getCmd) } diff --git a/cmd/web_experimentation/element_modification_code/element_modification_code.go b/cmd/web_experimentation/modification_code/modification_code.go similarity index 61% rename from cmd/web_experimentation/element_modification_code/element_modification_code.go rename to cmd/web_experimentation/modification_code/modification_code.go index eef919a..6850e4a 100644 --- a/cmd/web_experimentation/element_modification_code/element_modification_code.go +++ b/cmd/web_experimentation/modification_code/modification_code.go @@ -1,7 +1,7 @@ /* Copyright © 2022 Flagship Team flagship@abtasty.com */ -package element_modification_code +package modification_code import ( "log" @@ -18,12 +18,12 @@ var CampaignID string var ModificationID string var CreateFile bool -// ElementModificationCodeCmd represents the variation global code command -var ElementModificationCodeCmd = &cobra.Command{ - Use: "element-modification-code [get]", - Short: "Get element modification code", - Aliases: []string{"emc"}, - Long: `Get element modification code`, +// ModificationCodeCmd represents the variation global code command +var ModificationCodeCmd = &cobra.Command{ + Use: "modification-code [get]", + Short: "Get modification code", + Aliases: []string{"mc"}, + Long: `Get modification code`, Run: func(cmd *cobra.Command, args []string) { cmd.Help() }, @@ -32,8 +32,7 @@ var ElementModificationCodeCmd = &cobra.Command{ func init() { cobra.OnInitialize(initConfig) cobra.OnInitialize(initGlobalCodeDir) - ElementModificationCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") - + ModificationCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") } func initConfig() { @@ -41,7 +40,7 @@ func initConfig() { homeDir, _ := os.UserHomeDir() - v.BindPFlag("working_dir", ElementModificationCodeCmd.PersistentFlags().Lookup("working-dir")) + v.BindPFlag("working_dir", ModificationCodeCmd.PersistentFlags().Lookup("working-dir")) v.SetConfigFile(homeDir + "/.flagship/credentials/" + utils.WEB_EXPERIMENTATION + "/.cli.yaml") v.MergeInConfig() diff --git a/cmd/web_experimentation/variation_global_code/get-js.go b/cmd/web_experimentation/variation_global_code/get-js.go index 79a575e..e6f711a 100644 --- a/cmd/web_experimentation/variation_global_code/get-js.go +++ b/cmd/web_experimentation/variation_global_code/get-js.go @@ -26,6 +26,7 @@ var getJSCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } + variationID, err := strconv.Atoi(VariationID) if err != nil { log.Fatalf("error occurred: %v", err) diff --git a/cmd/web_experimentation/variation_global_code/info-css.go b/cmd/web_experimentation/variation_global_code/info-css.go new file mode 100644 index 0000000..8105fc1 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/info-css.go @@ -0,0 +1,64 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "log" + "strconv" + + "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// infoCSSCmd represents info-css command +var infoCSSCmd = &cobra.Command{ + Use: "info-css [-i | --id ] [--campaign-id ]", + Short: "Get variation global css code info", + Long: `Get variation global css code info `, + Run: func(cmd *cobra.Command, args []string) { + var modif web_experimentation.Modification + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == variationID && modification.Type == "addCSS" && modification.Selector == "" { + modif = modification + } + } + + utils.FormatItem([]string{"Id", "Name", "Type", "VariationID", "Selector", "Engine", "Value"}, modif, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + infoCSSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := infoCSSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + infoCSSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") + + if err := infoCSSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + VariationGlobalCodeCmd.AddCommand(infoCSSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/info-js.go b/cmd/web_experimentation/variation_global_code/info-js.go new file mode 100644 index 0000000..5f395ee --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/info-js.go @@ -0,0 +1,64 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "log" + "strconv" + + "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +// infoJSCmd represents info-js command +var infoJSCmd = &cobra.Command{ + Use: "info-js [-i | --id ] [--campaign-id ]", + Short: "Get variation global js code info", + Long: `Get variation global js code info `, + Run: func(cmd *cobra.Command, args []string) { + var modif web_experimentation.Modification + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + body, err := httprequest.ModificationRequester.HTTPListModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range body { + if modification.VariationID == variationID && modification.Type == "customScriptNew" && modification.Selector == "" { + modif = modification + } + } + + utils.FormatItem([]string{"Id", "Name", "Type", "VariationID", "Selector", "Engine", "Value"}, modif, viper.GetString("output_format"), cmd.OutOrStdout()) + }, +} + +func init() { + infoJSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + + if err := infoJSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + infoJSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") + + if err := infoJSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + VariationGlobalCodeCmd.AddCommand(infoJSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code.go b/cmd/web_experimentation/variation_global_code/variation_global_code.go index 5706e55..d6d4df9 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code.go @@ -34,7 +34,6 @@ func init() { cobra.OnInitialize(initConfig) cobra.OnInitialize(initGlobalCodeDir) VariationGlobalCodeCmd.PersistentFlags().StringVarP(&WorkingDir, "working-dir", "", utils.DefaultGlobalCodeWorkingDir(), "Directory where the file will be generated and pushed from") - } func initConfig() { diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 9fcadf0..4a0c9b9 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -11,7 +11,8 @@ import ( "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" - "github.com/flagship-io/flagship/cmd/web_experimentation/element_modification_code" + "github.com/flagship-io/flagship/cmd/web_experimentation/modification" + "github.com/flagship-io/flagship/cmd/web_experimentation/modification_code" "github.com/flagship-io/flagship/cmd/web_experimentation/token" "github.com/flagship-io/flagship/cmd/web_experimentation/variation" variation_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/variation_global_code" @@ -46,8 +47,9 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(campaign_global_code.CampaignGlobalCodeCmd) //WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) - WebExperimentationCmd.AddCommand(element_modification_code.ElementModificationCodeCmd) + WebExperimentationCmd.AddCommand(modification_code.ModificationCodeCmd) WebExperimentationCmd.AddCommand(token.TokenCmd) + WebExperimentationCmd.AddCommand(modification.ModificationCmd) } func init() { diff --git a/utils/config/config_global_code.go b/utils/config/config_global_code.go index ef20e1d..df57973 100644 --- a/utils/config/config_global_code.go +++ b/utils/config/config_global_code.go @@ -159,7 +159,7 @@ func VariationGlobalCodeDirectoryCSS(workingDir, accountID, campaignID, variatio return filePath, nil } -func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variationID, elementID, selector string, code []byte, override bool) (string, error) { +func ModificationCodeDirectory(workingDir, accountID, campaignID, variationID, modificationID, selector string, code []byte, override bool) (string, error) { gcWorkingDir, err := CheckGlobalCodeDirectory(workingDir) if err != nil { return "", err @@ -168,7 +168,7 @@ func ElementModificationCodeDirectory(workingDir, accountID, campaignID, variati accountCodeDir := gcWorkingDir + "/" + accountID campaignCodeDir := accountCodeDir + "/" + campaignID variationCodeDir := campaignCodeDir + "/" + variationID - elementCodeDir := variationCodeDir + "/" + elementID + elementCodeDir := variationCodeDir + "/" + modificationID err = os.MkdirAll(elementCodeDir, os.ModePerm) if err != nil { diff --git a/utils/config/config_global_code_test.go b/utils/config/config_global_code_test.go index 72e47b5..b508454 100644 --- a/utils/config/config_global_code_test.go +++ b/utils/config/config_global_code_test.go @@ -8,24 +8,24 @@ import ( ) type TestStruct struct { - name string - workingDir string - want string - code string - accountID string - campaignID string - variationID string - elementID string - selector string - wantErr bool + name string + workingDir string + want string + code string + accountID string + campaignID string + variationID string + modificationID string + selector string + wantErr bool } var ( - mockAccountID = "123456" - mockCampaignID = "100000" - mockVariationID = "200000" - mockElementID = "300000" - mockSelector = "document.querySelector('main')" + mockAccountID = "123456" + mockCampaignID = "100000" + mockVariationID = "200000" + mockModificationID = "300000" + mockSelector = "document.querySelector('main')" ) func TestCheckWorkingDirectory(t *testing.T) { @@ -267,7 +267,7 @@ func TestVariationGlobalCodeDirectoryCSS(t *testing.T) { } } -func TestElementModificationCodeDirectory(t *testing.T) { +func TestModificationCodeDirectory(t *testing.T) { currentDir, err := os.Getwd() if err != nil { t.Fatalf("Failed to get current working directory: %v", err) @@ -275,40 +275,40 @@ func TestElementModificationCodeDirectory(t *testing.T) { tests := []TestStruct{ { - name: "ExistingDirectory", - workingDir: currentDir, - code: "console.log('Hello, World!')", - accountID: mockAccountID, - campaignID: mockCampaignID, - variationID: mockVariationID, - elementID: mockElementID, - selector: mockSelector, - want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/" + mockVariationID + "/" + mockElementID + "/element.js", - wantErr: false, + name: "ExistingDirectory", + workingDir: currentDir, + code: "console.log('Hello, World!')", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + modificationID: mockModificationID, + selector: mockSelector, + want: currentDir + "/abtasty/" + mockAccountID + "/" + mockCampaignID + "/" + mockVariationID + "/" + mockModificationID + "/element.js", + wantErr: false, }, { - name: "NonExistingDirectory", - workingDir: "/path/to/nonexistent/directory", - code: "console.log('Hello, World!')", - accountID: mockAccountID, - campaignID: mockCampaignID, - variationID: mockVariationID, - elementID: mockElementID, - selector: mockSelector, - want: "", - wantErr: true, + name: "NonExistingDirectory", + workingDir: "/path/to/nonexistent/directory", + code: "console.log('Hello, World!')", + accountID: mockAccountID, + campaignID: mockCampaignID, + variationID: mockVariationID, + modificationID: mockModificationID, + selector: mockSelector, + want: "", + wantErr: true, }, } for i, tt := range tests { if i == 0 { t.Run(tt.name, func(t *testing.T) { - got, err := ElementModificationCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.elementID, tt.selector, []byte(tt.code), true) + got, err := ModificationCodeDirectory(tt.workingDir, tt.accountID, tt.campaignID, tt.variationID, tt.modificationID, tt.selector, []byte(tt.code), true) if (err != nil) != tt.wantErr { - t.Errorf("ElementModificationCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("ModificationCodeDirectory() error = %v, wantErr %v", err, tt.wantErr) } if got != tt.want { - t.Errorf("ElementModificationCodeDirectory() = %v, want %v", got, tt.want) + t.Errorf("ModificationCodeDirectory() = %v, want %v", got, tt.want) } }) diff --git a/utils/http_request/web_experimentation/campaign-global-code.go b/utils/http_request/web_experimentation/campaign-global-code.go index 1782567..a32deda 100644 --- a/utils/http_request/web_experimentation/campaign-global-code.go +++ b/utils/http_request/web_experimentation/campaign-global-code.go @@ -14,3 +14,8 @@ func (c *CampaignGlobalCodeRequester) HTTPGetCampaignGlobalCode(id string) (stri resp, err := common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + c.AccountID + "/tests/" + id) return resp.GlobalCodeCampaign, err } + +func (c *CampaignGlobalCodeRequester) HTTPGetCampaignGlobalCodeInfo(id string) (models.CampaignWE, error) { + resp, err := common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + c.AccountID + "/tests/" + id) + return resp, err +} From 0d58e9ada5c4d7b5f213b443d6acd6804a8fe91d Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 30 Apr 2024 15:52:02 +0200 Subject: [PATCH 43/48] add modification/modification info-js/info-css test --- .../modification/modification_test.go | 66 +++++++++++++++++++ .../modification_code_test.go | 47 +++++++++++++ .../variation_global_code_test.go | 30 +++++++++ .../campaign-global-code_test.go | 11 ++++ 4 files changed, 154 insertions(+) create mode 100644 cmd/web_experimentation/modification/modification_test.go create mode 100644 cmd/web_experimentation/modification_code/modification_code_test.go diff --git a/cmd/web_experimentation/modification/modification_test.go b/cmd/web_experimentation/modification/modification_test.go new file mode 100644 index 0000000..9a3d884 --- /dev/null +++ b/cmd/web_experimentation/modification/modification_test.go @@ -0,0 +1,66 @@ +package modification + +import ( + "encoding/json" + "strconv" + "testing" + + models "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + + mockfunction.SetMock(&http_request.ResourceRequester) + mockfunction_we.APIModification() + + m.Run() +} + +var testModification []models.Modification +var testModificationList []models.Modification + +func TestModificationCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(ModificationCmd) + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\" not set") + + successOutput, _ := utils.ExecuteCommand(ModificationCmd, "--campaign-id="+strconv.Itoa(100000)) + assert.Contains(t, successOutput, "Manage your modifications") +} + +func TestModificationHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(ModificationCmd, "--help") + assert.Contains(t, output, "Manage your modifications") +} + +func TestModificationGetCommand(t *testing.T) { + + failOutput, err := utils.ExecuteCommand(ModificationCmd, "get", "--campaign-id="+strconv.Itoa(100000)) + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(ModificationCmd, "get", "--id="+strconv.Itoa(120003), "--campaign-id="+strconv.Itoa(100000)) + + err = json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + + assert.Equal(t, []models.Modification{mockfunction_we.TestElementModification}, testModification) +} + +func TestModificationListCommand(t *testing.T) { + + output, err := utils.ExecuteCommand(ModificationCmd, "list", "--campaign-id="+strconv.Itoa(100000)) + err = json.Unmarshal([]byte(output), &testModificationList) + + assert.Nil(t, err) + assert.Equal(t, []models.Modification{mockfunction_we.TestModificationsJS, mockfunction_we.TestModificationsCSS}, testModificationList) +} diff --git a/cmd/web_experimentation/modification_code/modification_code_test.go b/cmd/web_experimentation/modification_code/modification_code_test.go new file mode 100644 index 0000000..2aa04fe --- /dev/null +++ b/cmd/web_experimentation/modification_code/modification_code_test.go @@ -0,0 +1,47 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ + +package modification_code + +import ( + "testing" + + "github.com/flagship-io/flagship/utils" + "github.com/flagship-io/flagship/utils/http_request" + mockfunction "github.com/flagship-io/flagship/utils/mock_function" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" + "github.com/jarcoal/httpmock" + "github.com/stretchr/testify/assert" +) + +func TestMain(m *testing.M) { + + httpmock.Activate() + defer httpmock.DeactivateAndReset() + defer mockfunction_we.InitMockAuth() + + mockfunction.SetMock(&http_request.ResourceRequester) + + mockfunction_we.APIModification() + + m.Run() +} + +func TestModificationCodeCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(ModificationCodeCmd) + assert.Contains(t, output, "Get modification code") +} + +func TestModificationCodeHelpCommand(t *testing.T) { + output, _ := utils.ExecuteCommand(ModificationCodeCmd, "--help") + assert.Contains(t, output, "Get modification code") +} + +func TestModificationCodeGetCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "get") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "get", "-i=120003", "--campaign-id=100000") + assert.Equal(t, "console.log(\"test modification\")\n", successOutput) +} diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go index c3dcc3b..7daedff 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go @@ -1,8 +1,10 @@ package variation_global_code import ( + "encoding/json" "testing" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" @@ -24,6 +26,8 @@ func TestMain(m *testing.M) { m.Run() } +var testModification models.Modification + func TestVariationGlobalCodeCommand(t *testing.T) { output, _ := utils.ExecuteCommand(VariationGlobalCodeCmd) assert.Contains(t, output, "Get variation global code") @@ -49,3 +53,29 @@ func TestVariationGlobalCodeGetCSSCommand(t *testing.T) { successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "get-css", "-i=110000", "--campaign-id=100000") assert.Equal(t, ".id{\"color\": \"black\"}\n", successOutput) } + +func TestVariationGlobalCodeInfoCSSCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "info-css") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "info-css", "-i=110000", "--campaign-id=100000") + + err := json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestModificationsCSS, testModification) +} + +func TestVariationGlobalCodeInfoJSCommand(t *testing.T) { + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "info-js") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "info-js", "-i=110000", "--campaign-id=100000") + + err := json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestModificationsJS, testModification) +} diff --git a/utils/http_request/web_experimentation/campaign-global-code_test.go b/utils/http_request/web_experimentation/campaign-global-code_test.go index dc8d1fb..db4522f 100644 --- a/utils/http_request/web_experimentation/campaign-global-code_test.go +++ b/utils/http_request/web_experimentation/campaign-global-code_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/flagship-io/flagship/utils/http_request/common" + mockfunction_we "github.com/flagship-io/flagship/utils/mock_function/web_experimentation" "github.com/stretchr/testify/assert" ) @@ -19,3 +20,13 @@ func TestHTTPCampaignGlobalCode(t *testing.T) { assert.Equal(t, "console.log(\"Hello World!\")", respBody) } + +func TestHTTPCampaignGlobalCodeInfo(t *testing.T) { + + respBody, err := campaignGlobalCodeRequester.HTTPGetCampaignGlobalCodeInfo("100000") + + assert.NotNil(t, respBody) + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestCampaign, respBody) +} From ee524d9b58478f53afe45552831453ce3bef0d14 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Thu, 2 May 2024 18:09:17 +0200 Subject: [PATCH 44/48] fix load resource --- cmd/feature_experimentation/resource/load.go | 46 +++++++++++++++----- utils/http_request/common/request.go | 4 +- 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 94f8d93..8701ad8 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -148,8 +148,11 @@ func Init(credL common.RequestConfig) { } type ResourceCmdStruct struct { - Name string `json:"name,omitempty"` - Data string `json:"data,omitempty"` + Name string `json:"name,omitempty"` + ResourceVariable string `json:"resource_variable,omitempty"` + Response string `json:"response,omitempty"` + Method string `json:"method,omitempty"` + Error string `json:"error,omitempty"` } func UnmarshalConfig(filePath string) ([]Resource, error) { @@ -235,6 +238,7 @@ var loadCmd = &cobra.Command{ return } } + jsonBytes := ScriptResource(cmd, gResources, inputParamsMap) if outputFile != "" { os.WriteFile(outputFile, jsonBytes, os.ModePerm) @@ -333,21 +337,31 @@ func ScriptResource(cmd *cobra.Command, resources []Resource, inputParamsMap map fmt.Fprintf(os.Stderr, "error occurred unmarshall resourceData: %v\n", err) } - for k, vInterface := range resourceData { - v, ok := vInterface.(string) - if ok { - if strings.Contains(v, "$") { - vTrim := strings.Trim(v, "$") - if inputParamsMap != nil { + if inputParamsMap != nil { + for k, vInterface := range resourceData { + v, ok := vInterface.(string) + if ok { + if strings.Contains(v, "$") { + vTrim := strings.Trim(v, "$") vTrimL := strings.Split(vTrim, ".") value, err := getNestedValue(inputParamsMap, vTrimL) if err != nil { fmt.Fprintf(os.Stderr, "Error: %s\n", err) } + if value != nil { resourceData[k] = value } } + } + } + } + + for k, vInterface := range resourceData { + v, ok := vInterface.(string) + if ok { + if strings.Contains(v, "$") { + vTrim := strings.Trim(v, "$") for k_, variable := range resourceVariables { script, _ := tengo.Eval(context.Background(), vTrim, map[string]interface{}{ k_: variable, @@ -376,11 +390,17 @@ func ScriptResource(cmd *cobra.Command, resources []Resource, inputParamsMap map } resultOutputFile = ResourceCmdStruct{ - Name: resourceName, - Data: string(response), + Name: resourceName, + Response: string(response), + ResourceVariable: resource.ResourceVariable, + Method: httpMethod, + } + + if err != nil { + resultOutputFile.Error = err.Error() } - loadResultOutputFile = append(loadResultOutputFile, resultOutputFile) + loadResultOutputFile = append(loadResultOutputFile, resultOutputFile) } if httpMethod == "DELETE" { @@ -391,13 +411,15 @@ func ScriptResource(cmd *cobra.Command, resources []Resource, inputParamsMap map if resource.Name == Goal || resource.Name == Campaign { _, err = common.HTTPRequest[ResourceData](httpMethod, utils.GetFeatureExperimentationHost()+"/v1/accounts/"+cred.AccountID+"/account_environments/"+cred.AccountEnvironmentID+url+"/"+fmt.Sprintf("%s", resourceData["id"]), nil) } + if err == nil && viper.GetString("output_format") != "json" { response = []byte("The id: " + fmt.Sprintf("%v", resourceData["id"]) + " deleted successfully") } } if err != nil { - log.Fatalf("error occurred http call: %v\n", err) + fmt.Fprintf(cmd.OutOrStdout(), "%s - %s: %s %s\n", color, resourceName, colorNone, err.Error()) + continue } if viper.GetString("output_format") != "json" { diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index 7a1bbab..f6b80ce 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -9,7 +9,6 @@ import ( "io" "log" "net/http" - "os" "reflect" "regexp" "strings" @@ -185,8 +184,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) match, _ := regexp.MatchString("4\\d\\d|5\\d\\d", resp.Status) if match { err := errors.New(string(respBody)) - fmt.Fprintf(os.Stderr, "error occurred: %v", err) - os.Exit(1) + return nil, err } return respBody, err From 1d3dcaab97443e35eb161ae960d7b25729c91526 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Tue, 14 May 2024 17:36:48 +0200 Subject: [PATCH 45/48] add push for agc and cgc --- .../account_global_code.go | 3 +- .../account_global_code_test.go | 15 +++++ .../account_global_code/get.go | 9 +-- .../account_global_code/push.go | 63 +++++++++++++++++++ cmd/web_experimentation/auth/login.go | 18 ++---- .../campaign_global_code.go | 2 +- .../campaign_global_code_test.go | 15 +++++ .../campaign_global_code/push.go | 63 +++++++++++++++++++ .../modification_code/get.go | 19 +++--- .../web_experimentation.go | 3 +- .../account-global-code.go | 16 +++++ .../campaign-global-code.go | 16 +++++ .../web_experimentation/account.go | 7 +++ .../web_experimentation/campaign.go | 7 +++ 14 files changed, 226 insertions(+), 30 deletions(-) create mode 100644 cmd/web_experimentation/account_global_code/push.go create mode 100644 cmd/web_experimentation/campaign_global_code/push.go diff --git a/cmd/web_experimentation/account_global_code/account_global_code.go b/cmd/web_experimentation/account_global_code/account_global_code.go index 9e333e6..666df0e 100644 --- a/cmd/web_experimentation/account_global_code/account_global_code.go +++ b/cmd/web_experimentation/account_global_code/account_global_code.go @@ -14,10 +14,11 @@ import ( ) var WorkingDir string +var AccountID string // AccountGlobalCodeCmd represents the account global code command var AccountGlobalCodeCmd = &cobra.Command{ - Use: "account-global-code [get]", + Use: "account-global-code [get|push]", Short: "Get account global code", Aliases: []string{"agc"}, Long: `Get account global code`, diff --git a/cmd/web_experimentation/account_global_code/account_global_code_test.go b/cmd/web_experimentation/account_global_code/account_global_code_test.go index 5f6e554..7635c5b 100644 --- a/cmd/web_experimentation/account_global_code/account_global_code_test.go +++ b/cmd/web_experimentation/account_global_code/account_global_code_test.go @@ -1,8 +1,10 @@ package account_global_code import ( + "encoding/json" "testing" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" @@ -41,3 +43,16 @@ func TestAccountGlobalCodeGetCommand(t *testing.T) { successOutput, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "get", "-i=account_id") assert.Equal(t, "console.log(\"test\")\n", successOutput) } + +func TestAccountGlobalCodePushCommand(t *testing.T) { + var testAccount models.AccountWE + + failOutput, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "push") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(AccountGlobalCodeCmd, "push", "-i=account_id", "--code=console.log(\"test\")") + err := json.Unmarshal([]byte(successOutput), &testAccount) + + assert.Nil(t, err) + assert.Equal(t, mockfunction_we.TestAccountGlobalCode, testAccount) +} diff --git a/cmd/web_experimentation/account_global_code/get.go b/cmd/web_experimentation/account_global_code/get.go index c59af1c..6cd5017 100644 --- a/cmd/web_experimentation/account_global_code/get.go +++ b/cmd/web_experimentation/account_global_code/get.go @@ -13,7 +13,6 @@ import ( "github.com/spf13/viper" ) -var accountID string var createFile bool var override bool @@ -23,28 +22,30 @@ var getCmd = &cobra.Command{ Short: "Get account global code", Long: `Get account global code`, Run: func(cmd *cobra.Command, args []string) { - body, err := httprequest.AccountGlobalCodeRequester.HTTPGetAccountGlobalCode(accountID) + body, err := httprequest.AccountGlobalCodeRequester.HTTPGetAccountGlobalCode(AccountID) if err != nil { log.Fatalf("error occurred: %v", err) } if createFile { - accountCodeDir, err := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), accountID, body, override) + accountCodeDir, err := config.AccountGlobalCodeDirectory(viper.GetString("working_dir"), AccountID, body, override) if err != nil { log.Fatalf("error occurred: %s", err) } fmt.Fprintln(cmd.OutOrStdout(), "Account code file generated successfully: ", accountCodeDir) return } + fmt.Fprintln(cmd.OutOrStdout(), body) }, } func init() { - getCmd.Flags().StringVarP(&accountID, "id", "i", "", "id of the global code account you want to display") + getCmd.Flags().StringVarP(&AccountID, "id", "i", "", "id of the global code account you want to display") if err := getCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } + getCmd.Flags().BoolVarP(&createFile, "create-file", "", false, "create a file that contains account global code") getCmd.Flags().BoolVarP(&override, "override", "", false, "override existing account global code file") diff --git a/cmd/web_experimentation/account_global_code/push.go b/cmd/web_experimentation/account_global_code/push.go new file mode 100644 index 0000000..ac0ad9d --- /dev/null +++ b/cmd/web_experimentation/account_global_code/push.go @@ -0,0 +1,63 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package account_global_code + +import ( + "fmt" + "log" + "os" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var code string +var filePath string + +// pushCmd represents push command +var pushCmd = &cobra.Command{ + Use: "push [-i | --id ]", + Short: "Push account global code", + Long: `push account global code`, + Run: func(cmd *cobra.Command, args []string) { + var codeByte []byte + + if !utils.CheckSingleFlag(filePath != "", code != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") + } + + if filePath != "" { + fileContent, err := os.ReadFile(filePath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + codeByte = fileContent + } + + if code != "" { + codeByte = []byte(code) + } + + body, err := httprequest.AccountGlobalCodeRequester.HTTPPushAccountGlobalCode(AccountID, codeByte) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + }, +} + +func init() { + pushCmd.Flags().StringVarP(&AccountID, "id", "i", "", "id of the global code account") + if err := pushCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCmd.Flags().StringVarP(&code, "code", "c", "", "new code to push in the account") + pushCmd.Flags().StringVarP(&filePath, "file", "", "", "file that contains new code to push in the account") + + AccountGlobalCodeCmd.AddCommand(pushCmd) +} diff --git a/cmd/web_experimentation/auth/login.go b/cmd/web_experimentation/auth/login.go index ea9deca..10e2c34 100644 --- a/cmd/web_experimentation/auth/login.go +++ b/cmd/web_experimentation/auth/login.go @@ -19,25 +19,13 @@ var ( accountId string ) -func checkSingleFlag(bool1, bool2 bool) bool { - count := 0 - if bool1 { - count++ - } - if bool2 { - count++ - } - - return count == 1 -} - // createCmd represents the create command var loginCmd = &cobra.Command{ Use: "login [--credential-file] | [-u | --username=] [-i | --client-id=] [-s | --client-secret=] [-a | --account-id=]", Short: "login", Long: `login`, Run: func(cmd *cobra.Command, args []string) { - if !checkSingleFlag(credentialsFile != "", Username != "") { + if !utils.CheckSingleFlag(credentialsFile != "", Username != "") { log.Fatalf("error occurred: %s", "1 flag is required. (browser, username)") } @@ -51,6 +39,7 @@ var loginCmd = &cobra.Command{ fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") return } + authenticationResponse, err := common.HTTPCreateTokenWE(v.GetString("client_id"), v.GetString("client_secret"), v.GetString("account_id")) if err != nil { fmt.Fprintf(cmd.OutOrStderr(), "error occurred: %s", err) @@ -98,6 +87,7 @@ var loginCmd = &cobra.Command{ fmt.Fprintln(cmd.OutOrStdout(), "Credential changed successfully to "+Username) return } + fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (account id)") return } @@ -106,6 +96,7 @@ var loginCmd = &cobra.Command{ fmt.Fprintln(cmd.OutOrStderr(), "Error while login, required fields (username, client ID, client secret, account id)") return } + authenticationResponse, err := common.HTTPCreateTokenWE(ClientID, ClientSecret, accountId) if err != nil { fmt.Fprintln(cmd.OutOrStderr(), err) @@ -134,7 +125,6 @@ var loginCmd = &cobra.Command{ fmt.Fprintln(cmd.OutOrStdout(), "Credential created successfully") } - }, } diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go index 1a1806d..2aa1d34 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code.go @@ -18,7 +18,7 @@ var CampaignID string // CampaignGlobalCodeCmd represents the campaign global code command var CampaignGlobalCodeCmd = &cobra.Command{ - Use: "campaign-global-code [get]", + Use: "campaign-global-code [get|push]", Short: "Get campaign global code", Aliases: []string{"cgc"}, Long: `Get campaign global code`, diff --git a/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go b/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go index 694bd3b..cdc957f 100644 --- a/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go +++ b/cmd/web_experimentation/campaign_global_code/campaign_global_code_test.go @@ -1,8 +1,10 @@ package campaign_global_code import ( + "encoding/json" "testing" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" @@ -41,3 +43,16 @@ func TestCampaignGlobalCodeGetCommand(t *testing.T) { successOutput, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "get", "-i=100000") assert.Equal(t, "console.log(\"Hello World!\")\n", successOutput) } + +func TestCampaignGlobalCodePushCommand(t *testing.T) { + var testCampaign models.CampaignWE + + failOutput, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "push") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(CampaignGlobalCodeCmd, "push", "-i=100000", "--code=console.log(\"Hello Earth!\")") + err := json.Unmarshal([]byte(successOutput), &testCampaign) + + assert.Nil(t, err) + assert.Equal(t, mockfunction_we.TestCampaign, testCampaign) +} diff --git a/cmd/web_experimentation/campaign_global_code/push.go b/cmd/web_experimentation/campaign_global_code/push.go new file mode 100644 index 0000000..637cebb --- /dev/null +++ b/cmd/web_experimentation/campaign_global_code/push.go @@ -0,0 +1,63 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign_global_code + +import ( + "fmt" + "log" + "os" + + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var code string +var filePath string + +// pushCmd represents push command +var pushCmd = &cobra.Command{ + Use: "push [-i | --id ]", + Short: "push campaign global code", + Long: `push campaign global code`, + Run: func(cmd *cobra.Command, args []string) { + var codeByte []byte + + if !utils.CheckSingleFlag(filePath != "", code != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") + } + + if filePath != "" { + fileContent, err := os.ReadFile(filePath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + codeByte = fileContent + } + + if code != "" { + codeByte = []byte(code) + } + + body, err := httprequest.CampaignGlobalCodeRequester.HTTPPushCampaignGlobalCode(CampaignID, codeByte) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + }, +} + +func init() { + pushCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the global code campaign") + if err := pushCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCmd.Flags().StringVarP(&code, "code", "c", "", "new code to push in the campaign") + pushCmd.Flags().StringVarP(&filePath, "file", "", "", "file that contains new code to push in the campaign") + + CampaignGlobalCodeCmd.AddCommand(pushCmd) +} diff --git a/cmd/web_experimentation/modification_code/get.go b/cmd/web_experimentation/modification_code/get.go index 02f7ee2..d48e2df 100644 --- a/cmd/web_experimentation/modification_code/get.go +++ b/cmd/web_experimentation/modification_code/get.go @@ -8,6 +8,7 @@ import ( "log" "strconv" + "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils/config" httprequest "github.com/flagship-io/flagship/utils/http_request" "github.com/spf13/cobra" @@ -22,9 +23,7 @@ var getCmd = &cobra.Command{ Short: "Get modification code", Long: `Get modification code`, Run: func(cmd *cobra.Command, args []string) { - var code string - var selector string - var variationID int + var modif *web_experimentation.Modification campaignID, err := strconv.Atoi(CampaignID) if err != nil { @@ -42,15 +41,17 @@ var getCmd = &cobra.Command{ for _, modification := range body { if modification.Type == "customScriptNew" && modification.Selector != "" { - code = modification.Value - selector = modification.Selector - variationID = modification.VariationID + modif = &modification } } + if modif == nil { + log.Fatalf("error occurred: no modification found") + } + if CreateFile { - fileCode := config.AddHeaderSelectorComment(selector, code) - modificationCodeDir, err := config.ModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(variationID), ModificationID, selector, fileCode, override) + fileCode := config.AddHeaderSelectorComment(modif.Selector, modif.Value) + modificationCodeDir, err := config.ModificationCodeDirectory(viper.GetString("working_dir"), httprequest.CampaignGlobalCodeRequester.AccountID, CampaignID, strconv.Itoa(modif.VariationID), ModificationID, modif.Selector, fileCode, override) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -59,7 +60,7 @@ var getCmd = &cobra.Command{ return } - fmt.Fprintln(cmd.OutOrStdout(), string(code)) + fmt.Fprintln(cmd.OutOrStdout(), string(modif.Value)) }, } diff --git a/cmd/web_experimentation/web_experimentation.go b/cmd/web_experimentation/web_experimentation.go index 4a0c9b9..7efc957 100644 --- a/cmd/web_experimentation/web_experimentation.go +++ b/cmd/web_experimentation/web_experimentation.go @@ -8,6 +8,7 @@ import ( "os" "github.com/flagship-io/flagship/cmd/web_experimentation/account" + "github.com/flagship-io/flagship/cmd/web_experimentation/account_global_code" "github.com/flagship-io/flagship/cmd/web_experimentation/auth" "github.com/flagship-io/flagship/cmd/web_experimentation/campaign" campaign_global_code "github.com/flagship-io/flagship/cmd/web_experimentation/campaign_global_code" @@ -45,7 +46,7 @@ func addSubCommandPalettes() { WebExperimentationCmd.AddCommand(auth.AuthCmd) WebExperimentationCmd.AddCommand(account.AccountCmd) WebExperimentationCmd.AddCommand(campaign_global_code.CampaignGlobalCodeCmd) - //WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) + WebExperimentationCmd.AddCommand(account_global_code.AccountGlobalCodeCmd) WebExperimentationCmd.AddCommand(variation_global_code.VariationGlobalCodeCmd) WebExperimentationCmd.AddCommand(modification_code.ModificationCodeCmd) WebExperimentationCmd.AddCommand(token.TokenCmd) diff --git a/utils/http_request/web_experimentation/account-global-code.go b/utils/http_request/web_experimentation/account-global-code.go index 51bbe15..e4b676e 100644 --- a/utils/http_request/web_experimentation/account-global-code.go +++ b/utils/http_request/web_experimentation/account-global-code.go @@ -1,6 +1,9 @@ package web_experimentation import ( + "encoding/json" + "net/http" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -14,3 +17,16 @@ func (a *AccountGlobalCodeRequester) HTTPGetAccountGlobalCode(id string) (string resp, err := common.HTTPGetItem[models.AccountWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + id) return resp.GlobalCode.Value, err } + +func (a *AccountGlobalCodeRequester) HTTPPushAccountGlobalCode(id string, code []byte) ([]byte, error) { + var gc = models.GlobalCodeStr{ + GlobalCode: string(code), + } + + data, err := json.Marshal(gc) + if err != nil { + return nil, err + } + + return common.HTTPRequest[models.AccountWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+a.AccountID, []byte(data)) +} diff --git a/utils/http_request/web_experimentation/campaign-global-code.go b/utils/http_request/web_experimentation/campaign-global-code.go index a32deda..f2660a8 100644 --- a/utils/http_request/web_experimentation/campaign-global-code.go +++ b/utils/http_request/web_experimentation/campaign-global-code.go @@ -1,6 +1,9 @@ package web_experimentation import ( + "encoding/json" + "net/http" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -15,6 +18,19 @@ func (c *CampaignGlobalCodeRequester) HTTPGetCampaignGlobalCode(id string) (stri return resp.GlobalCodeCampaign, err } +func (c *CampaignGlobalCodeRequester) HTTPPushCampaignGlobalCode(id string, code []byte) ([]byte, error) { + var gc = models.GlobalCodeStr{ + GlobalCode: string(code), + } + + data, err := json.Marshal(gc) + if err != nil { + return nil, err + } + + return common.HTTPRequest[models.CampaignWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+c.AccountID+"/tests/"+id, []byte(data)) +} + func (c *CampaignGlobalCodeRequester) HTTPGetCampaignGlobalCodeInfo(id string) (models.CampaignWE, error) { resp, err := common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + c.AccountID + "/tests/" + id) return resp, err diff --git a/utils/mock_function/web_experimentation/account.go b/utils/mock_function/web_experimentation/account.go index c5569a0..23002e6 100644 --- a/utils/mock_function/web_experimentation/account.go +++ b/utils/mock_function/web_experimentation/account.go @@ -55,4 +55,11 @@ func APIAccount() { return resp, nil }, ) + + httpmock.RegisterResponder("PATCH", utils.GetWebExperimentationHost()+"/v1/accounts/"+accountID, + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestAccountGlobalCode) + return resp, nil + }, + ) } diff --git a/utils/mock_function/web_experimentation/campaign.go b/utils/mock_function/web_experimentation/campaign.go index cd758b9..2bb1297 100644 --- a/utils/mock_function/web_experimentation/campaign.go +++ b/utils/mock_function/web_experimentation/campaign.go @@ -56,4 +56,11 @@ func APICampaign() { return resp, nil }, ) + + httpmock.RegisterResponder("PATCH", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestCampaign) + return resp, nil + }, + ) } From 7d7c090c1e5fbf708b2331316ad917bfdce5853b Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 15 May 2024 11:42:01 +0200 Subject: [PATCH 46/48] add push for vgc and mc --- .../modification_code/modification_code.go | 2 +- .../modification_code_test.go | 15 +++ .../modification_code/push.go | 115 ++++++++++++++++++ .../variation_global_code/push-css.go | 101 +++++++++++++++ .../variation_global_code/push-js.go | 101 +++++++++++++++ .../variation_global_code_test.go | 27 ++++ models/web_experimentation/global-code.go | 13 ++ utils/functions.go | 12 ++ utils/http_request/common/request.go | 1 + .../web_experimentation/modification.go | 21 ++++ .../web_experimentation/modification.go | 20 +++ 11 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 cmd/web_experimentation/modification_code/push.go create mode 100644 cmd/web_experimentation/variation_global_code/push-css.go create mode 100644 cmd/web_experimentation/variation_global_code/push-js.go diff --git a/cmd/web_experimentation/modification_code/modification_code.go b/cmd/web_experimentation/modification_code/modification_code.go index 6850e4a..acd3c53 100644 --- a/cmd/web_experimentation/modification_code/modification_code.go +++ b/cmd/web_experimentation/modification_code/modification_code.go @@ -20,7 +20,7 @@ var CreateFile bool // ModificationCodeCmd represents the variation global code command var ModificationCodeCmd = &cobra.Command{ - Use: "modification-code [get]", + Use: "modification-code [get|push]", Short: "Get modification code", Aliases: []string{"mc"}, Long: `Get modification code`, diff --git a/cmd/web_experimentation/modification_code/modification_code_test.go b/cmd/web_experimentation/modification_code/modification_code_test.go index 2aa04fe..4bc27c8 100644 --- a/cmd/web_experimentation/modification_code/modification_code_test.go +++ b/cmd/web_experimentation/modification_code/modification_code_test.go @@ -5,8 +5,10 @@ Copyright © 2022 Flagship Team flagship@abtasty.com package modification_code import ( + "encoding/json" "testing" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request" mockfunction "github.com/flagship-io/flagship/utils/mock_function" @@ -45,3 +47,16 @@ func TestModificationCodeGetCommand(t *testing.T) { successOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "get", "-i=120003", "--campaign-id=100000") assert.Equal(t, "console.log(\"test modification\")\n", successOutput) } + +func TestModificationCodePushCommand(t *testing.T) { + var testModification models.Modification + + failOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "push") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "push", "-i=120003", "--campaign-id=100000", "--code=console.log(\"test modification\")") + err := json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + assert.Equal(t, mockfunction_we.TestElementModification, testModification) +} diff --git a/cmd/web_experimentation/modification_code/push.go b/cmd/web_experimentation/modification_code/push.go new file mode 100644 index 0000000..030e4df --- /dev/null +++ b/cmd/web_experimentation/modification_code/push.go @@ -0,0 +1,115 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package modification_code + +import ( + "fmt" + "log" + "os" + "strconv" + + "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var code string +var filePath string +var selector string + +// pushCmd represents get command +var pushCmd = &cobra.Command{ + Use: "push [-i | --id ] [--campaign-id ]", + Short: "push modification code", + Long: `push modification code`, + Run: func(cmd *cobra.Command, args []string) { + var codeByte []byte + var modif *web_experimentation.Modification + + if !utils.CheckSingleFlag(filePath != "", code != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") + } + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + modificationID, err := strconv.Atoi(ModificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + modifList, err := httprequest.ModificationRequester.HTTPGetModification(campaignID, modificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range modifList { + if modification.Type == "customScriptNew" && modification.Selector != "" { + modif = &modification + } + } + + if modif == nil { + log.Fatalf("error occurred: no modification found") + } + + if filePath != "" { + fileContent, err := os.ReadFile(filePath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + codeByte = fileContent + } + + if code != "" { + codeByte = []byte(code) + } + + selector_ := modif.Selector + + if selector != "" { + selector_ = selector + } + + modifToPush := web_experimentation.ModificationCodeStr{ + InputType: "modification", + Name: modif.Name, + Value: string(codeByte), + Selector: selector_, + Type: modif.Type, + Engine: modif.Engine, + } + + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modif.Id, modifToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + }, +} + +func init() { + pushCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the campaign") + + if err := pushCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the modification code you want to display") + + if err := pushCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCmd.Flags().StringVarP(&code, "code", "c", "", "new code to push in the modification") + pushCmd.Flags().StringVarP(&selector, "selector", "", "", "new selector to push in the modification") + + pushCmd.Flags().StringVarP(&filePath, "file", "", "", "file that contains new code to push in the modification") + + ModificationCodeCmd.AddCommand(pushCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/push-css.go b/cmd/web_experimentation/variation_global_code/push-css.go new file mode 100644 index 0000000..0bd589f --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/push-css.go @@ -0,0 +1,101 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "fmt" + "log" + "os" + "strconv" + + "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var cssCode string +var cssFilePath string + +// pushCSSCmd represents push command +var pushCSSCmd = &cobra.Command{ + Use: "push-css [-i | --id ] [--campaign-id ]", + Short: "push variation global css code", + Long: `push variation global css code`, + Run: func(cmd *cobra.Command, args []string) { + var modifId int + var codeByte []byte + + if !utils.CheckSingleFlag(cssFilePath != "", cssCode != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") + } + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + modifList, err := httprequest.ModificationRequester.HTTPListModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range modifList { + if modification.VariationID == variationID && modification.Type == "addCSS" && modification.Selector == "" { + modifId = modification.Id + } + } + + if modifId == 0 { + log.Fatalf("error occurred: no global variation found") + } + + if cssFilePath != "" { + fileContent, err := os.ReadFile(cssFilePath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + codeByte = fileContent + } + + if cssCode != "" { + codeByte = []byte(cssCode) + } + + modifToPush := web_experimentation.ModificationCodeStr{ + InputType: "modification", + Value: string(codeByte), + } + + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modifId, modifToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + }, +} + +func init() { + pushCSSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + if err := pushCSSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCSSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") + if err := pushCSSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushCSSCmd.Flags().StringVarP(&cssCode, "code", "c", "", "new code to push in the variation") + pushCSSCmd.Flags().StringVarP(&cssFilePath, "file", "", "", "file that contains new code to push in the variation") + + VariationGlobalCodeCmd.AddCommand(pushCSSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/push-js.go b/cmd/web_experimentation/variation_global_code/push-js.go new file mode 100644 index 0000000..d5c8496 --- /dev/null +++ b/cmd/web_experimentation/variation_global_code/push-js.go @@ -0,0 +1,101 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation_global_code + +import ( + "fmt" + "log" + "os" + "strconv" + + "github.com/flagship-io/flagship/models/web_experimentation" + "github.com/flagship-io/flagship/utils" + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +var jsCode string +var jsFilePath string + +// pushJsCmd represents push command +var pushJSCmd = &cobra.Command{ + Use: "push-js [-i | --id ] [--campaign-id ]", + Short: "push variation global js code", + Long: `push variation global js code`, + Run: func(cmd *cobra.Command, args []string) { + var modifId int + var codeByte []byte + + if !utils.CheckSingleFlag(jsFilePath != "", jsCode != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") + } + + campaignID, err := strconv.Atoi(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + variationID, err := strconv.Atoi(VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + modifList, err := httprequest.ModificationRequester.HTTPListModification(campaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + for _, modification := range modifList { + if modification.VariationID == variationID && modification.Type == "customScriptNew" && modification.Selector == "" { + modifId = modification.Id + } + } + + if modifId == 0 { + log.Fatalf("error occurred: no global variation found") + } + + if jsFilePath != "" { + fileContent, err := os.ReadFile(jsFilePath) + if err != nil { + log.Fatalf("error occurred: %s", err) + } + + codeByte = fileContent + } + + if jsCode != "" { + codeByte = []byte(jsCode) + } + + modifToPush := web_experimentation.ModificationCodeStr{ + InputType: "modification", + Value: string(codeByte), + } + + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modifId, modifToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + }, +} + +func init() { + pushJSCmd.Flags().StringVarP(&CampaignID, "campaign-id", "", "", "id of the global code campaign you want to display") + if err := pushJSCmd.MarkFlagRequired("campaign-id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushJSCmd.Flags().StringVarP(&VariationID, "id", "i", "", "id of the global code variation you want to display") + if err := pushJSCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + pushJSCmd.Flags().StringVarP(&jsCode, "code", "c", "", "new code to push in the variation") + pushJSCmd.Flags().StringVarP(&jsFilePath, "file", "", "", "file that contains new code to push in the variation") + + VariationGlobalCodeCmd.AddCommand(pushJSCmd) +} diff --git a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go index 7daedff..bb30224 100644 --- a/cmd/web_experimentation/variation_global_code/variation_global_code_test.go +++ b/cmd/web_experimentation/variation_global_code/variation_global_code_test.go @@ -79,3 +79,30 @@ func TestVariationGlobalCodeInfoJSCommand(t *testing.T) { assert.Equal(t, mockfunction_we.TestModificationsJS, testModification) } + +func TestVariationGlobalCodePushJSCommand(t *testing.T) { + var testModification models.Modification + + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "push-js") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "push-js", "-i=110000", "--campaign-id=100000", "--code=console.log(\"test modification\")") + err := json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + assert.Equal(t, mockfunction_we.TestModificationsJS, testModification) +} + +func TestVariationGlobalCodePushCSSCommand(t *testing.T) { + var testModification models.Modification + + failOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "push-css") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + + successOutput, _ := utils.ExecuteCommand(VariationGlobalCodeCmd, "push-css", "-i=110000", "--campaign-id=100000", "--code=.id{\"color\": \"black\"}") + err := json.Unmarshal([]byte(successOutput), &testModification) + + assert.Nil(t, err) + + assert.Equal(t, mockfunction_we.TestModificationsCSS, testModification) +} diff --git a/models/web_experimentation/global-code.go b/models/web_experimentation/global-code.go index bc4236d..4f37f42 100644 --- a/models/web_experimentation/global-code.go +++ b/models/web_experimentation/global-code.go @@ -5,3 +5,16 @@ type GlobalCode struct { Code string `json:"code"` CreatedAt DateTemplate `json:"created_at"` } + +type GlobalCodeStr struct { + GlobalCode string `json:"global_code"` +} + +type ModificationCodeStr struct { + InputType string `json:"input_type"` + Name string `json:"name,omitempty"` + Value string `json:"value,omitempty"` + Selector string `json:"selector,omitempty"` + Type string `json:"type,omitempty"` + Engine string `json:"engine,omitempty"` +} diff --git a/utils/functions.go b/utils/functions.go index 17fd6c3..67e769c 100644 --- a/utils/functions.go +++ b/utils/functions.go @@ -43,3 +43,15 @@ func ExecuteCommand(cmd *cobra.Command, args ...string) (output string, err erro return buf.String(), err } + +func CheckSingleFlag(bool1, bool2 bool) bool { + count := 0 + if bool1 { + count++ + } + if bool2 { + count++ + } + + return count == 1 +} diff --git a/utils/http_request/common/request.go b/utils/http_request/common/request.go index f6b80ce..d6b2196 100644 --- a/utils/http_request/common/request.go +++ b/utils/http_request/common/request.go @@ -170,6 +170,7 @@ func HTTPRequest[T any](method string, url string, body []byte) ([]byte, error) default: reader = resp.Body } + respBody, err := io.ReadAll(reader) if err != nil { return nil, err diff --git a/utils/http_request/web_experimentation/modification.go b/utils/http_request/web_experimentation/modification.go index 2b6feff..aeeffce 100644 --- a/utils/http_request/web_experimentation/modification.go +++ b/utils/http_request/web_experimentation/modification.go @@ -1,8 +1,11 @@ package web_experimentation import ( + "encoding/json" + "net/http" "strconv" + "github.com/flagship-io/flagship/models/web_experimentation" models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -21,3 +24,21 @@ func (m *ModificationRequester) HTTPGetModification(campaignID int, id int) ([]m resp, err := common.HTTPGetItem[models.ModificationDataWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + m.AccountID + "/tests/" + strconv.Itoa(campaignID) + "/modifications?ids=" + strconv.Itoa(id)) return resp.Data.Modifications, err } + +func (m *ModificationRequester) HTTPEditModification(campaignID int, id int, modificationData web_experimentation.ModificationCodeStr) ([]byte, error) { + data, err := json.Marshal(modificationData) + if err != nil { + return nil, err + } + + return common.HTTPRequest[models.ModificationDataWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+m.AccountID+"/tests/"+strconv.Itoa(campaignID)+"/modifications/"+strconv.Itoa(id), data) +} + +func (m *ModificationRequester) HTTPCreateModification(campaignID int, modificationData web_experimentation.ModificationCodeStr) ([]byte, error) { + data, err := json.Marshal(modificationData) + if err != nil { + return nil, err + } + + return common.HTTPRequest[models.ModificationDataWE](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+m.AccountID+"/tests/"+strconv.Itoa(campaignID)+"/modifications", data) +} diff --git a/utils/mock_function/web_experimentation/modification.go b/utils/mock_function/web_experimentation/modification.go index 57f1798..92ee445 100644 --- a/utils/mock_function/web_experimentation/modification.go +++ b/utils/mock_function/web_experimentation/modification.go @@ -69,4 +69,24 @@ func APIModification() { }, ) + httpmock.RegisterResponder("PATCH", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications/"+strconv.Itoa(TestElementModification.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestElementModification) + return resp, nil + }, + ) + + httpmock.RegisterResponder("PATCH", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications/"+strconv.Itoa(TestModificationsJS.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestModificationsJS) + return resp, nil + }, + ) + + httpmock.RegisterResponder("PATCH", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications/"+strconv.Itoa(TestModificationsCSS.Id), + func(req *http.Request) (*http.Response, error) { + resp, _ := httpmock.NewJsonResponse(200, TestModificationsCSS) + return resp, nil + }, + ) } From 196371744e9541fd4d4b071445f10a54193b6d21 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 15 May 2024 14:07:39 +0200 Subject: [PATCH 47/48] fix push bug --- cmd/feature_experimentation/resource/load.go | 32 +++++++++-- .../modification_code/push.go | 56 ++++++++++++++----- .../variation_global_code/push-css.go | 32 ++++++++--- .../variation_global_code/push-js.go | 32 ++++++++--- models/web_experimentation/global-code.go | 12 +++- .../web_experimentation/modification.go | 4 +- 6 files changed, 128 insertions(+), 40 deletions(-) diff --git a/cmd/feature_experimentation/resource/load.go b/cmd/feature_experimentation/resource/load.go index 8701ad8..b89b9cb 100644 --- a/cmd/feature_experimentation/resource/load.go +++ b/cmd/feature_experimentation/resource/load.go @@ -23,9 +23,10 @@ import ( ) var ( - resourceFile string - outputFile string - inputParams string + resourceFile string + outputFile string + inputParams string + inputParamsFile string ) var inputParamsMap map[string]interface{} @@ -231,12 +232,30 @@ var loadCmd = &cobra.Command{ Short: "Load your resources", Long: `Load your resources`, Run: func(cmd *cobra.Command, args []string) { + var params []byte + + if !utils.CheckSingleFlag(inputParams != "", inputParamsFile != "") { + log.Fatalf("error occurred: %s", "1 flag is required. (input-params, input-params-file)") + } + if inputParams != "" { - err := json.Unmarshal([]byte(inputParams), &inputParamsMap) + params = []byte(inputParams) + + } + + if inputParamsFile != "" { + fileContent, err := os.ReadFile(inputParamsFile) if err != nil { - fmt.Fprintf(cmd.OutOrStderr(), "Error: %s", err) - return + log.Fatalf("error occurred: %s", err) } + + params = fileContent + } + + err := json.Unmarshal(params, &inputParamsMap) + if err != nil { + fmt.Fprintf(cmd.OutOrStderr(), "Error: %s", err) + return } jsonBytes := ScriptResource(cmd, gResources, inputParamsMap) @@ -264,6 +283,7 @@ func init() { loadCmd.Flags().StringVarP(&outputFile, "output-file", "", "", "result of the command that contains all resource informations") loadCmd.Flags().StringVarP(&inputParams, "input-params", "", "", "params to replace resource loader file") + loadCmd.Flags().StringVarP(&inputParamsFile, "input-params-file", "", "", "file that contains params to replace resource loader file") ResourceCmd.AddCommand(loadCmd) } diff --git a/cmd/web_experimentation/modification_code/push.go b/cmd/web_experimentation/modification_code/push.go index 030e4df..7f3bda6 100644 --- a/cmd/web_experimentation/modification_code/push.go +++ b/cmd/web_experimentation/modification_code/push.go @@ -18,6 +18,7 @@ import ( var code string var filePath string var selector string +var variationID string // pushCmd represents get command var pushCmd = &cobra.Command{ @@ -26,7 +27,7 @@ var pushCmd = &cobra.Command{ Long: `push modification code`, Run: func(cmd *cobra.Command, args []string) { var codeByte []byte - var modif *web_experimentation.Modification + var modification_ web_experimentation.Modification if !utils.CheckSingleFlag(filePath != "", code != "") { log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") @@ -36,6 +37,12 @@ var pushCmd = &cobra.Command{ if err != nil { log.Fatalf("error occurred: %v", err) } + + variationID_, err := strconv.Atoi(variationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + modificationID, err := strconv.Atoi(ModificationID) if err != nil { log.Fatalf("error occurred: %v", err) @@ -48,14 +55,10 @@ var pushCmd = &cobra.Command{ for _, modification := range modifList { if modification.Type == "customScriptNew" && modification.Selector != "" { - modif = &modification + modification_ = modification } } - if modif == nil { - log.Fatalf("error occurred: no modification found") - } - if filePath != "" { fileContent, err := os.ReadFile(filePath) if err != nil { @@ -69,22 +72,45 @@ var pushCmd = &cobra.Command{ codeByte = []byte(code) } - selector_ := modif.Selector - + selector_ := modification_.Selector if selector != "" { selector_ = selector } - modifToPush := web_experimentation.ModificationCodeStr{ + if modification_ == (web_experimentation.Modification{}) { + if variationID_ == 0 && selector == "" { + log.Fatalf("error occurred: Flag variation-id and selector are required.") + } + + modificationToPush := web_experimentation.ModificationCodeCreateStruct{ + InputType: "modification", + Name: "", + Value: string(codeByte), + Selector: selector, + Type: "customScriptNew", + Engine: "", + VariationID: variationID_, + } + + body, err := httprequest.ModificationRequester.HTTPCreateModification(campaignID, modificationToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + return + } + + modificationToPush := web_experimentation.ModificationCodeEditStruct{ InputType: "modification", - Name: modif.Name, + Name: modification_.Name, Value: string(codeByte), Selector: selector_, - Type: modif.Type, - Engine: modif.Engine, + Type: modification_.Type, + Engine: modification_.Engine, } - body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modif.Id, modifToPush) + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modification_.Id, modificationToPush) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -100,15 +126,15 @@ func init() { log.Fatalf("error occurred: %v", err) } - pushCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the modification code you want to display") + pushCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the modification code") if err := pushCmd.MarkFlagRequired("id"); err != nil { log.Fatalf("error occurred: %v", err) } + pushCmd.Flags().StringVarP(&variationID, "variation-id", "", "", "id of the variation") pushCmd.Flags().StringVarP(&code, "code", "c", "", "new code to push in the modification") pushCmd.Flags().StringVarP(&selector, "selector", "", "", "new selector to push in the modification") - pushCmd.Flags().StringVarP(&filePath, "file", "", "", "file that contains new code to push in the modification") ModificationCodeCmd.AddCommand(pushCmd) diff --git a/cmd/web_experimentation/variation_global_code/push-css.go b/cmd/web_experimentation/variation_global_code/push-css.go index 0bd589f..cd4f432 100644 --- a/cmd/web_experimentation/variation_global_code/push-css.go +++ b/cmd/web_experimentation/variation_global_code/push-css.go @@ -24,7 +24,7 @@ var pushCSSCmd = &cobra.Command{ Short: "push variation global css code", Long: `push variation global css code`, Run: func(cmd *cobra.Command, args []string) { - var modifId int + var modificationId int var codeByte []byte if !utils.CheckSingleFlag(cssFilePath != "", cssCode != "") { @@ -48,14 +48,10 @@ var pushCSSCmd = &cobra.Command{ for _, modification := range modifList { if modification.VariationID == variationID && modification.Type == "addCSS" && modification.Selector == "" { - modifId = modification.Id + modificationId = modification.Id } } - if modifId == 0 { - log.Fatalf("error occurred: no global variation found") - } - if cssFilePath != "" { fileContent, err := os.ReadFile(cssFilePath) if err != nil { @@ -69,12 +65,32 @@ var pushCSSCmd = &cobra.Command{ codeByte = []byte(cssCode) } - modifToPush := web_experimentation.ModificationCodeStr{ + if modificationId == 0 { + modificationToPush := web_experimentation.ModificationCodeCreateStruct{ + InputType: "modification", + Name: "", + Value: string(codeByte), + Selector: "", + Type: "addCSS", + Engine: "", + VariationID: variationID, + } + + body, err := httprequest.ModificationRequester.HTTPCreateModification(campaignID, modificationToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + return + } + + modificationToPush := web_experimentation.ModificationCodeEditStruct{ InputType: "modification", Value: string(codeByte), } - body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modifId, modifToPush) + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modificationId, modificationToPush) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/cmd/web_experimentation/variation_global_code/push-js.go b/cmd/web_experimentation/variation_global_code/push-js.go index d5c8496..b205b1a 100644 --- a/cmd/web_experimentation/variation_global_code/push-js.go +++ b/cmd/web_experimentation/variation_global_code/push-js.go @@ -24,7 +24,7 @@ var pushJSCmd = &cobra.Command{ Short: "push variation global js code", Long: `push variation global js code`, Run: func(cmd *cobra.Command, args []string) { - var modifId int + var modificationId int var codeByte []byte if !utils.CheckSingleFlag(jsFilePath != "", jsCode != "") { @@ -48,14 +48,10 @@ var pushJSCmd = &cobra.Command{ for _, modification := range modifList { if modification.VariationID == variationID && modification.Type == "customScriptNew" && modification.Selector == "" { - modifId = modification.Id + modificationId = modification.Id } } - if modifId == 0 { - log.Fatalf("error occurred: no global variation found") - } - if jsFilePath != "" { fileContent, err := os.ReadFile(jsFilePath) if err != nil { @@ -69,12 +65,32 @@ var pushJSCmd = &cobra.Command{ codeByte = []byte(jsCode) } - modifToPush := web_experimentation.ModificationCodeStr{ + if modificationId == 0 { + modificationToPush := web_experimentation.ModificationCodeCreateStruct{ + InputType: "modification", + Name: "", + Value: string(codeByte), + Selector: "", + Type: "customScriptNew", + Engine: "", + VariationID: variationID, + } + + body, err := httprequest.ModificationRequester.HTTPCreateModification(campaignID, modificationToPush) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), string(body)) + return + } + + modificationToPush := web_experimentation.ModificationCodeEditStruct{ InputType: "modification", Value: string(codeByte), } - body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modifId, modifToPush) + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modificationId, modificationToPush) if err != nil { log.Fatalf("error occurred: %v", err) } diff --git a/models/web_experimentation/global-code.go b/models/web_experimentation/global-code.go index 4f37f42..f409519 100644 --- a/models/web_experimentation/global-code.go +++ b/models/web_experimentation/global-code.go @@ -10,7 +10,7 @@ type GlobalCodeStr struct { GlobalCode string `json:"global_code"` } -type ModificationCodeStr struct { +type ModificationCodeEditStruct struct { InputType string `json:"input_type"` Name string `json:"name,omitempty"` Value string `json:"value,omitempty"` @@ -18,3 +18,13 @@ type ModificationCodeStr struct { Type string `json:"type,omitempty"` Engine string `json:"engine,omitempty"` } + +type ModificationCodeCreateStruct struct { + InputType string `json:"input_type"` + Name string `json:"name"` + Value string `json:"value"` + Selector string `json:"selector"` + Type string `json:"type"` + Engine string `json:"engine"` + VariationID int `json:"variation_id"` +} diff --git a/utils/http_request/web_experimentation/modification.go b/utils/http_request/web_experimentation/modification.go index aeeffce..72daa5c 100644 --- a/utils/http_request/web_experimentation/modification.go +++ b/utils/http_request/web_experimentation/modification.go @@ -25,7 +25,7 @@ func (m *ModificationRequester) HTTPGetModification(campaignID int, id int) ([]m return resp.Data.Modifications, err } -func (m *ModificationRequester) HTTPEditModification(campaignID int, id int, modificationData web_experimentation.ModificationCodeStr) ([]byte, error) { +func (m *ModificationRequester) HTTPEditModification(campaignID int, id int, modificationData web_experimentation.ModificationCodeEditStruct) ([]byte, error) { data, err := json.Marshal(modificationData) if err != nil { return nil, err @@ -34,7 +34,7 @@ func (m *ModificationRequester) HTTPEditModification(campaignID int, id int, mod return common.HTTPRequest[models.ModificationDataWE](http.MethodPatch, utils.GetWebExperimentationHost()+"/v1/accounts/"+m.AccountID+"/tests/"+strconv.Itoa(campaignID)+"/modifications/"+strconv.Itoa(id), data) } -func (m *ModificationRequester) HTTPCreateModification(campaignID int, modificationData web_experimentation.ModificationCodeStr) ([]byte, error) { +func (m *ModificationRequester) HTTPCreateModification(campaignID int, modificationData web_experimentation.ModificationCodeCreateStruct) ([]byte, error) { data, err := json.Marshal(modificationData) if err != nil { return nil, err From c4d1a26f1eb633bb9021a74d5aa93707760cd7e2 Mon Sep 17 00:00:00 2001 From: Chadi LAOULAOU Date: Wed, 15 May 2024 17:10:04 +0200 Subject: [PATCH 48/48] fix modification push & add delete cmd for campaign/variation/modification --- .../campaign/campaign_test.go | 11 ++- cmd/web_experimentation/campaign/delete.go | 36 ++++++++++ .../modification/delete.go | 37 ++++++++++ .../modification/modification.go | 2 +- .../modification/modification_test.go | 9 +++ .../modification_code_test.go | 4 +- .../modification_code/push.go | 70 +++++++++---------- cmd/web_experimentation/variation/delete.go | 37 ++++++++++ .../variation/variation.go | 2 +- .../variation/variation_test.go | 9 +++ .../web_experimentation/campaign.go | 8 +++ .../web_experimentation/campaign_test.go | 7 ++ .../web_experimentation/modification.go | 5 ++ .../web_experimentation/modification_test.go | 7 ++ .../web_experimentation/variation.go | 6 ++ .../web_experimentation/variation_test.go | 7 ++ .../web_experimentation/campaign.go | 10 ++- .../web_experimentation/modification.go | 7 ++ .../web_experimentation/variation.go | 6 ++ 19 files changed, 235 insertions(+), 45 deletions(-) create mode 100644 cmd/web_experimentation/campaign/delete.go create mode 100644 cmd/web_experimentation/modification/delete.go create mode 100644 cmd/web_experimentation/variation/delete.go diff --git a/cmd/web_experimentation/campaign/campaign_test.go b/cmd/web_experimentation/campaign/campaign_test.go index b2a6925..c70d6fb 100644 --- a/cmd/web_experimentation/campaign/campaign_test.go +++ b/cmd/web_experimentation/campaign/campaign_test.go @@ -61,5 +61,14 @@ func TestCampaignListCommand(t *testing.T) { assert.Nil(t, err) - assert.Equal(t, mockfunction_we.TestCampaignlist, testCampaignList) + assert.Equal(t, mockfunction_we.TestCampaignList, testCampaignList) +} + +func TestCampaignDeleteCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(CampaignCmd, "delete") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(CampaignCmd, "delete", "--id=100000") + assert.Equal(t, "Campaign deleted\n", successOutput) } diff --git a/cmd/web_experimentation/campaign/delete.go b/cmd/web_experimentation/campaign/delete.go new file mode 100644 index 0000000..52ce855 --- /dev/null +++ b/cmd/web_experimentation/campaign/delete.go @@ -0,0 +1,36 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package campaign + +import ( + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +// deleteCmd represents delete command +var deleteCmd = &cobra.Command{ + Use: "delete [-i | --id=]", + Short: "Delete a campaign", + Long: `Delete a campaign`, + Run: func(cmd *cobra.Command, args []string) { + err := httprequest.CampaignWERequester.HTTPDeleteCampaign(CampaignID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + fmt.Fprintln(cmd.OutOrStdout(), "Campaign deleted") + }, +} + +func init() { + deleteCmd.Flags().StringVarP(&CampaignID, "id", "i", "", "id of the campaign you want to delete") + + if err := deleteCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + CampaignCmd.AddCommand(deleteCmd) +} diff --git a/cmd/web_experimentation/modification/delete.go b/cmd/web_experimentation/modification/delete.go new file mode 100644 index 0000000..44bd1d0 --- /dev/null +++ b/cmd/web_experimentation/modification/delete.go @@ -0,0 +1,37 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package modification + +import ( + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +// deleteCmd represents delete command +var deleteCmd = &cobra.Command{ + Use: "delete [-i | --id=] [--campaign-id ]", + Short: "Delete a modification", + Long: `Delete a modification`, + Run: func(cmd *cobra.Command, args []string) { + err := httprequest.ModificationRequester.HTTPDeleteModification(CampaignID, ModificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "Modification deleted") + + }, +} + +func init() { + deleteCmd.Flags().IntVarP(&ModificationID, "id", "i", 0, "id of the modification you want to delete") + + if err := deleteCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + ModificationCmd.AddCommand(deleteCmd) +} diff --git a/cmd/web_experimentation/modification/modification.go b/cmd/web_experimentation/modification/modification.go index 0b5b869..c824cb7 100644 --- a/cmd/web_experimentation/modification/modification.go +++ b/cmd/web_experimentation/modification/modification.go @@ -18,7 +18,7 @@ var ( // modificationCmd represents the modification command var ModificationCmd = &cobra.Command{ - Use: "modification [get|list|delete|switch]", + Use: "modification [get|list|delete]", Short: "Manage your modifications", Long: `Manage your modifications`, Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/web_experimentation/modification/modification_test.go b/cmd/web_experimentation/modification/modification_test.go index 9a3d884..8fb7a37 100644 --- a/cmd/web_experimentation/modification/modification_test.go +++ b/cmd/web_experimentation/modification/modification_test.go @@ -64,3 +64,12 @@ func TestModificationListCommand(t *testing.T) { assert.Nil(t, err) assert.Equal(t, []models.Modification{mockfunction_we.TestModificationsJS, mockfunction_we.TestModificationsCSS}, testModificationList) } + +func TestModificationDeleteCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(ModificationCmd, "delete") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(ModificationCmd, "delete", "--campaign-id=100000", "--id=120003") + assert.Equal(t, "Modification deleted\n", successOutput) +} diff --git a/cmd/web_experimentation/modification_code/modification_code_test.go b/cmd/web_experimentation/modification_code/modification_code_test.go index 4bc27c8..fada57e 100644 --- a/cmd/web_experimentation/modification_code/modification_code_test.go +++ b/cmd/web_experimentation/modification_code/modification_code_test.go @@ -42,7 +42,7 @@ func TestModificationCodeHelpCommand(t *testing.T) { func TestModificationCodeGetCommand(t *testing.T) { failOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "get") - assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\nUsage") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set\n") successOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "get", "-i=120003", "--campaign-id=100000") assert.Equal(t, "console.log(\"test modification\")\n", successOutput) @@ -52,7 +52,7 @@ func TestModificationCodePushCommand(t *testing.T) { var testModification models.Modification failOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "push") - assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\", \"id\" not set") + assert.Contains(t, failOutput, "Error: required flag(s) \"campaign-id\" not set") successOutput, _ := utils.ExecuteCommand(ModificationCodeCmd, "push", "-i=120003", "--campaign-id=100000", "--code=console.log(\"test modification\")") err := json.Unmarshal([]byte(successOutput), &testModification) diff --git a/cmd/web_experimentation/modification_code/push.go b/cmd/web_experimentation/modification_code/push.go index 7f3bda6..09f04c6 100644 --- a/cmd/web_experimentation/modification_code/push.go +++ b/cmd/web_experimentation/modification_code/push.go @@ -27,7 +27,6 @@ var pushCmd = &cobra.Command{ Long: `push modification code`, Run: func(cmd *cobra.Command, args []string) { var codeByte []byte - var modification_ web_experimentation.Modification if !utils.CheckSingleFlag(filePath != "", code != "") { log.Fatalf("error occurred: %s", "1 flag is required. (file, code)") @@ -38,27 +37,6 @@ var pushCmd = &cobra.Command{ log.Fatalf("error occurred: %v", err) } - variationID_, err := strconv.Atoi(variationID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - modificationID, err := strconv.Atoi(ModificationID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - modifList, err := httprequest.ModificationRequester.HTTPGetModification(campaignID, modificationID) - if err != nil { - log.Fatalf("error occurred: %v", err) - } - - for _, modification := range modifList { - if modification.Type == "customScriptNew" && modification.Selector != "" { - modification_ = modification - } - } - if filePath != "" { fileContent, err := os.ReadFile(filePath) if err != nil { @@ -72,16 +50,16 @@ var pushCmd = &cobra.Command{ codeByte = []byte(code) } - selector_ := modification_.Selector - if selector != "" { - selector_ = selector - } - - if modification_ == (web_experimentation.Modification{}) { - if variationID_ == 0 && selector == "" { + if ModificationID == "" { + if variationID == "" && selector == "" { log.Fatalf("error occurred: Flag variation-id and selector are required.") } + variationID_, err := strconv.Atoi(variationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + modificationToPush := web_experimentation.ModificationCodeCreateStruct{ InputType: "modification", Name: "", @@ -101,16 +79,37 @@ var pushCmd = &cobra.Command{ return } + modificationID, err := strconv.Atoi(ModificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + modificationList, err := httprequest.ModificationRequester.HTTPGetModification(campaignID, modificationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + + if len(modificationList) == 0 { + log.Fatalf("error occurred: Modification not found.") + } + + modification := modificationList[0] + + selector_ := modification.Selector + if selector != "" { + selector_ = selector + } + modificationToPush := web_experimentation.ModificationCodeEditStruct{ InputType: "modification", - Name: modification_.Name, + Name: modification.Name, Value: string(codeByte), Selector: selector_, - Type: modification_.Type, - Engine: modification_.Engine, + Type: modification.Type, + Engine: modification.Engine, } - body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modification_.Id, modificationToPush) + body, err := httprequest.ModificationRequester.HTTPEditModification(campaignID, modification.Id, modificationToPush) if err != nil { log.Fatalf("error occurred: %v", err) } @@ -127,11 +126,6 @@ func init() { } pushCmd.Flags().StringVarP(&ModificationID, "id", "i", "", "id of the modification code") - - if err := pushCmd.MarkFlagRequired("id"); err != nil { - log.Fatalf("error occurred: %v", err) - } - pushCmd.Flags().StringVarP(&variationID, "variation-id", "", "", "id of the variation") pushCmd.Flags().StringVarP(&code, "code", "c", "", "new code to push in the modification") pushCmd.Flags().StringVarP(&selector, "selector", "", "", "new selector to push in the modification") diff --git a/cmd/web_experimentation/variation/delete.go b/cmd/web_experimentation/variation/delete.go new file mode 100644 index 0000000..8d60ede --- /dev/null +++ b/cmd/web_experimentation/variation/delete.go @@ -0,0 +1,37 @@ +/* +Copyright © 2022 Flagship Team flagship@abtasty.com +*/ +package variation + +import ( + "fmt" + "log" + + httprequest "github.com/flagship-io/flagship/utils/http_request" + "github.com/spf13/cobra" +) + +// deleteCmd represents delete command +var deleteCmd = &cobra.Command{ + Use: "delete [-i | --id=] [--campaign-id ]", + Short: "Delete a variation", + Long: `Delete a variation`, + Run: func(cmd *cobra.Command, args []string) { + err := httprequest.VariationWERequester.HTTPDeleteVariation(CampaignID, VariationID) + if err != nil { + log.Fatalf("error occurred: %v", err) + } + fmt.Fprintln(cmd.OutOrStdout(), "Variation deleted") + + }, +} + +func init() { + deleteCmd.Flags().IntVarP(&VariationID, "id", "i", 0, "id of the variation you want to delete") + + if err := deleteCmd.MarkFlagRequired("id"); err != nil { + log.Fatalf("error occurred: %v", err) + } + + VariationCmd.AddCommand(deleteCmd) +} diff --git a/cmd/web_experimentation/variation/variation.go b/cmd/web_experimentation/variation/variation.go index baa6a16..e55735c 100644 --- a/cmd/web_experimentation/variation/variation.go +++ b/cmd/web_experimentation/variation/variation.go @@ -18,7 +18,7 @@ var ( // VariationCmd represents the variation command var VariationCmd = &cobra.Command{ - Use: "variation [create|edit|get|delete]", + Use: "variation [get|delete]", Short: "Manage your variation", Long: `Manage your variation`, Run: func(cmd *cobra.Command, args []string) { diff --git a/cmd/web_experimentation/variation/variation_test.go b/cmd/web_experimentation/variation/variation_test.go index 8b58203..359a5bb 100644 --- a/cmd/web_experimentation/variation/variation_test.go +++ b/cmd/web_experimentation/variation/variation_test.go @@ -50,3 +50,12 @@ func TestVariationGetCommand(t *testing.T) { assert.Nil(t, err) assert.Equal(t, mockfunction_we.TestVariation, testVariation) } + +func TestVariationDeleteCommand(t *testing.T) { + + failOutput, _ := utils.ExecuteCommand(VariationCmd, "delete") + assert.Contains(t, failOutput, "Error: required flag(s) \"id\" not set") + + successOutput, _ := utils.ExecuteCommand(VariationCmd, "delete", "--campaign-id=100000", "--id=110000") + assert.Equal(t, "Variation deleted\n", successOutput) +} diff --git a/utils/http_request/web_experimentation/campaign.go b/utils/http_request/web_experimentation/campaign.go index f59230b..41b11e7 100644 --- a/utils/http_request/web_experimentation/campaign.go +++ b/utils/http_request/web_experimentation/campaign.go @@ -1,6 +1,8 @@ package web_experimentation import ( + "net/http" + models "github.com/flagship-io/flagship/models/web_experimentation" "github.com/flagship-io/flagship/utils" "github.com/flagship-io/flagship/utils/http_request/common" @@ -17,3 +19,9 @@ func (t *CampaignWERequester) HTTPListCampaign() ([]models.CampaignWE, error) { func (t *CampaignWERequester) HTTPGetCampaign(id string) (models.CampaignWE, error) { return common.HTTPGetItem[models.CampaignWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + t.AccountID + "/tests/" + id) } + +func (t *CampaignWERequester) HTTPDeleteCampaign(id string) error { + _, err := common.HTTPRequest[models.CampaignWE](http.MethodDelete, utils.GetWebExperimentationHost()+"/v1/accounts/"+t.AccountID+"/tests/"+id, nil) + + return err +} diff --git a/utils/http_request/web_experimentation/campaign_test.go b/utils/http_request/web_experimentation/campaign_test.go index 9e02674..f9a3753 100644 --- a/utils/http_request/web_experimentation/campaign_test.go +++ b/utils/http_request/web_experimentation/campaign_test.go @@ -44,3 +44,10 @@ func TestHTTPListCampaign(t *testing.T) { assert.Equal(t, "ab", respBody[1].Type) } + +func TestHTTPDeleteCampaign(t *testing.T) { + + err := campaignRequester.HTTPDeleteCampaign("100000") + + assert.Nil(t, err) +} diff --git a/utils/http_request/web_experimentation/modification.go b/utils/http_request/web_experimentation/modification.go index 72daa5c..882db4b 100644 --- a/utils/http_request/web_experimentation/modification.go +++ b/utils/http_request/web_experimentation/modification.go @@ -42,3 +42,8 @@ func (m *ModificationRequester) HTTPCreateModification(campaignID int, modificat return common.HTTPRequest[models.ModificationDataWE](http.MethodPost, utils.GetWebExperimentationHost()+"/v1/accounts/"+m.AccountID+"/tests/"+strconv.Itoa(campaignID)+"/modifications", data) } + +func (m *ModificationRequester) HTTPDeleteModification(campaignID int, id int) error { + _, err := common.HTTPRequest[models.ModificationDataWE](http.MethodDelete, utils.GetWebExperimentationHost()+"/v1/accounts/"+m.AccountID+"/tests/"+strconv.Itoa(campaignID)+"/modifications/"+strconv.Itoa(id)+"?input_type=modification", nil) + return err +} diff --git a/utils/http_request/web_experimentation/modification_test.go b/utils/http_request/web_experimentation/modification_test.go index fe9c5d4..0c6058e 100644 --- a/utils/http_request/web_experimentation/modification_test.go +++ b/utils/http_request/web_experimentation/modification_test.go @@ -32,3 +32,10 @@ func TestHTTPGetModification(t *testing.T) { assert.Equal(t, []models.Modification{web_experimentation.TestModification.Data.Modifications[0]}, respBody) } + +func TestHTTPDeleteModification(t *testing.T) { + + err := modificationRequester.HTTPDeleteModification(100000, 120003) + + assert.Nil(t, err) +} diff --git a/utils/http_request/web_experimentation/variation.go b/utils/http_request/web_experimentation/variation.go index 465a0b4..1b991d4 100644 --- a/utils/http_request/web_experimentation/variation.go +++ b/utils/http_request/web_experimentation/variation.go @@ -1,6 +1,7 @@ package web_experimentation import ( + "net/http" "strconv" models "github.com/flagship-io/flagship/models/web_experimentation" @@ -15,3 +16,8 @@ type VariationWERequester struct { func (v *VariationWERequester) HTTPGetVariation(testID, id int) (models.VariationWE, error) { return common.HTTPGetItem[models.VariationWE](utils.GetWebExperimentationHost() + "/v1/accounts/" + v.AccountID + "/tests/" + strconv.Itoa(testID) + "/variations/" + strconv.Itoa(id)) } + +func (v *VariationWERequester) HTTPDeleteVariation(testID, id int) error { + _, err := common.HTTPRequest[models.VariationWE](http.MethodDelete, utils.GetWebExperimentationHost()+"/v1/accounts/"+v.AccountID+"/tests/"+strconv.Itoa(testID)+"/variations/"+strconv.Itoa(id), nil) + return err +} diff --git a/utils/http_request/web_experimentation/variation_test.go b/utils/http_request/web_experimentation/variation_test.go index 5362c85..fe6fa3f 100644 --- a/utils/http_request/web_experimentation/variation_test.go +++ b/utils/http_request/web_experimentation/variation_test.go @@ -20,3 +20,10 @@ func TestHTTPGetVariation(t *testing.T) { assert.Equal(t, web_experimentation.TestVariation, respBody) } + +func TestHTTPDeleteVariation(t *testing.T) { + + err := variationRequester.HTTPDeleteVariation(100000, 110000) + + assert.Nil(t, err) +} diff --git a/utils/mock_function/web_experimentation/campaign.go b/utils/mock_function/web_experimentation/campaign.go index 2bb1297..4943d19 100644 --- a/utils/mock_function/web_experimentation/campaign.go +++ b/utils/mock_function/web_experimentation/campaign.go @@ -26,7 +26,7 @@ var TestCampaign1 = models.CampaignWE{ GlobalCodeCampaign: "console.log(\"Hello Earth!\")", } -var TestCampaignlist = []models.CampaignWE{ +var TestCampaignList = []models.CampaignWE{ TestCampaign, TestCampaign1, } @@ -34,7 +34,7 @@ var TestCampaignlist = []models.CampaignWE{ func APICampaign() { respList := utils.HTTPListResponseWE[models.CampaignWE]{ - Data: TestCampaignlist, + Data: TestCampaignList, Pagination: utils.Pagination{ Total: 1, Pages: 2, @@ -63,4 +63,10 @@ func APICampaign() { return resp, nil }, ) + + httpmock.RegisterResponder("DELETE", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id), + func(req *http.Request) (*http.Response, error) { + return httpmock.NewStringResponse(204, ""), nil + }, + ) } diff --git a/utils/mock_function/web_experimentation/modification.go b/utils/mock_function/web_experimentation/modification.go index 92ee445..bc7010f 100644 --- a/utils/mock_function/web_experimentation/modification.go +++ b/utils/mock_function/web_experimentation/modification.go @@ -89,4 +89,11 @@ func APIModification() { return resp, nil }, ) + + httpmock.RegisterResponder("DELETE", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/modifications/"+strconv.Itoa(TestElementModification.Id), + func(req *http.Request) (*http.Response, error) { + return httpmock.NewStringResponse(204, ""), nil + + }, + ) } diff --git a/utils/mock_function/web_experimentation/variation.go b/utils/mock_function/web_experimentation/variation.go index 3f36f0a..9ac7f6a 100644 --- a/utils/mock_function/web_experimentation/variation.go +++ b/utils/mock_function/web_experimentation/variation.go @@ -25,4 +25,10 @@ func APIVariation() { }, ) + httpmock.RegisterResponder("DELETE", utils.GetWebExperimentationHost()+"/v1/accounts/"+mockfunction.Auth.AccountID+"/tests/"+strconv.Itoa(TestCampaign.Id)+"/variations/"+strconv.Itoa(TestVariation.Id), + func(req *http.Request) (*http.Response, error) { + return httpmock.NewStringResponse(204, ""), nil + }, + ) + }