How to use Get method of main Package

Best Syzkaller code snippet using main.Get

abci_test.go

Source:abci_test.go Github

copy

Full Screen

...161 testapp.AddMaccPerms(collector, perms)162 testapp.AddMaccPerms("c4e_distributor", nil)163 app := testapp.Setup(false)164 ctx := app.BaseApp.NewContext(false, tmproto.Header{})165 // app.AccountKeeper.GetModuleAccount(ctx, "c4e_distributor");166 //prepare module account with coin to distribute fee_collector 1017167 cointToMint := sdk.NewCoin(denom, sdk.NewInt(1017))168 app.BankKeeper.MintCoins(ctx, collector, sdk.NewCoins(cointToMint))169 require.EqualValues(t, cointToMint, app.BankKeeper.GetSupply(ctx, denom))170 var subdistributors []types.SubDistributor171 subdistributors = append(subdistributors, prepareBurningDistributor(destinationType))172 app.CfedistributorKeeper.SetParams(ctx, types.NewParams(subdistributors))173 ctx = ctx.WithBlockHeight(int64(2))174 app.BeginBlocker(ctx, abci.RequestBeginBlock{})175 //coin on "burnState" should be equal 498, remains: 1 and 0.33 on remains176 burnState, _ := app.CfedistributorKeeper.GetState(ctx, "burn_state_key")177 ctx.Logger().Error(burnState.String())178 //burnState, _ := app.CfedistributorKeeper.GetAllStates()179 coinRemains := burnState.CoinsStates180 require.EqualValues(t, sdk.MustNewDecFromStr("0.67"), coinRemains.AmountOf("uc4e"))181 if destinationType == MainCollector {182 mainCollectorCoins :=183 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)184 require.EqualValues(t, 1, len(app.CfedistributorKeeper.GetAllStates(ctx)))185 require.EqualValues(t, sdk.NewInt(499), mainCollectorCoins.AmountOf(denom))186 } else if destinationType == ModuleAccount {187 mainCollectorCoins :=188 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)189 c4eModulAccountCoins :=190 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, "c4e_distributor")191 require.EqualValues(t, 2, len(app.CfedistributorKeeper.GetAllStates(ctx)))192 require.EqualValues(t, sdk.NewInt(498), c4eModulAccountCoins.AmountOf(denom))193 require.EqualValues(t, sdk.NewInt(1), mainCollectorCoins.AmountOf(denom))194 c4eDistrState, _ := app.CfedistributorKeeper.GetState(ctx, "c4e_distributor")195 coinRemains := c4eDistrState.CoinsStates196 require.EqualValues(t, sdk.MustNewDecFromStr("0.33"), coinRemains.AmountOf("uc4e"))197 } else if destinationType == InternalAccount {198 mainCollectorCoins :=199 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)200 require.EqualValues(t, 2, len(app.CfedistributorKeeper.GetAllStates(ctx)))201 require.EqualValues(t, sdk.NewInt(499), mainCollectorCoins.AmountOf(denom))202 c4eDistrState, _ := app.CfedistributorKeeper.GetState(ctx, "c4e_distributor")203 coinRemains := c4eDistrState.CoinsStates204 require.EqualValues(t, sdk.MustNewDecFromStr("498.33"), coinRemains.AmountOf("uc4e"))205 } else {206 address, _ := sdk.AccAddressFromBech32("cosmos13zg4u07ymq83uq73t2cq3dj54jj37zzgr3hlck")207 mainCollectorCoins :=208 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)209 accountCoins :=210 app.CfedistributorKeeper.GetAccountCoins(ctx, address)211 require.EqualValues(t, 2, len(app.CfedistributorKeeper.GetAllStates(ctx)))212 ctx.Logger().Error(accountCoins.AmountOf(denom).String())213 println("Amount: " + accountCoins.AmountOf(denom).String())214 require.EqualValues(t, sdk.NewInt(498), accountCoins.AmountOf(denom))215 require.EqualValues(t, sdk.NewInt(1), mainCollectorCoins.AmountOf(denom))216 c4eDistrState, _ := app.CfedistributorKeeper.GetState(ctx, "cosmos13zg4u07ymq83uq73t2cq3dj54jj37zzgr3hlck")217 coinRemains := c4eDistrState.CoinsStates218 require.EqualValues(t, sdk.MustNewDecFromStr("0.33"), coinRemains.AmountOf("uc4e"))219 }220 require.EqualValues(t, sdk.NewCoin(denom, sdk.NewInt(499)), app.BankKeeper.GetSupply(ctx, denom))221}222func TestBurningWithInflationDistributorPassThroughMainCollector(t *testing.T) {223 BurningWithInflationDistributorTest(t, MainCollector, true)224}225func TestBurningWithInflationDistributorPassThroughModuleAccount(t *testing.T) {226 BurningWithInflationDistributorTest(t, ModuleAccount, true)227}228func TestBurningWithInflationDistributorPassInternalAccountAccount(t *testing.T) {229 BurningWithInflationDistributorTest(t, InternalAccount, true)230}231func TestBurningWithInflationDistributorPassBaseAccountAccount(t *testing.T) {232 BurningWithInflationDistributorTest(t, BaseAccount, true)233}234func TestBurningWithInflationDistributorPassThroughMainCollectorNoValidators(t *testing.T) {235 BurningWithInflationDistributorTest(t, MainCollector, false)236}237func TestBurningWithInflationDistributorPassThroughModuleAccountNoValidators(t *testing.T) {238 BurningWithInflationDistributorTest(t, ModuleAccount, false)239}240func TestBurningWithInflationDistributorPassInternalAccountAccountNoValidators(t *testing.T) {241 BurningWithInflationDistributorTest(t, InternalAccount, false)242}243func TestBurningWithInflationDistributorPassBaseAccountAccountNoValidators(t *testing.T) {244 BurningWithInflationDistributorTest(t, BaseAccount, false)245}246func BurningWithInflationDistributorTest(t *testing.T, passThroughAccoutType DestinationType, toValidators bool) {247 perms := []string{authtypes.Minter, authtypes.Burner}248 collector := "fee_collector"249 testapp.AddMaccPerms("c4e_distributor", nil)250 testapp.AddMaccPerms("no_validators", nil)251 denom := "uc4e"252 testapp.AddMaccPerms(collector, perms)253 testapp.AddMaccPerms(types.DistributorMainAccount, perms)254 app := testapp.Setup(false)255 ctx := app.BaseApp.NewContext(false, tmproto.Header{})256 //prepare module account with coin to distribute fee_collector 1017257 cointToMint := sdk.NewCoin(denom, sdk.NewInt(1017))258 app.BankKeeper.MintCoins(ctx, collector, sdk.NewCoins(cointToMint))259 cointToMintFromInflation := sdk.NewCoin(denom, sdk.NewInt(5044))260 app.BankKeeper.MintCoins(ctx, types.DistributorMainAccount, sdk.NewCoins(cointToMintFromInflation))261 require.EqualValues(t, sdk.NewCoin(denom, sdk.NewInt(1017+5044)), app.BankKeeper.GetSupply(ctx, denom))262 var subDistributors []types.SubDistributor263 subDistributors = append(subDistributors, prepareBurningDistributor(MainCollector))264 if passThroughAccoutType != MainCollector {265 subDistributors = append(subDistributors, prepareInflationToPassAcoutSubDistr(passThroughAccoutType))266 }267 subDistributors = append(subDistributors, prepareInflationSubDistributor(passThroughAccoutType, toValidators))268 app.CfedistributorKeeper.SetParams(ctx, types.NewParams(subDistributors))269 ctx = ctx.WithBlockHeight(int64(2))270 app.BeginBlocker(ctx, abci.RequestBeginBlock{})271 if passThroughAccoutType == MainCollector {272 require.EqualValues(t, 3, len(app.CfedistributorKeeper.GetAllStates(ctx)))273 } else if passThroughAccoutType == ModuleAccount {274 require.EqualValues(t, 4, len(app.CfedistributorKeeper.GetAllStates(ctx)))275 } else if passThroughAccoutType == InternalAccount {276 require.EqualValues(t, 4, len(app.CfedistributorKeeper.GetAllStates(ctx)))277 } else {278 require.EqualValues(t, 4, len(app.CfedistributorKeeper.GetAllStates(ctx)))279 }280 // coins flow:281 // fee 1017*51% = 518.67 to burn, so 518 burned - and burn remains 0.67282 require.EqualValues(t, sdk.NewCoin(denom, sdk.NewInt(1017+5044-518)), app.BankKeeper.GetSupply(ctx, denom))283 burnState, _ := app.CfedistributorKeeper.GetBurnState(ctx)284 coinRemains := burnState.CoinsStates285 require.EqualValues(t, sdk.MustNewDecFromStr("0.67"), coinRemains.AmountOf("uc4e"))286 // added 499 to main collector287 // main collector state = 499 + 5044 = 5543, but 5543 - 0,67 = 5542.33 to distribute288 if passThroughAccoutType == ModuleAccount || passThroughAccoutType == InternalAccount {289 // 5542.33 moved to c4e_distributor module or internal account290 // and all is distributed further, and 0 in remains291 c4eDIstrCoins := app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, "c4e_distributor")292 require.EqualValues(t, sdk.MustNewDecFromStr("0"), c4eDIstrCoins.AmountOf(denom).ToDec())293 remains, _ := app.CfedistributorKeeper.GetState(ctx, "c4e_distributor")294 //require.EqualValues(t, passThroughAccoutType == ModuleAccount, remains.Account.IsModuleAccount)295 //require.EqualValues(t, passThroughAccoutType == InternalAccount, remains.Account.IsInternalAccount)296 //require.EqualValues(t, false, remains.Account.IsMainCollector)297 coinRemainsDevelopmentFund := remains.CoinsStates298 require.EqualValues(t, sdk.MustNewDecFromStr("0"), coinRemainsDevelopmentFund.AmountOf("uc4e"))299 } else if passThroughAccoutType == BaseAccount {300 // 5542.33 moved to cosmos13zg4u07ymq83uq73t2cq3dj54jj37zzgr3hlck account301 // and all is distributed further, and 0 in remains302 address, _ := sdk.AccAddressFromBech32("cosmos13zg4u07ymq83uq73t2cq3dj54jj37zzgr3hlck")303 c4eDIstrCoins := app.CfedistributorKeeper.GetAccountCoins(ctx, address)304 require.EqualValues(t, sdk.MustNewDecFromStr("0"), c4eDIstrCoins.AmountOf(denom).ToDec())305 remains, _ := app.CfedistributorKeeper.GetState(ctx, "cosmos13zg4u07ymq83uq73t2cq3dj54jj37zzgr3hlck")306 //require.EqualValues(t, passThroughAccoutType == ModuleAccount, remains.Account.IsModuleAccount)307 //require.EqualValues(t, passThroughAccoutType == InternalAccount, remains.Account.IsInternalAccount)308 //require.EqualValues(t, false, remains.Account.IsMainCollector)309 coinRemainsDevelopmentFund := remains.CoinsStates310 require.EqualValues(t, sdk.MustNewDecFromStr("0"), coinRemainsDevelopmentFund.AmountOf("uc4e"))311 }312 // 5542.33*10.345% = 573.3540385 to cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag, so313 // 573 on cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag and 0.3540385 on its distributor state314 acc, _ := sdk.AccAddressFromBech32("cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag")315 developmentFundAccount := app.CfedistributorKeeper.GetAccountCoins(ctx, acc)316 require.EqualValues(t, sdk.MustNewDecFromStr("573"), developmentFundAccount.AmountOf(denom).ToDec())317 remains, _ := app.CfedistributorKeeper.GetState(ctx, "cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag")318 coinRemainsDevelopmentFund := remains.CoinsStates319 require.EqualValues(t, sdk.MustNewDecFromStr("0.3540385"), coinRemainsDevelopmentFund.AmountOf("uc4e"))320 // 5542.33 - 573.3540385 = 4968.9759615 to validators_rewards_collector, so321 // 4968 on validators_rewards_collector or no_validators module account and 0.9759615 on its distributor state322 if toValidators {323 // validators_rewards_collector coins sent to vaalidator distribition so amount is 0,324 validatorRewardCollectorAccountCoin := app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.ValidatorsRewardsCollector)325 require.EqualValues(t, sdk.MustNewDecFromStr("0"), validatorRewardCollectorAccountCoin.AmountOf(denom).ToDec())326 // still 0.9759615 on its distributor state remains327 remains, _ = app.CfedistributorKeeper.GetState(ctx, types.ValidatorsRewardsCollector)328 coinRemainsValidatorsReward := remains.CoinsStates329 require.EqualValues(t, sdk.MustNewDecFromStr("0.9759615"), coinRemainsValidatorsReward.AmountOf("uc4e"))330 // and 4968 to validators rewards331 distrCoins := app.CfedistributorKeeper.GetAccountCoins(ctx, app.DistrKeeper.GetDistributionAccount(ctx).GetAddress())332 require.EqualValues(t, sdk.NewCoins(sdk.NewCoin("uc4e", sdk.NewInt(4968))), distrCoins)333 } else {334 // no_validators module account coins amount is 4968,335 // and remains 0.9759615 on its distributor state336 NoValidatorsCoin := app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, "no_validators")337 require.EqualValues(t, sdk.MustNewDecFromStr("4968"), NoValidatorsCoin.AmountOf(denom).ToDec())338 remains, _ = app.CfedistributorKeeper.GetState(ctx, "no_validators")339 coinRemainsValidatorsReward := remains.CoinsStates340 require.EqualValues(t, sdk.MustNewDecFromStr("0.9759615"), coinRemainsValidatorsReward.AmountOf("uc4e"))341 }342 // 5543 - 573 - 4968 = 2 (its ramains 0,67 + 0.3540385 + 0.9759615 = 2) on main collector343 coinOnDistributorAccount :=344 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)345 require.EqualValues(t, sdk.MustNewDecFromStr("2"), coinOnDistributorAccount.AmountOf(denom).ToDec())346}347func TestBurningWithInflationDistributorAfter3001Blocks(t *testing.T) {348 perms := []string{authtypes.Minter, authtypes.Burner}349 collector := "fee_collector"350 denom := "uc4e"351 // inflationCollector := "c4e_distributor"352 testapp.AddMaccPerms(collector, perms)353 testapp.AddMaccPerms(types.DistributorMainAccount, perms)354 app := testapp.Setup(false)355 ctx := app.BaseApp.NewContext(false, tmproto.Header{})356 var subdistributors []types.SubDistributor357 subdistributors = append(subdistributors, prepareBurningDistributor(MainCollector))358 subdistributors = append(subdistributors, prepareInflationSubDistributor(MainCollector, true))359 app.CfedistributorKeeper.SetParams(ctx, types.NewParams(subdistributors))360 for i := int64(1); i <= 3001; i++ {361 cointToMint := sdk.NewCoin(denom, sdk.NewInt(1017))362 app.BankKeeper.MintCoins(ctx, collector, sdk.NewCoins(cointToMint))363 cointToMintFromInflation := sdk.NewCoin(denom, sdk.NewInt(5044))364 app.BankKeeper.MintCoins(ctx, types.DistributorMainAccount, sdk.NewCoins(cointToMintFromInflation))365 ctx = ctx.WithBlockHeight(int64(i))366 app.BeginBlocker(ctx, abci.RequestBeginBlock{})367 app.EndBlocker(ctx, abci.RequestEndBlock{})368 burn, _ := sdk.NewDecFromStr("518.67")369 burn = burn.MulInt64(i)370 burn.GT(burn.TruncateDec())371 totalExpected := sdk.NewDec(i * (1017 + 5044)).Sub(burn)372 totalExpectedTruncated := totalExpected.TruncateInt()373 if burn.GT(burn.TruncateDec()) {374 totalExpectedTruncated = totalExpectedTruncated.AddRaw(1)375 }376 require.EqualValues(t, sdk.NewCoin(denom, totalExpectedTruncated).String(), app.BankKeeper.GetSupply(ctx, denom).String())377 }378 ctx = ctx.WithBlockHeight(int64(3002))379 app.BeginBlocker(ctx, abci.RequestBeginBlock{})380 app.EndBlocker(ctx, abci.RequestEndBlock{})381 // coins flow:382 // fee 3001*1017*51% = 1556528.67 to burn, so 1556528 burned - and burn remains 0.67383 // fee 3001*(1017*51%) = 3001*518.67 = 1556528.67 to burn, so 1556528 burned - and burn remains 0.67384 require.EqualValues(t, sdk.NewCoin(denom, sdk.NewInt(3001*(1017+5044)-1556528)), app.BankKeeper.GetSupply(ctx, denom))385 burnState, _ := app.CfedistributorKeeper.GetBurnState(ctx)386 coinRemains := burnState.CoinsStates387 require.EqualValues(t, sdk.MustNewDecFromStr("0.67"), coinRemains.AmountOf("uc4e"))388 // added 3001*1017 - 1556528 = 1495489 to main collector389 // main collector state = 1495489 + 3001*5044 = 16632533, but 16632533 - 0.67 (burning remains) = 16632532.33 to distribute390 // 16632532.33*10.345% = 1720635.4695385 to cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag, so391 // 1720635 on cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag and 0.4695385 on its distributor state392 acc, _ := sdk.AccAddressFromBech32("cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag")393 developmentFundAccount := app.CfedistributorKeeper.GetAccountCoins(ctx, acc)394 require.EqualValues(t, sdk.MustNewDecFromStr("1720635"), developmentFundAccount.AmountOf(denom).ToDec())395 remains, _ := app.CfedistributorKeeper.GetState(ctx, "cosmos1p20lmfzp4g9vywl2jxwexwh6akvkxzpa6hdrag")396 coinRemainsDevelopmentFund := remains.CoinsStates397 require.EqualValues(t, sdk.MustNewDecFromStr("0.4695385"), coinRemainsDevelopmentFund.AmountOf("uc4e"))398 // 16632532.33- 1720635.4695385 = 14911896.8604615 to validators_rewards_collector, so399 // 14911896 on validators_rewards_collector or no_validators module account and 0.8604615 on its distributor state400 // validators_rewards_collector coins sent to vaalidator distribition so amount is 0,401 validatorRewardCollectorAccountCoin := app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.ValidatorsRewardsCollector)402 require.EqualValues(t, sdk.MustNewDecFromStr("0"), validatorRewardCollectorAccountCoin.AmountOf(denom).ToDec())403 // still 0.8845 on its distributor state remains404 remains, _ = app.CfedistributorKeeper.GetState(ctx, types.ValidatorsRewardsCollector)405 coinRemainsValidatorsReward := remains.CoinsStates406 require.EqualValues(t, sdk.MustNewDecFromStr("0.8604615"), coinRemainsValidatorsReward.AmountOf("uc4e"))407 // and 14906927 to validators rewards408 distrCoins := app.CfedistributorKeeper.GetAccountCoins(ctx, app.DistrKeeper.GetDistributionAccount(ctx).GetAddress())409 require.EqualValues(t, sdk.NewCoins(sdk.NewCoin("uc4e", sdk.NewInt(14911896))), distrCoins)410 // 16632533 - 1720635 - 14911896 = 1 (its ramains 0.67 + 0.4695385 + 0.8604615 = 2) on main collector411 coinOnDistributorAccount :=412 app.CfedistributorKeeper.GetAccountCoinsForModuleAccount(ctx, types.DistributorMainAccount)413 require.EqualValues(t, sdk.MustNewDecFromStr("2"), coinOnDistributorAccount.AmountOf(denom).ToDec())414}...

