Skip to content

Commit 470d174

Browse files
committed
updates
1 parent 2a63a43 commit 470d174

File tree

2 files changed

+36
-29
lines changed

2 files changed

+36
-29
lines changed

aws_doc_sdk_examples_tools/stats/app.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ class CodeCommitCloneStack extends cdk.Stack {
1616
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
1717
super(scope, id, props);
1818

19-
// Initialize Lambda function
19+
// Create Lambda function
2020
const cloneLambda = this.initCloneLambda();
2121

22-
// Set up EventBridge rule to trigger Lambda on CodeCommit repository changes
22+
// Create EventBridge rule to trigger Lambda on CodeCommit repository changes
2323
this.initCodeCommitTrigger(cloneLambda);
2424
}
2525

@@ -47,19 +47,19 @@ class CodeCommitCloneStack extends cdk.Stack {
4747
})
4848
);
4949

50-
// Grant necessary permissions to S3 bucket "codeexamplestats" for Get and Put
50+
// Grant necessary permissions to S3 bucket "codeexamplestats" for Get/Put
5151
lambdaExecutionRole.addToPolicy(
5252
new iam.PolicyStatement({
5353
actions: ["s3:GetObject", "s3:PutObject"],
54-
resources: [`arn:aws:s3:::codeexamplestats/*`], // Allow access to all objects in the bucket
54+
resources: [`arn:aws:s3:::codeexamplestats/*`], // Allow all objects in the bucket
5555
})
5656
);
5757

58-
// Define the Lambda function, pointing directly to the source code directory
58+
// Define the Lambda function, pointing directly to the source code dir
5959
const cloneLambda = new lambda.Function(this, "CodeCommitCloneLambda", {
6060
runtime: lambda.Runtime.PYTHON_3_9,
6161
handler: "index.lambda_handler",
62-
code: lambda.Code.fromAsset(path.join(__dirname, "lambda")), // Pointing to the directory of the lambda function code
62+
code: lambda.Code.fromAsset(path.join(__dirname, "lambda")),
6363
environment: {
6464
REPO_NAME: repoName,
6565
},
@@ -71,7 +71,7 @@ class CodeCommitCloneStack extends cdk.Stack {
7171
}
7272

7373
private initCodeCommitTrigger(cloneLambda: lambda.Function): void {
74-
// Create EventBridge rule for CodeCommit repository updates
74+
// EventBridge rule for CodeCommit repo updates
7575
const codeCommitRule = new events.Rule(this, "CodeCommitUpdateRule", {
7676
eventPattern: {
7777
source: ["aws.codecommit"],
@@ -87,7 +87,7 @@ class CodeCommitCloneStack extends cdk.Stack {
8787
}
8888
});
8989

90-
// Add Lambda function as the target of the EventBridge rule
90+
// Add Lambda function as target of the EventBridge rule
9191
codeCommitRule.addTarget(new targets.LambdaFunction(cloneLambda));
9292
}
9393
}
@@ -96,7 +96,7 @@ const app = new cdk.App();
9696
new CodeCommitCloneStack(app, "CodeCommitCloneStack", {
9797
env: {
9898
account: process.env.CDK_DEFAULT_ACCOUNT,
99-
region: "us-west-2", // Where codecommit is stored
99+
region: "us-west-2", // Where codecommit is stored (internal requirement)
100100
},
101101
});
102102
app.synth();

aws_doc_sdk_examples_tools/stats/lambda/index.py

Lines changed: 27 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@
66
import csv
77
from datetime import datetime # Import datetime module
88

9+
910
def lambda_handler(event, context):
1011
# Initialize boto3 clients
1112
codecommit = boto3.client("codecommit", region_name=os.environ["AWS_REGION"])
1213
s3 = boto3.client("s3")
13-
14+
1415
# Environment variables
1516
repo_name = os.environ.get("REPO_NAME")
1617
branch_name = os.environ.get("BRANCH_NAME", "mainline") # Default to "mainline"
@@ -21,39 +22,41 @@ def lambda_handler(event, context):
2122
# Step 1: Retrieve the .stats file content directly from CodeCommit
2223
file_response = codecommit.get_file(
2324
repositoryName=repo_name,
24-
filePath='.stats', # Specify the path to the .stats file
25-
commitSpecifier=branch_name
25+
filePath=".stats", # Specify the path to the .stats file
26+
commitSpecifier=branch_name,
2627
)
27-
28+
2829
# Convert .stats content to valid JSON if necessary
29-
file_content = file_response['fileContent'].decode("utf-8")
30+
file_content = file_response["fileContent"].decode("utf-8")
3031
try:
3132
stats_data = json.loads(file_content) # Valid JSON parsing
3233
except json.JSONDecodeError:
33-
file_content = file_content.replace("'", "\"") # Replace single quotes
34+
file_content = file_content.replace("'", '"') # Replace single quotes
3435
stats_data = json.loads(file_content)
35-
36+
3637
# Step 2: Fetch the current stats.csv file from S3
3738
existing_rows = []
3839
try:
3940
csv_obj = s3.get_object(Bucket=bucket_name, Key=csv_file_key)
40-
csv_data = csv_obj['Body'].read().decode('utf-8')
41+
csv_data = csv_obj["Body"].read().decode("utf-8")
4142
csv_reader = csv.DictReader(StringIO(csv_data))
4243
existing_rows = list(csv_reader)
4344
except s3.exceptions.NoSuchKey:
4445
existing_rows = []
4546

4647
# Step 3: Append the new data from .stats file with a formatted timestamp
4748
new_row = {
48-
'sdks': stats_data['sdks'],
49-
'services': stats_data['services'],
50-
'examples': stats_data['examples'],
51-
'versions': stats_data['versions'],
52-
'snippets': stats_data['snippets'],
53-
'genai_none': stats_data['genai']['none'],
54-
'genai_some': stats_data['genai']['some'],
55-
'genai_most': stats_data['genai']['most'],
56-
'timestamp': datetime.now().strftime("%d/%m/%Y %H:%M:%S") # Formatted timestamp
49+
"sdks": stats_data["sdks"],
50+
"services": stats_data["services"],
51+
"examples": stats_data["examples"],
52+
"versions": stats_data["versions"],
53+
"snippets": stats_data["snippets"],
54+
"genai_none": stats_data["genai"]["none"],
55+
"genai_some": stats_data["genai"]["some"],
56+
"genai_most": stats_data["genai"]["most"],
57+
"timestamp": datetime.now().strftime(
58+
"%d/%m/%Y %H:%M:%S"
59+
), # Formatted timestamp
5760
}
5861
existing_rows.append(new_row)
5962

@@ -63,10 +66,14 @@ def lambda_handler(event, context):
6366
writer = csv.DictWriter(output, fieldnames=new_row.keys())
6467
writer.writeheader() # Ensure we have headers
6568
writer.writerows(existing_rows)
66-
s3.put_object(Bucket=bucket_name, Key=csv_file_key, Body=output.getvalue().encode('utf-8'))
67-
69+
s3.put_object(
70+
Bucket=bucket_name,
71+
Key=csv_file_key,
72+
Body=output.getvalue().encode("utf-8"),
73+
)
74+
6875
print("Successfully updated stats.csv in S3 with new .stats data.")
69-
76+
7077
except Exception as e:
7178
print(f"Error occurred: {e}")
7279
return {"statusCode": 500, "body": "Failed to update stats.csv."}

0 commit comments

Comments
 (0)