Skip to content

Commit

Permalink
Merge pull request #9 from vaidik/output-params
Browse files Browse the repository at this point in the history
Output params
  • Loading branch information
vaidik authored Jun 7, 2023
2 parents 4b6a918 + 24a33ba commit 0765d09
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 46 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/semgrep.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Name of this GitHub Actions workflow.
name: Semgrep

on:
# Scan changed files in PRs (diff-aware scanning):
pull_request: {}
# Scan on-demand through GitHub Actions interface:
workflow_dispatch: {}
# Scan mainline branches and report all findings:
push:
branches: ["master", "main"]
# Schedule the CI job (this method uses cron syntax):
schedule:
- cron: '20 17 * * *' # Sets Semgrep to scan every day at 17:20 UTC.
# It is recommended to change the schedule to a random time.

jobs:
semgrep:
# User definable name of this GitHub Actions job.
name: semgrep/ci
# If you are self-hosting, change the following `runs-on` value:
runs-on: ubuntu-latest

container:
# A Docker image with Semgrep installed. Do not change this.
image: returntocorp/semgrep

# Skip any PR created by dependabot to avoid permission issues:
if: (github.actor != 'dependabot[bot]')

steps:
# Fetch project source with GitHub Actions Checkout.
- uses: actions/checkout@v3
# Run the "semgrep ci" command on the command line of the docker image.
- run: semgrep ci
env:
# Connect to Semgrep Cloud Platform through your SEMGREP_APP_TOKEN.
# Generate a token from Semgrep Cloud Platform > Settings
# and add it to your GitHub secrets.
SEMGREP_APP_TOKEN: ${{ secrets.SEMGREP_APP_TOKEN }}
11 changes: 10 additions & 1 deletion example.config.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
{
"tagManagerAPI": {
"defaultRateLimitBatchSize": 1,
"defaultRateLimitBatchDelay": 5000
},
"accounts": [
{
"alias": "account-1",
"accountId": "123456789",
"containerId": "123456789",
"workspaceId": "2",
"isResettable": false
"isResettable": false,
"variableOverrides": {
"<Variable 1: Name>": "<Variable 1: Value>",
"<Variable 2: Name>": "<Variable 2: Value>",
"<Variable 3: Name>": "<Variable 3: Value>"
}
}
]
}
40 changes: 34 additions & 6 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ import {
IsOptional,
IsNumber,
IsPositive,
MinLength,
} from 'class-validator';

class AccountConfig {
abstract class AbstractConfig {
fixTypes() {}
}

class AccountConfig extends AbstractConfig {
@IsString()
alias: string;

Expand All @@ -27,20 +32,35 @@ class AccountConfig {
@IsOptional()
isResettable?: boolean;

@IsOptional()
@MinLength(1, {each: true})
variableOverrides: Map<string, string> | undefined;

constructor(
alias: string,
accountId: string,
containerId: string,
workspaceId: string
) {
super();
this.alias = alias;
this.accountId = accountId;
this.containerId = containerId;
this.workspaceId = workspaceId;
}

fixTypes(): void {
if (this.variableOverrides) {
const obj = new Map<string, string>();
for (const [key, val] of Object.entries(this.variableOverrides ?? {})) {
obj.set(key, val);
}
this.variableOverrides = obj;
}
}
}

class TagManagerAPIConfig {
class TagManagerAPIConfig extends AbstractConfig {
@IsNumber()
@IsPositive()
defaultRateLimitBatchSize: number;
Expand All @@ -53,12 +73,13 @@ class TagManagerAPIConfig {
defaultRateLimitBatchSize = 5, // 15 requests per minute
defaultRateLimitBatchDelay = 15000 // 15 seconds
) {
super();
this.defaultRateLimitBatchSize = defaultRateLimitBatchSize;
this.defaultRateLimitBatchDelay = defaultRateLimitBatchDelay;
}
}

export class Config {
export class Config extends AbstractConfig {
private static instance: Config;

@ValidateNested()
Expand All @@ -70,6 +91,7 @@ export class Config {
accounts?: AccountConfig[];

constructor(tagManagerAPI?: TagManagerAPIConfig, accounts?: AccountConfig[]) {
super();
if (tagManagerAPI === undefined) {
this.tagManagerAPI = new TagManagerAPIConfig();
} else {
Expand All @@ -84,13 +106,19 @@ export class Config {
Config.instance = this;
}

getAccount(alias: string): AccountConfig | undefined {
fixTypes() {
this.accounts?.forEach((account: AccountConfig) => {
account?.fixTypes();
});
}

getAccount(aliasOrId: string): AccountConfig | undefined {
const matchedAccounts = this.accounts?.filter(
account => account.alias === alias
account => account.alias === aliasOrId || account.accountId === aliasOrId
);
if (matchedAccounts?.length === 0) {
throw new Error(
`Could not find an account by the alias ${alias} in the config.`
`Could not find an account by alias or ID ${aliasOrId} in the config.`
);
}
return matchedAccounts ? matchedAccounts[0] : undefined;
Expand Down
24 changes: 6 additions & 18 deletions src/copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,6 @@ copy_cmd.action(async () => {
'Name',
'Type',
'👉 Copy Status',
'👉 Reason',
'✨ New Variable ID',
],
});
Expand All @@ -170,11 +169,8 @@ copy_cmd.action(async () => {
sourceVariable?.name as string,
sourceVariable?.type as string,
val.response.error === undefined
? 'Copy Successful'
: 'Copy Failed',
val.response.error !== undefined
? val.response.error?.message
: '',
? '✅ Copy Successful'
: `❌ Copy Failed \n\n${val.response.error?.message ?? ''}`,
val.targetVariableId === undefined ? '' : val.targetVariableId,
]);
});
Expand All @@ -191,7 +187,6 @@ copy_cmd.action(async () => {
'Name',
'Type',
'👉 Copy Status',
'👉 Reason',
'✨New Trigger ID',
],
});
Expand All @@ -204,11 +199,8 @@ copy_cmd.action(async () => {
sourceTrigger?.name as string,
sourceTrigger?.type as string,
val.response.error === undefined
? 'Copy Successful'
: 'Copy Failed',
val.response.error !== undefined
? val.response.error?.message
: '',
? '✅ Copy Successful'
: `❌ Copy Failed \n\n${val.response.error?.message ?? ''}`,
val.targetTriggerId === undefined ? '' : val.targetTriggerId,
]);
});
Expand All @@ -226,7 +218,6 @@ copy_cmd.action(async () => {
'Type',
'Firing Triggers (Trigger ID)',
'👉 Copy Status',
'👉 Reason',
'✨ New Tag ID',
'✨ New Firing Triggers (New Trigger ID)',
],
Expand All @@ -246,11 +237,8 @@ copy_cmd.action(async () => {
)
.join(', ') ?? '') as string,
val.response.error === undefined
? 'Copy Successful'
: 'Copy Failed',
val.response.error !== undefined
? val.response.error?.message
: '',
? '✅ Copy Successful'
: `❌ Copy Failed \n\n${val.response.error?.message ?? ''}`,
val.targetTagId === undefined ? '' : val.targetTagId,
(targetAccount.tags
.get(val.targetTagId)
Expand Down
35 changes: 23 additions & 12 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,17 @@ export class TagManagerData {
delete requestBody.fingerprint;
requestBody.formatValue;

if (requestBody.type === 'c') {
const varOverride: string | undefined = this.config
.getAccount(this.accountId)
?.variableOverrides?.get(val.name as string);
requestBody.parameter?.forEach(val => {
if (val.key === 'value') {
val.value = varOverride ?? val.value;
}
});
}

try {
const res =
this.gtmClient.accounts.containers.workspaces.variables.create({
Expand Down Expand Up @@ -362,6 +373,18 @@ export class TagManagerData {
responses.tags.push(response);
}, tags);

await this.batchPromise(async (val: tagmanager_v2.Schema$Trigger) => {
console.log(
`==> Deleting trigger - Trigger ID: ${val.triggerId}, Trigger Name: ${val.name}`
.grey
);
const response =
await this.gtmClient.accounts.containers.workspaces.triggers.delete({
path: `${this.parent}/triggers/${val.triggerId}`,
});
responses.triggers.push(response);
}, triggers);

// First delete variables of type `jsm` because they could have
// other variables that depend on them. So the variables that other
// variables depend on cannot be deleted unless the dependent variables
Expand Down Expand Up @@ -399,18 +422,6 @@ export class TagManagerData {
},
variables.filter(variable => variable.type !== 'jsm')
);

await this.batchPromise(async (val: tagmanager_v2.Schema$Trigger) => {
console.log(
`==> Deleting trigger - Trigger ID: ${val.triggerId}, Trigger Name: ${val.name}`
.grey
);
const response =
await this.gtmClient.accounts.containers.workspaces.triggers.delete({
path: `${this.parent}/triggers/${val.triggerId}`,
});
responses.triggers.push(response);
}, triggers);
} catch (e) {
console.log(e);
}
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ cli.hook('preAction', async () => {
})
);
const configObj = plainToClass(Config, configRaw as Object);
configObj.fixTypes();

await validate(configObj, {forbidUnknownValues: false}).then(errors => {
if (errors.length > 0) {
Expand Down
28 changes: 19 additions & 9 deletions src/list.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {Command, Option} from 'commander';
import Table from 'cli-table';
import colors from 'colors';
import yaml from 'yaml';
import {TagManagerData, validateSingleAccountOpts} from './core.js';
import {Config} from './config.js';

Expand All @@ -11,13 +12,14 @@ async function list(account: TagManagerData) {

// Variables
const variablesTable = new Table({
head: ['Variable ID', 'Name', 'Type'],
head: ['Name', 'Variable ID', 'Type', 'Parameters'],
});
account.variables.forEach(val => {
account.variables.forEach(variable => {
variablesTable.push([
val.variableId as string,
val.name as string,
val.type as string,
variable.name as string,
variable.variableId as string,
variable.type as string,
yaml.stringify(variable?.parameter) ?? '',
]);
});
console.log('==> Variables'.blue, `(${account.variables.size} variables)`);
Expand All @@ -26,13 +28,14 @@ async function list(account: TagManagerData) {

// Triggers
const triggersTable = new Table({
head: ['Trigger ID', 'Name', 'Type'],
head: ['Name', 'Trigger ID', 'Type', 'Custom Event Filter'],
});
account.triggers?.forEach(trigger => {
triggersTable.push([
trigger.triggerId as string,
trigger.name as string,
trigger.triggerId as string,
trigger.type as string,
yaml.stringify(trigger?.customEventFilter) ?? '',
]);
});
console.log('==> Triggers'.blue, `(${account.triggers.size} triggers)`);
Expand All @@ -41,12 +44,18 @@ async function list(account: TagManagerData) {

// Tags
const tagsTable = new Table({
head: ['Tag ID', 'Name', 'Type', 'Firing Triggers (Trigger ID)'],
head: [
'Name',
'Tag ID',
'Type',
'Firing Triggers (Trigger ID)',
'Parameters',
],
});
account.tags?.forEach(tag => {
tagsTable.push([
tag.tagId as string,
tag.name as string,
tag.tagId as string,
tag.type as string,
(tag.firingTriggerId
?.map(
Expand All @@ -56,6 +65,7 @@ async function list(account: TagManagerData) {
})`
)
.join(', ') ?? '') as string,
yaml.stringify(tag?.parameter) ?? '',
]);
});
console.log('==> Tags'.blue, `(${account.tags.size} tags)`);
Expand Down

0 comments on commit 0765d09

Please sign in to comment.