Full Screen

Full Screen

composite.go

Source:composite.go Github

copy

Full Screen

...11 si.checkMergePhase(mergePhaseServicesTwo)12 if !si.HasSourceMainCatalog() {13 return14 }15 if si.GetSourceMainCatalog().Kind == kindComposite {16 // Parent Composite17 if base, _ := ParseCompositeName(si.GetSourceMainCatalog().Name); base != "" {18 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a name that itself a composite child name`, "name=%s", si.GetSourceMainCatalog().Name).TagCRN().TagCatalogComposite()19 }20 comp := si.GetSourceMainCatalog().ObjectMetaData.Other.Composite21 if comp == nil {22 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry is of kind=composite but does not contain a ObjectMetaData.Other.Composite section`, "").TagCRN().TagCatalogComposite()23 return24 }25 if comp.CompositeKind == kindComposite {26 si.AddValidationIssue(ossvalidation.CRITICAL, `Main Catalog entry is of kind=composite) but its composite_kind (for child entries) is itself "composite" (not supported by this tool)`, "").TagCRN().TagCatalogComposite()27 }28 for _, childEntry := range comp.Children {29 childInfo, found := LookupService(MakeComparableName(childEntry.Name), false)30 base, _ := ParseCompositeName(childEntry.Name)31 if base != si.GetSourceMainCatalog().Name {32 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a child entry name that is not formed using the Composite parent name as a base`, "child=%s parent=%s", childEntry.Name, si.GetSourceMainCatalog().Name).TagCRN().TagCatalogComposite()33 }34 if childEntry.Kind != comp.CompositeKind {35 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a child entry Kind that is not the same as the main composite_kind`, "child=%s composite_kind=%s child.kind=%s", childEntry.Name, comp.CompositeKind, childEntry.Kind).TagCRN().TagCatalogComposite()36 }37 if !found || childInfo.OSSValidation.NumTrueSources() == 0 {38 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite references a child object that is not found in any source`, "child=%s", childEntry.Name).TagCRN().TagCatalogComposite()39 continue40 }41 issues := 042 if childInfo.mergeWorkArea.compositeParent != "" {43 if childInfo.mergeWorkArea.compositeParent == si.OSSService.ReferenceResourceName {44 childInfo.AddValidationIssue(ossvalidation.CRITICAL, "Main Catalog entry is referenced as a child more than once from the same Composite parent", `parent="%s"`, childInfo.mergeWorkArea.compositeParent).TagCRN().TagCatalogComposite()45 } else {46 childInfo.AddValidationIssue(ossvalidation.CRITICAL, "Main Catalog entry is referenced as a child of more than one Composite parent", `parent1="%s" parent2="%s"`, childInfo.mergeWorkArea.compositeParent, si.OSSService.ReferenceResourceName).TagCRN().TagCatalogComposite()47 }48 issues++49 } else {50 childInfo.mergeWorkArea.compositeParent = si.OSSService.ReferenceResourceName51 debug.Debug(debug.Composite, `Found composite child in parent %s -> %s`, si.OSSService.ReferenceResourceName, childInfo.OSSService.ReferenceResourceName)52 }53 if !childInfo.HasSourceMainCatalog() {54 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite references a child object found in some sources but not in the Catalog iself`, "child=%s sources=%v%v", childEntry.Name, childInfo.OSSValidation.CanonicalNameSources, childInfo.OSSValidation.OtherNamesSources).TagCRN().TagCatalogComposite()55 childInfo.AddValidationIssue(ossvalidation.SEVERE, `Entry is a child of a Composite entry in the Catalog but is not itself in the Catalog`, `parent_name="%s"`, si.OSSService.ReferenceResourceName).TagCRN().TagCatalogComposite()56 /*57 if debug.IsDebugEnabled(debug.Composite) {58 buf, _ := json.MarshalIndent(childInfo, " ", " ")59 debug.Debug(debug.Composite, "checkComposite(%s,%s): child found but not in Catalog: childEntry=%+v childServiceInfo=%s", si.String(), childEntry, &childEntry, buf)60 }61 */62 continue63 }64 if childInfo.GetSourceMainCatalog().Name != childEntry.Name {65 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a child object that is found but whose name is not an exact match`, "expected=%s got=%s", childEntry.Name, childInfo.GetSourceMainCatalog().Name).TagCRN().TagCatalogComposite()66 childInfo.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry is a child of a Composite entry but its name is not an exact match for the reference in the parent", `parent_name="%s" actual_child_name="%s" expected_child_name="%s"`, si.OSSService.ReferenceResourceName, childInfo.GetSourceMainCatalog().Name, childEntry.Name).TagCRN().TagCatalogComposite()67 issues++68 }69 if base2, _ := ParseCompositeName(childInfo.GetSourceMainCatalog().Name); base2 != si.GetSourceMainCatalog().Name {70 childInfo.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry is a child of a Composite entry but its name is not formed using the Composite parent name as a base", `parent_name="%s" child_name="%s" child_base_name="%s"`, si.OSSService.ReferenceResourceName, childInfo.GetSourceMainCatalog().Name, base2).TagCRN().TagCatalogComposite()71 issues++72 }73 if childInfo.GetSourceMainCatalog().Kind != childEntry.Kind {74 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a child object that is not of the expected Kind`, "child=%s expected_kind=%s got=%s", childEntry.Name, childEntry.Kind, childInfo.GetSourceMainCatalog().Kind).TagCRN().TagCatalogComposite()75 childInfo.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry is a child of a Composite entry but does not have the expected Kind as specified in the parent", `parent_name="%s" child_kind="%s" expected_kind="%s"`, si.OSSService.ReferenceResourceName, childInfo.GetSourceMainCatalog().Kind, childEntry.Kind).TagCRN().TagCatalogComposite()76 issues++77 }78 if !catalog.SearchTags(childInfo.GetSourceMainCatalog(), comp.CompositeTag) {79 si.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry of kind=composite has a child object that does not contain the expected composite_tag`, "child=%s expected_tag=%s", childEntry.Name, comp.CompositeTag).TagCRN().TagCatalogComposite()80 childInfo.AddValidationIssue(ossvalidation.SEVERE, `Main Catalog entry is a child of a Composite entry but does not contain the expected composite_tag as specified in the parent`, `parent_name="%s" expected_tag="%s"`, si.OSSService.ReferenceResourceName, comp.CompositeTag).TagCRN().TagCatalogComposite()81 issues++82 }83 if issues == 0 {84 childInfo.AddValidationIssue(ossvalidation.INFO, `Main Catalog entry is a child of a Composite entry -- no issues`, "").TagCRN().TagCatalogComposite()85 }86 }87 } else if base, _ := ParseCompositeName(si.GetSourceMainCatalog().Name); base != "" {88 // Child of a Composite parent89 parent, found := LookupService(MakeComparableName(base), false)90 if !found {91 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent Composite is not found from any sources", `parent="%s"`, base).TagCRN().TagCatalogComposite()92 return93 }94 if !parent.HasSourceMainCatalog() {95 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent Composite is found in some sources but not in the Catalog iself", `parent="%s" sources=%v%v"`, base, parent.OSSValidation.CanonicalNameSources, parent.OSSValidation.OtherNamesSources).TagCRN().TagCatalogComposite()96 return97 }98 if parent.GetSourceMainCatalog().Kind != kindComposite {99 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent is not actually of kind=composite", `parent="%s" parent.kind="%s"`, parent.GetSourceMainCatalog().Name, parent.GetSourceMainCatalog().Kind).TagCRN().TagCatalogComposite()100 return101 }102 comp := parent.GetSourceMainCatalog().ObjectMetaData.Other.Composite103 if comp == nil {104 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent Composite does not contain a ObjectMetaData.Other.Composite section", `parent="%s" parent.kind="%s"`, parent.GetSourceMainCatalog().Name, parent.GetSourceMainCatalog().Kind).TagCRN().TagCatalogComposite()105 return106 }107 var childFound int108 for _, childEntry := range comp.Children {109 // TODO: should we check for fuzzy matches that would be found through the "comparable name" logic even though not an exact match (we do in the other direction, from parent to child...)110 if si.GetSourceMainCatalog().Name == childEntry.Name {111 childFound++112 }113 }114 if childFound == 0 {115 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent Composite does not have a reference to this child", `parent_name="%s" child_name="%s"`, parent.GetSourceMainCatalog().Name, si.GetSourceMainCatalog().Name).TagCRN().TagCatalogComposite()116 if parent.GetSourceMainCatalog().Name != base {117 // If the child was found in the parent, this warning would have been generated from the parent118 si.AddValidationIssue(ossvalidation.SEVERE, "Main Catalog entry looks like a child of a Composite entry but the parent Composite name is not an exact match (and does not contain a reference to this child)", `expected_parent="%s" actual_parent="%s"`, base, parent.GetSourceMainCatalog().Name).TagCRN().TagCatalogComposite()119 }120 } else if childFound > 1 {121 si.AddValidationIssue(ossvalidation.CRITICAL, "Main Catalog entry is a child of a Composite entry but the parent Composite contains more than one child entry with the same name", `parent_name="%s" matches=%d`, parent.GetSourceMainCatalog().Name, childFound).TagCRN().TagCatalogComposite()122 }123 if si.HasSourceRMC() && si.GetSourceRMC().ParentCompositeService.Name != string(parent.ReferenceResourceName) {124 si.AddValidationIssue(ossvalidation.CRITICAL, "Main Catalog entry looks like a child of a Composite entry but the parent does not match the RMC entry", `Catalog_parent="%s" RMC_parent="%s"`, parent.ReferenceResourceName, si.GetSourceRMC().ParentCompositeService.Name).TagCRN().TagCatalogComposite().TagRunAction(ossrunactions.RMC)125 }126 } else if si.HasSourceRMC() && si.GetSourceRMC().ParentCompositeService.Name != "" {127 si.AddValidationIssue(ossvalidation.CRITICAL, "RMC indicates this entry is a child of a Composite entry but entry in the Catalog does not look like a child of Composite", `RMC_parent="%s"`, si.GetSourceRMC().ParentCompositeService.Name).TagCRN().TagCatalogComposite().TagRunAction(ossrunactions.RMC)128 // Force the compositeParent anyway, to set the ParentResourceName field later.129 }130}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...45 return c.Render()46}47// Dashboard - Main-Page after Login48func (c Main) Dashboard() revel.Result {49 c.ViewArgs["devices"] = dao.GetAllDevices(c.getCurrentUserID())50 return c.Render()51}52// Settings - display Settings-Page53func (c Main) Settings() revel.Result {54 user := dao.GetUserWithID(c.getCurrentUserID())55 c.ViewArgs["muser"] = *user56 return c.Render()57}58// UserList - display UserList Page59func (c Main) UserList() revel.Result {60 users := dao.GetAllUsers()61 c.ViewArgs["users"] = *users62 return c.Render()63}64// Oauth - render Oauth-Page65func (c Main) Oauth2() revel.Result {66 c.ViewArgs["action"] = app.ContextRoot + "/oauth2/auth?permissionAccepted=true&" + c.Params.Query.Encode()67 for _, s := range []string{"redirect_uri", "scope", "client_id"} {68 c.ViewArgs[s] = c.Params.Query.Get(s)69 }70 return c.Render()71}72// DeviceList - List all Devices73func (c Main) DeviceList() revel.Result {74 devices := dao.GetAllDevices(c.getCurrentUserID())75 c.ViewArgs["devices"] = devices76 return c.Render()77}78// DeviceNew - Create Device Page79func (c Main) DeviceNew() revel.Result {80 i8nNames := []string{}81 for i := 0; i < alexa.DeviceTypeNum; i++ {82 i8nNames = append(i8nNames, c.Message("alexa.devicetype."+strconv.Itoa(i)))83 }84 c.ViewArgs["devicetype"] = i8nNames85 return c.Render()86}87// CreateDevicePassword ...88func (c Main) CreateDevicePassword() revel.Result {89 user := dao.GetUserWithID(c.getCurrentUserID())90 randompassword := "hallo"91 c.ViewArgs["pass"] = randompassword92 user.DevicePassword, _ = bcrypt.GenerateFromPassword([]byte(randompassword), bcrypt.DefaultCost)93 dao.SaveUser(user)94 return c.Render()95}96func (c Main) DeviceEdit(deviceId uint) revel.Result {97 device := dao.FindDevice(c.getCurrentUserID(), deviceId)98 c.Log.Debug("found device", "device", device)99 if device == nil {100 return c.Redirect(app.ContextRoot + routes.Main.Dashboard())101 }102 logs := dao.GetLogs(deviceId)103 scheds := dao.GetSchedules(deviceId)104 c.ViewArgs["device"] = device105 c.ViewArgs["logs"] = logs106 c.ViewArgs["scheds"] = scheds107 lastTab := c.Flash.Data["activeTab"]108 if lastTab == "" {109 lastTab = "#info"110 }111 c.ViewArgs["activeTab"] = lastTab112 return c.Render()113}114// Actions115// ***********************************116// Login processes a Login117func (c Main) Login(username, password string, remember bool) revel.Result {118 dbUsr := dao.GetUser(username)119 if dbUsr == nil {120 c.Flash.Error("User unbekannt")121 return c.Redirect(app.ContextRoot + routes.Main.Index())122 }123 err := bcrypt.CompareHashAndPassword(dbUsr.Password, []byte(password))124 if err != nil {125 c.Flash.Error("Password false")126 return c.Redirect(app.ContextRoot + routes.Main.Index())127 }128 // Set Session129 c.setSession(strconv.Itoa(int(dbUsr.ID)), dbUsr.UserID)130 return c.Redirect(c.getSuccessfulLoginRedirect())131}132// Logout API133func (c Main) Logout() revel.Result {134 delete(c.Session, "useroid")135 delete(c.Session, "userid")136 return c.Redirect(app.ContextRoot + routes.Main.Index())137}138// UpdateUser updates a User139func (c Main) UpdateUser(user dao.User) revel.Result {140 dbUser := dao.GetUserWithID(c.getCurrentUserID())141 dbUser.Name = user.Name142 dbUser.UserID = c.Session["userid"]143 dao.SaveUser(dbUser)144 return c.Redirect(app.ContextRoot + routes.Main.Dashboard())145}146// UserDel deletes a User147func (c Main) UserDel(id string) revel.Result {148 uid, _ := strconv.Atoi(id)149 user := dao.GetUserWithID(uint(uid))150 dao.DeleteUser(user)151 return c.Redirect(app.ContextRoot + routes.Main.Dashboard())152}153// CreateDevice creates a Device154func (c Main) CreateDevice(device dao.Device) revel.Result {155 device.UserID = c.getCurrentUserID()156 c.Log.Debug("Create Device", "device", device)157 c.Validation.Required(device.Name).Message("Device Name nicht angegeben")158 c.Validation.Required(device.Producer).Message("Hersteller nicht angegeben")159 c.Validation.Required(device.Description).Message("Beschreibung nicht angegeben")160 if !c.Validation.HasErrors() {161 dao.CreateDevice(&device)162 dao.PersistLog(device.ID, "Device Created")163 return c.Redirect(app.ContextRoot + routes.Main.Dashboard())164 } else {165 c.Validation.Keep()166 return c.Redirect(app.ContextRoot + routes.Main.DeviceNew())167 }168}169func (c Main) UpdateDevice(device dao.Device) revel.Result {170 c.Log.Info("UpdateDevice", "device", device)171 dao.PersistLog(device.ID, "Device Updated")172 dbdev := dao.FindDevice(c.getCurrentUserID(), device.ID)173 dbdev.AutoCountDown = device.AutoCountDown174 dbdev.Description = device.Description175 dbdev.Name = device.Name176 dao.SaveDevice(dbdev)177 c.Flash.Out["activeTab"] = "#setting"178 return c.Redirect(app.ContextRoot + routes.Main.DeviceEdit(1))179}180// DeleteDevice deletes a Device181func (c Main) DeleteDevice(id string) revel.Result {182 device := dao.FindDeviceByID(c.getCurrentUserID(), id)183 //TODO: Popup Question184 //TODO: what if device do net exists185 dao.DeleteDevice(device)186 return c.Redirect(app.ContextRoot + routes.Main.DeviceList())187}188// Save Cron Entry189func (c Main) AddSchedule(SchedWeekday, SchedTime, SchedStatus string, SchedDevice uint, SchedOnce bool) revel.Result {190 //TODO: Check if device belongs to user191 c.Log.Info("add schedule: ", "params", c.Params)192 c.Validation.Required(SchedTime)193 sched := dao.CreateSchedule(SchedWeekday, SchedTime, SchedStatus, SchedDevice, SchedOnce)194 c.Log.Info("new Schedule", "sched", sched)195 if sched != nil {196 dao.SaveSchedule(sched)197 } else {198 c.Validation.Error("Fehler beim Speichern")199 }200 if c.Validation.HasErrors() {201 c.Validation.Keep()202 }203 dao.PersistLog(SchedDevice, "new Schedule")204 c.Flash.Out["activeTab"] = "#schedule"205 return c.Redirect(app.ContextRoot + routes.Main.DeviceEdit(1))206}207// Delete Cron Entry208func (c Main) DeleteSchedule(id uint) revel.Result {209 schedule := dao.GetSchedule(id)210 if schedule == nil {211 c.Log.Error("Unable to delete Schedule: not found")212 }213 device := dao.FindDevice(c.getCurrentUserID(), schedule.DeviceID)214 if device != nil {215 dao.DeleteSchedule(schedule)216 } else {217 c.Log.Error("Unable to delete Schedule: no permission")218 }219 dao.PersistLog(device.ID, "delete Schedule")220 c.Flash.Out["activeTab"] = "#schedule"221 return c.Redirect(app.ContextRoot + routes.Main.DeviceEdit(1))222}223func (c Main) getCurrentUserID() uint {224 oid, _ := strconv.Atoi(c.Session["useroid"])225 return uint(oid)226}227// Interception Method gets called on every /main/ Request228func (c Main) genericInterceptor() revel.Result {229 // Set app.ContextRoot if we ar behind a rewritng Proxy230 c.ViewArgs["contextRoot"] = app.ContextRoot231 c.ViewArgs["websocketHost"] = app.WebSocketHost232 c.ViewArgs["version"] = app.AppVersion233 c.ViewArgs["build"] = app.BuildTime234 return nil235}236// Interception Method gets called on every /main/ Request237func (c Main) checkUser() revel.Result {238 // diese Seiten benötigen kein Login239 if c.Action == "Main.Index" ||240 c.Action == "Main.Login" ||241 c.Action == "Main.OAuth2CallBackGoogle" {242 return nil243 }244 // keine useroid -> zurück zur Loginseite245 if c.Session["useroid"] == "" {246 // if the Call is for the Websocket, request must have a basic auth header247 if c.Action == "Main.DeviceFeed" {248 return c.checkWebsocketBasicAuth()249 }250 c.Flash.Error("not logged in")251 // redirect back to intensional site252 c.SetCookie(&http.Cookie{253 Name: REVELREDIRECT,254 Path: "/",255 Value: app.ContextRoot + c.Request.GetRequestURI(),256 Expires: time.Now().Add(time.Duration(5) * time.Minute),257 })258 return c.Redirect(app.ContextRoot + routes.Main.Index())259 }260 c.ViewArgs["user"] = c.Session["userid"]261 return nil262}263// redirect to the site the user want's initially (and would be intercepted by login page)264func (c Main) getSuccessfulLoginRedirect() string {265 // If User wants initially to an other site266 if cookie, err := c.Request.Cookie(REVELREDIRECT); err == nil {267 target := cookie.GetValue()268 // delete cookie269 c.SetCookie(&http.Cookie{270 Name: REVELREDIRECT,271 Expires: time.Now().Add(time.Duration(-5) * time.Minute),272 })273 return target274 }275 // Default after Login276 return app.ContextRoot + routes.Main.Dashboard()277}278// Set the Session Info279func (c Main) setSession(useroid, userid string) {280 c.Session["useroid"] = useroid281 c.Session["userid"] = userid...

Full Screen

Full Screen

builder.go

Source:builder.go Github

copy

Full Screen

...62 var projs = make(map[string]*Project)63 var projKeys []string64 for _, projName := range conf.Keys() {65 var proj *Project66 proj, err = NewProject(projName, builderOpts.NeedUpdate, conf.GetConfig(projName))67 if err != nil {68 return69 }70 if _, exist := projs[projName]; exist {71 if exist {72 err = fmt.Errorf("project: %s already exist", projName)73 return74 }75 }76 projs[projName] = proj77 projKeys = append(projKeys, projName)78 }79 builder = &Builder{80 conf: conf,81 projectsKeys: projKeys,82 projects: projs,83 }84 return85}86func NewProject(projName string, needUpdate bool, conf config.Configuration) (proj *Project, err error) {87 if conf == nil {88 err = fmt.Errorf("could not inital project of %s config because of config is nil", projName)89 return90 }91 fetchers := make(map[string]fetcher.Fetcher)92 fetchersConf := conf.GetConfig("fetchers")93 if fetchersConf == nil {94 err = fmt.Errorf("could not inital project of %s config because of fetchers config is not set", projName)95 return96 }97 for _, fetcherName := range []string{"git", "goget"} {98 var f fetcher.Fetcher99 f, err = fetcher.NewFetcher(100 fetcherName,101 fetchersConf.GetConfig(fetcherName),102 )103 if err != nil {104 return105 }106 fetchers[fetcherName] = f107 }108 proj = &Project{109 Name: projName,110 conf: conf,111 fetchers: fetchers,112 needUpdate: needUpdate,113 }114 return115}116func (p *Project) getFetchRepos() (repos []*fetchRepo, err error) {117 reposConf := p.conf.GetConfig("repos")118 if reposConf == nil {119 return120 }121 var fetchRepos []*fetchRepo122 for _, repoName := range reposConf.Keys() {123 repoConf := reposConf.GetConfig(repoName)124 if repoConf == nil {125 err = fmt.Errorf("repo's config is nil, project: %s, repo: %s", p.Name, repoName)126 return127 }128 url := repoConf.GetString("url")129 if len(url) == 0 {130 err = fmt.Errorf("repo's url is empty, project: %s, repo: %s", p.Name, repoName)131 return132 }133 f, exist := p.fetchers[repoConf.GetString("fetcher", "goget")]134 if !exist {135 err = fmt.Errorf("fetcher %s not exist, project: %s, repo: %s", p.fetchers[repoConf.GetString("fetcher", "goget")], p.Name, repoName)136 return137 }138 revision := repoConf.GetString("revision")139 r := &fetchRepo{140 repoConf: repoConf,141 Url: url,142 Fetcher: f,143 Revision: revision,144 NeedUpdate: p.needUpdate,145 }146 fetchRepos = append(fetchRepos, r)147 }148 repos = fetchRepos149 return150}151func (p *Project) Pull() (err error) {152 repos, err := p.getFetchRepos()153 if err != nil {154 return155 }156 for _, repo := range repos {157 err = repo.Pull()158 if err != nil {159 return160 }161 }162 return163}164func (p *Project) Build() (err error) {165 pkgs := p.conf.GetStringList("packages")166 if len(pkgs) == 0 {167 return168 }169 buf := bytes.NewBuffer(nil)170 for _, pkg := range pkgs {171 buf.WriteString(fmt.Sprintf("import _ \"%s\"\n", pkg))172 }173 cwd, err := os.Getwd()174 if err != nil {175 return176 }177 mainName := fmt.Sprintf("main_spirit_%s.go", p.Name)178 workdir := fmt.Sprintf("%s/%s", os.TempDir(), uuid.New().String())179 err = os.MkdirAll(workdir, 0755)180 if err != nil {181 return182 }183 mainPath := filepath.Join(workdir, mainName)184 mainSrc := strings.Replace(mainTmpl, "##imports##", buf.String(), 1)185 mainSrc = strings.Replace(mainSrc, "##config##", "`"+p.conf.String()+"`", 1)186 mainSrc = strings.Replace(mainSrc, "##Name##", "\""+p.Name+"\"", 1)187 err = ioutil.WriteFile(mainPath, []byte(mainSrc), 0644)188 if err != nil {189 err = fmt.Errorf("write %s failure to temp dir: %s", mainName, err)190 return191 }192 mainSrc = strings.Replace(mainSrc, "\"##revision##\"", "`"+p.revisions(workdir)+"`", 1)193 err = ioutil.WriteFile(mainPath, []byte(mainSrc), 0644)194 if err != nil {195 err = fmt.Errorf("write %s failure to temp dir: %s", mainName, err)196 return197 }198 logrus.WithField("PROJECT", p.Name).Debugln(mainSrc)199 if os.Getenv("GO111MODULE") == "on" {200 copyFile("go.mod", workdir+"/go.mod")201 logrus.WithField("GO111MODULE", "on").Println("go.mod file copied")202 }203 // defer os.Remove(mainPath)204 // go get before build205 appendGetArgs := p.conf.GetStringList("build.args.go-get")206 gogetArgs := []string{"get", "-d"}207 gogetArgs = append(gogetArgs, appendGetArgs...)208 utils.ExecCommandSTDWD("go", workdir, gogetArgs...)209 // go build210 appendBuildArgs := p.conf.GetStringList("build.args.go-build")211 buildArgs := []string{"build"}212 buildArgs = append(buildArgs, appendBuildArgs...)213 targetConf := p.conf.GetConfig("build.target")214 if targetConf.IsEmpty() {215 buildArgs = append(buildArgs, "-o", filepath.Join(cwd, p.Name), mainPath)216 err = utils.ExecCommandSTD("go", nil, buildArgs...)217 if err != nil {218 return219 }220 } else {221 for _, targetOS := range targetConf.Keys() {222 targetArchs := targetConf.GetStringList(targetOS)223 for _, targetArch := range targetArchs {224 envs := []string{"GOOS=" + targetOS, "GOARCH=" + targetArch}225 targetBuildArgs := append(buildArgs, "-o", filepath.Join(cwd, fmt.Sprintf("%s-%s-%s", p.Name, targetOS, targetArch)), mainPath)226 err = utils.ExecCommandSTD("go", envs, targetBuildArgs...)227 if err != nil {228 return229 }230 }231 }232 }233 return234}235type packageRevision struct {236 Package string `json:"package"`237 Branch string `json:"branch"`238 Revision string `json:"revision"`239}240func (p *Project) revisions(wkdir string) string {241 pkgs, _ := utils.GoDeps(wkdir)242 if len(pkgs) == 0 {243 return ""244 }245 var pkgsRevision []packageRevision246 strGOPATH := utils.GoPath()247 gopaths := strings.Split(strGOPATH, ":")248 goroot := utils.GoRoot()249 if len(goroot) > 0 {250 gopaths = append(gopaths, goroot)251 }252 revExists := map[string]bool{}253 for _, pkg := range pkgs {254 _, pkgPath, exist := utils.FindPkgPathByGOPATH(strGOPATH, pkg)255 if !exist {256 logrus.WithField("PACKAGE", pkg).WithField("PROJECT", p.Name).WithField("PKG_PATH", pkgPath).Debugln("Package not found")257 continue258 }259 pkgHash, err := utils.GetCommitSHA(pkgPath)260 if err != nil {261 logrus.WithField("PACKAGE", pkg).WithField("PROJECT", p.Name).WithError(err).WithField("PKG_PATH", pkgPath).Debugln("Get commit sha failure")262 continue263 }264 branchName, err := utils.GetBranchOrTagName(pkgPath)265 if err != nil {266 logrus.WithField("PACKAGE", pkg).WithField("PROJECT", p.Name).WithError(err).WithField("PKG_PATH", pkgPath).Debugln("Get branch or tag name failure")267 }268 if !revExists[pkg] {269 revExists[pkg] = true270 pkgsRevision = append(pkgsRevision, packageRevision{Package: pkg, Revision: pkgHash, Branch: branchName})271 }272 }273 data, _ := json.MarshalIndent(pkgsRevision, "", " ")274 return string(data)275}276func (p *Builder) ListProject() []string {277 var porj []string278 for _, c := range p.projectsKeys {279 porj = append(porj, c)280 }...

Full Screen

Full Screen

main_error.go

Source:main_error.go Github

copy

Full Screen

...27// CreateMainErrorFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value28func CreateMainErrorFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {29 return NewMainError(), nil30}31// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.32func (m *MainError) GetAdditionalData()(map[string]interface{}) {33 if m == nil {34 return nil35 } else {36 return m.additionalData37 }38}39// GetCode gets the code property value. The code property40func (m *MainError) GetCode()(*string) {41 if m == nil {42 return nil43 } else {44 return m.code45 }46}47// GetDetails gets the details property value. The details property48func (m *MainError) GetDetails()([]ErrorDetailsable) {49 if m == nil {50 return nil51 } else {52 return m.details53 }54}55// GetFieldDeserializers the deserialization information for the current model56func (m *MainError) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {57 res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))58 res["code"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {59 val, err := n.GetStringValue()60 if err != nil {61 return err62 }63 if val != nil {64 m.SetCode(val)65 }66 return nil67 }68 res["details"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {69 val, err := n.GetCollectionOfObjectValues(CreateErrorDetailsFromDiscriminatorValue)70 if err != nil {71 return err72 }73 if val != nil {74 res := make([]ErrorDetailsable, len(val))75 for i, v := range val {76 res[i] = v.(ErrorDetailsable)77 }78 m.SetDetails(res)79 }80 return nil81 }82 res["innererror"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {83 val, err := n.GetObjectValue(CreateInnerErrorFromDiscriminatorValue)84 if err != nil {85 return err86 }87 if val != nil {88 m.SetInnererror(val.(InnerErrorable))89 }90 return nil91 }92 res["message"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {93 val, err := n.GetStringValue()94 if err != nil {95 return err96 }97 if val != nil {98 m.SetMessage(val)99 }100 return nil101 }102 res["target"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {103 val, err := n.GetStringValue()104 if err != nil {105 return err106 }107 if val != nil {108 m.SetTarget(val)109 }110 return nil111 }112 return res113}114// GetInnererror gets the innererror property value. The innererror property115func (m *MainError) GetInnererror()(InnerErrorable) {116 if m == nil {117 return nil118 } else {119 return m.innererror120 }121}122// GetMessage gets the message property value. The message property123func (m *MainError) GetMessage()(*string) {124 if m == nil {125 return nil126 } else {127 return m.message128 }129}130// GetTarget gets the target property value. The target property131func (m *MainError) GetTarget()(*string) {132 if m == nil {133 return nil134 } else {135 return m.target136 }137}138// Serialize serializes information the current object139func (m *MainError) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {140 {141 err := writer.WriteStringValue("code", m.GetCode())142 if err != nil {143 return err144 }145 }146 if m.GetDetails() != nil {147 cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDetails()))148 for i, v := range m.GetDetails() {149 cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)150 }151 err := writer.WriteCollectionOfObjectValues("details", cast)152 if err != nil {153 return err154 }155 }156 {157 err := writer.WriteObjectValue("innererror", m.GetInnererror())158 if err != nil {159 return err160 }161 }162 {163 err := writer.WriteStringValue("message", m.GetMessage())164 if err != nil {165 return err166 }167 }168 {169 err := writer.WriteStringValue("target", m.GetTarget())170 if err != nil {171 return err172 }173 }174 {175 err := writer.WriteAdditionalData(m.GetAdditionalData())176 if err != nil {177 return err178 }179 }180 return nil181}182// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.183func (m *MainError) SetAdditionalData(value map[string]interface{})() {184 if m != nil {185 m.additionalData = value186 }187}188// SetCode sets the code property value. The code property189func (m *MainError) SetCode(value *string)() {...

Full Screen

Full Screen

http.go

Source:http.go Github

copy

Full Screen

1package http2import (3 "go-common/app/interface/main/app-resource/conf"4 absvr "go-common/app/interface/main/app-resource/service/abtest"5 auditsvr "go-common/app/interface/main/app-resource/service/audit"6 broadcastsvr "go-common/app/interface/main/app-resource/service/broadcast"7 domainsvr "go-common/app/interface/main/app-resource/service/domain"8 guidesvc "go-common/app/interface/main/app-resource/service/guide"9 modulesvr "go-common/app/interface/main/app-resource/service/module"10 "go-common/app/interface/main/app-resource/service/notice"11 "go-common/app/interface/main/app-resource/service/param"12 pingsvr "go-common/app/interface/main/app-resource/service/ping"13 pluginsvr "go-common/app/interface/main/app-resource/service/plugin"14 showsvr "go-common/app/interface/main/app-resource/service/show"15 sidesvr "go-common/app/interface/main/app-resource/service/sidebar"16 "go-common/app/interface/main/app-resource/service/splash"17 staticsvr "go-common/app/interface/main/app-resource/service/static"18 "go-common/app/interface/main/app-resource/service/version"19 whitesvr "go-common/app/interface/main/app-resource/service/white"20 "go-common/library/log"21 bm "go-common/library/net/http/blademaster"22 "go-common/library/net/http/blademaster/middleware/auth"23)24var (25 // depend service26 authSvc *auth.Auth27 // self service28 pgSvr *pluginsvr.Service29 pingSvr *pingsvr.Service30 sideSvr *sidesvr.Service31 verSvc *version.Service32 paramSvc *param.Service33 ntcSvc *notice.Service34 splashSvc *splash.Service35 auditSvc *auditsvr.Service36 abSvc *absvr.Service37 moduleSvc *modulesvr.Service38 guideSvc *guidesvc.Service39 staticSvc *staticsvr.Service40 domainSvc *domainsvr.Service41 whiteSvc *whitesvr.Service42 showSvc *showsvr.Service43 broadcastSvc *broadcastsvr.Service44)45type Server struct {46 // depend service47 AuthSvc *auth.Auth48 // self service49 PgSvr *pluginsvr.Service50 PingSvr *pingsvr.Service51 SideSvr *sidesvr.Service52 VerSvc *version.Service53 ParamSvc *param.Service54 NtcSvc *notice.Service55 SplashSvc *splash.Service56 AuditSvc *auditsvr.Service57 AbSvc *absvr.Service58 ModuleSvc *modulesvr.Service59 GuideSvc *guidesvc.Service60 StaticSvc *staticsvr.Service61 DomainSvc *domainsvr.Service62 WhiteSvc *whitesvr.Service63 ShowSvc *showsvr.Service64 BroadcastSvc *broadcastsvr.Service65}66// Init is67func Init(c *conf.Config, svr *Server) {68 initService(c, svr)69 // init external router70 engineOut := bm.DefaultServer(c.BM.Outer)71 outerRouter(engineOut)72 // init Outer server73 if err := engineOut.Start(); err != nil {74 log.Error("engineOut.Start() error(%v) | config(%v)", err, c)75 panic(err)76 }77}78// initService init services.79func initService(c *conf.Config, svr *Server) {80 // init self service81 authSvc = svr.AuthSvc82 pgSvr = svr.PgSvr83 pingSvr = svr.PingSvr84 sideSvr = svr.SideSvr85 verSvc = svr.VerSvc86 paramSvc = svr.ParamSvc87 ntcSvc = svr.NtcSvc88 splashSvc = svr.SplashSvc89 auditSvc = svr.AuditSvc90 abSvc = svr.AbSvc91 moduleSvc = svr.ModuleSvc92 guideSvc = svr.GuideSvc93 staticSvc = svr.StaticSvc94 domainSvc = svr.DomainSvc95 broadcastSvc = svr.BroadcastSvc96 whiteSvc = svr.WhiteSvc97 showSvc = svr.ShowSvc98}99// outerRouter init outer router api path.100func outerRouter(e *bm.Engine) {101 e.Ping(ping)102 r := e.Group("/x/resource")103 {104 r.GET("/plugin", plugin)105 r.GET("/sidebar", authSvc.GuestMobile, sidebar)106 r.GET("/topbar", topbar)107 r.GET("/abtest", abTest)108 r.GET("/abtest/v2", abTestV2)109 r.GET("/abtest/abserver", authSvc.GuestMobile, abserver)110 m := r.Group("/module")111 {112 m.POST("", module)113 m.POST("/list", list)114 }115 g := r.Group("/guide", authSvc.GuestMobile)116 {117 g.GET("/interest", interest)118 g.GET("/interest2", interest2)119 }120 r.GET("/static", getStatic)121 r.GET("/domain", domain)122 r.GET("/broadcast/servers", serverList)123 r.GET("/white/list", whiteList)124 r.GET("/show/tab", authSvc.GuestMobile, tabs)125 }126 v := e.Group("/x/v2/version")127 {128 v.GET("", getVersion)129 v.GET("/update", versionUpdate)130 v.GET("/update.pb", versionUpdatePb)131 v.GET("/so", versionSo)132 v.GET("/rn/update", versionRn)133 }134 p := e.Group("/x/v2/param", authSvc.GuestMobile)135 {136 p.GET("", getParam)137 }138 n := e.Group("/x/v2/notice", authSvc.GuestMobile)139 {140 n.GET("", getNotice)141 }142 s := e.Group("/x/v2/splash")143 {144 s.GET("", splashs)145 s.GET("/birthday", birthSplash)146 s.GET("/list", authSvc.GuestMobile, splashList)147 }148 a := e.Group("/x/v2/audit")149 {150 a.GET("", audit)151 }152}...

Full Screen

Full Screen

main_panel.go

Source:main_panel.go Github

copy

Full Screen

1package gui2import (3 "math"4 "github.com/jesseduffield/gocui"5)6func (gui *Gui) scrollUpMain(g *gocui.Gui, v *gocui.View) error {7 mainView := gui.getMainView()8 mainView.Autoscroll = false9 ox, oy := mainView.Origin()10 newOy := int(math.Max(0, float64(oy-gui.Config.UserConfig.Gui.ScrollHeight)))11 return mainView.SetOrigin(ox, newOy)12}13func (gui *Gui) scrollDownMain(g *gocui.Gui, v *gocui.View) error {14 mainView := gui.getMainView()15 mainView.Autoscroll = false16 ox, oy := mainView.Origin()17 reservedLines := 018 if !gui.Config.UserConfig.Gui.ScrollPastBottom {19 _, sizeY := mainView.Size()20 reservedLines = sizeY21 }22 totalLines := mainView.ViewLinesHeight()23 if oy+reservedLines >= totalLines {24 return nil25 }26 return mainView.SetOrigin(ox, oy+gui.Config.UserConfig.Gui.ScrollHeight)27}28func (gui *Gui) scrollLeftMain(g *gocui.Gui, v *gocui.View) error {29 mainView := gui.getMainView()30 ox, oy := mainView.Origin()31 newOx := int(math.Max(0, float64(ox-gui.Config.UserConfig.Gui.ScrollHeight)))32 return mainView.SetOrigin(newOx, oy)33}34func (gui *Gui) scrollRightMain(g *gocui.Gui, v *gocui.View) error {35 mainView := gui.getMainView()36 ox, oy := mainView.Origin()37 content := mainView.ViewBufferLines()38 var largestNumberOfCharacters int39 for _, txt := range content {40 if len(txt) > largestNumberOfCharacters {41 largestNumberOfCharacters = len(txt)42 }43 }44 sizeX, _ := mainView.Size()45 if ox+sizeX >= largestNumberOfCharacters {46 return nil47 }48 return mainView.SetOrigin(ox+gui.Config.UserConfig.Gui.ScrollHeight, oy)49}50func (gui *Gui) autoScrollMain(g *gocui.Gui, v *gocui.View) error {51 gui.getMainView().Autoscroll = true52 return nil53}54func (gui *Gui) onMainTabClick(tabIndex int) error {55 gui.Log.Warn(tabIndex)56 viewName := gui.currentViewName()57 mainView := gui.getMainView()58 if viewName == "main" && mainView.ParentView != nil {59 viewName = mainView.ParentView.Name()60 }61 switch viewName {62 case "project":63 gui.State.Panels.Project.ContextIndex = tabIndex64 return gui.handleProjectSelect(gui.g, gui.getProjectView())65 case "services":66 gui.State.Panels.Services.ContextIndex = tabIndex67 return gui.handleServiceSelect(gui.g, gui.getServicesView())68 case "containers":69 gui.State.Panels.Containers.ContextIndex = tabIndex70 return gui.handleContainerSelect(gui.g, gui.getContainersView())71 case "images":72 gui.State.Panels.Images.ContextIndex = tabIndex73 return gui.handleImageSelect(gui.g, gui.getImagesView())74 case "volumes":75 gui.State.Panels.Volumes.ContextIndex = tabIndex76 return gui.handleVolumeSelect(gui.g, gui.getVolumesView())77 }78 return nil79}80func (gui *Gui) handleEnterMain(g *gocui.Gui, v *gocui.View) error {81 mainView := gui.getMainView()82 mainView.ParentView = v83 return gui.switchFocus(gui.g, v, mainView, false)84}85func (gui *Gui) handleExitMain(g *gocui.Gui, v *gocui.View) error {86 v.ParentView = nil87 return gui.returnFocus(gui.g, v)88}89func (gui *Gui) handleMainClick(g *gocui.Gui, v *gocui.View) error {90 if gui.popupPanelFocused() {91 return nil92 }93 currentView := gui.g.CurrentView()94 if currentView != nil && currentView.Name() == "main" {95 currentView = nil96 } else {97 v.ParentView = currentView98 }99 return gui.switchFocus(gui.g, currentView, v, false)100}...

Full Screen

Full Screen

Context.go

Source:Context.go Github

copy

Full Screen

...11var mainDir string12var mainSkin *skin.Skin13var mainFontManager *util.FontManager14var mainNetworkManager *util.NetworkManager15func GetWindow() *sdl.Window {16 return mainWindow17}18func SetWindow(window *sdl.Window) {19 mainWindow = window20}21func SetSurface(surface *sdl.Surface) {22 mainSurface = surface23}24func GetSurface() *sdl.Surface {25 return mainSurface26}27func SetRenderer(renderer *sdl.Renderer) {28 mainRenderer = renderer29}30func GetRenderer() *sdl.Renderer {31 return mainRenderer32}33func GetRect() *sdl.Rect {34 return mainRect35}36func SetRect(rect *sdl.Rect) {37 mainRect = rect38}39func GetBaseDir() string {40 return mainDir41}42func SetBaseDir(baseDir string) {43 mainDir = baseDir44}45func SetSkin(newSkin *skin.Skin) {46 mainSkin = newSkin47}48func GetSkin() *skin.Skin {49 return mainSkin50}51func SetFontManager(fontManager *util.FontManager) {52 mainFontManager = fontManager53}54func GetFontManager() *util.FontManager {55 return mainFontManager56}57func GetNetworkManager() *util.NetworkManager {58 return mainNetworkManager59}60func SetNetworkManager(manager *util.NetworkManager) {61 mainNetworkManager = manager62}...

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 beego.Run()4}5import (6type MainController struct {7}8func (c *MainController) Get() {

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println(Get())4}5import "fmt"6func main() {7 fmt.Println("Hello World!")8}9import "fmt"10func main() {11 fmt.Println(Get())12}13import "fmt"14func main() {15 fmt.Println("Hello World!")16}17import "fmt"18func main() {19 fmt.Println(Get())20}21import "fmt"22func main() {23 fmt.Println("Hello World!")24}25import "fmt"26func main() {27 fmt.Println(Get())28}29import "fmt"30func main() {31 fmt.Println("Hello World!")32}33import "fmt"34func main() {35 fmt.Println(Get())36}

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, World!")4 go2.Get()5}6import (7func Get() {8 fmt.Println("Hello, World!")9}10import (11func main() {12 fmt.Println("Hello, World!")13 fmt.Println(math.Sqrt(16))14}15import (16func main() {17 fmt.Println("Hello, World!")18 fmt.Println(rand.Intn(100))19}20import (

Full Screen

Full Screen

Get

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(main.Get())4}5import “fmt”6import “fmt”7import “fmt”

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful