Skip to content

Commit 18e61fb

Browse files
authored
chore: dx improvement for code build (#664)
* chore: dx improvement * fix script * fix spec
1 parent fde05c2 commit 18e61fb

File tree

10 files changed

+69
-29
lines changed

10 files changed

+69
-29
lines changed

.codebuild/cleanup_e2e_resources.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,8 @@ env:
88
phases:
99
build:
1010
commands:
11-
- source ./shared-scripts.sh && _cleanupE2EResources
11+
- source ./shared-scripts.sh && _cleanupE2EResources
12+
artifacts:
13+
files:
14+
- '**/*'
15+
base-directory: $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports

.codebuild/cleanup_workflow.yml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,8 @@ phases:
99
build:
1010
commands:
1111
- yarn production-build
12-
- cd packages/amplify-codegen-e2e-tests && yarn clean-e2e-resources
12+
- cd packages/amplify-codegen-e2e-tests && yarn clean-e2e-resources
13+
artifacts:
14+
files:
15+
- '**/*'
16+
base-directory: $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports

.codebuild/run_android_modelgen_e2e_test.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,11 @@ phases:
2525
- source ./shared-scripts.sh && _runE2ETestsLinux
2626
post_build:
2727
commands:
28+
- source ./shared-scripts.sh && _unassumeTestAccountCredentials
2829
- aws sts get-caller-identity
2930
- source ./shared-scripts.sh && _scanArtifacts
3031

3132
artifacts:
3233
files:
33-
- $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports/*
34-
discard-paths: yes
34+
- '**/*'
35+
base-directory: $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports

.codebuild/run_e2e_tests.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ phases:
1616
- source ./shared-scripts.sh && _runE2ETestsLinux
1717
post_build:
1818
commands:
19+
- source ./shared-scripts.sh && _unassumeTestAccountCredentials
1920
- aws sts get-caller-identity
2021
- source ./shared-scripts.sh && _scanArtifacts
2122

2223
artifacts:
2324
files:
24-
- $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports/*
25-
discard-paths: yes
25+
- '**/*'
26+
base-directory: $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports

.codebuild/run_ios_modelgen_e2e_test.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,5 @@ phases:
2828

2929
artifacts:
3030
files:
31-
- $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports/*
32-
discard-paths: yes
31+
- '**/*'
32+
base-directory: $CODEBUILD_SRC_DIR/packages/amplify-codegen-e2e-tests/amplify-e2e-reports

packages/amplify-codegen-e2e-core/src/nexpect-reporter.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,10 @@ class AmplifyCLIExecutionReporter {
6060

6161
onRunComplete(contexts, results) {
6262
const { publicPath = process.cwd(), filename = 'jest_html_reporters.html', logoImgPath } = this._options;
63+
const runIdx = process.env['RUN_INDEX'] ?? '0';
6364
const logoImg = logoImgPath ? imgToBase64(logoImgPath) : undefined;
64-
fs.ensureDirSync(publicPath);
65+
const reportPath = path.join(publicPath, runIdx);
66+
fs.ensureDirSync(reportPath);
6567

6668
const processedResults = results.testResults.map(result => {
6769
const resultCopy = { ...result };
@@ -73,7 +75,7 @@ class AmplifyCLIExecutionReporter {
7375

7476
const recordingWithPath = recordings.map(r => {
7577
const castFile = `${uuid.v4()}.cast`;
76-
const castFilePath = path.join(publicPath, castFile);
78+
const castFilePath = path.join(reportPath, castFile);
7779
fs.writeFileSync(castFilePath, r.recording);
7880
const rCopy = { ...r };
7981
delete rCopy.recording;
@@ -98,7 +100,7 @@ class AmplifyCLIExecutionReporter {
98100
resultsWithRecordings._reporterOptions = { ...this._options, logoImg, customInfos: {} };
99101
const data = JSON.stringify(resultsWithRecordings);
100102

101-
const filePath = path.resolve(publicPath, filename);
103+
const filePath = path.resolve(reportPath, filename);
102104
// const filePathMock = path.resolve(publicPath, `devMock.json`);
103105
// fs.writeFileSync(filePathMock, data);
104106
const htmlTemplate = fs.readFileSync(localTemplatePath, 'utf-8');

packages/amplify-codegen-e2e-tests/src/cleanup-e2e-resources.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const AWS_REGIONS_TO_RUN_TESTS = [
2020
'ap-southeast-2',
2121
];
2222

23-
const reportPath = path.normalize(path.join(__dirname, '..', 'amplify-e2e-reports', 'stale-resources.json'));
23+
const reportPathDir = path.normalize(path.join(__dirname, '..', 'amplify-e2e-reports'));
2424

2525
const MULTI_JOB_APP = '<Amplify App reused by multiple apps>';
2626
const ORPHAN = '<orphan>';
@@ -546,7 +546,8 @@ const deleteCfnStack = async (account: AWSAccountInfo, accountIndex: number, sta
546546
}
547547
};
548548

549-
const generateReport = (jobs: _.Dictionary<ReportEntry>): void => {
549+
const generateReport = (jobs: _.Dictionary<ReportEntry>, accountIdx: number): void => {
550+
const reportPath = path.join(reportPathDir, `stale-resources-${accountIdx}.json`);
550551
fs.ensureFileSync(reportPath);
551552
fs.writeFileSync(reportPath, JSON.stringify(jobs, null, 4));
552553
};
@@ -688,7 +689,7 @@ const cleanupAccount = async (account: AWSAccountInfo, accountIndex: number, fil
688689
const allResources = await mergeResourcesByCCIJob(apps, stacks, buckets, orphanBuckets, orphanIamRoles);
689690
const staleResources = _.pickBy(allResources, filterPredicate);
690691

691-
generateReport(staleResources);
692+
generateReport(staleResources, accountIndex);
692693
await deleteResources(account, accountIndex, staleResources);
693694
console.log(`${generateAccountInfo(account, accountIndex)} Cleanup done!`);
694695
};

scripts/view-test-artifacts.sh

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,43 @@
22

33
source ./scripts/cloud-utils.sh
44

5+
# Function to convert S3 ARN to S3 URI
6+
function convertArnToUri {
7+
local arn="$1"
8+
9+
# Remove "arn:aws:s3:::" from the beginning of the ARN
10+
local stripped_arn="${arn#arn:aws:s3:::}"
11+
12+
# Extract the bucket name and object key
13+
local bucket_name="${stripped_arn%%/*}"
14+
local object_key="${stripped_arn#*/}"
15+
16+
# Create the S3 URI
17+
local s3_uri="s3://$bucket_name/$object_key"
18+
19+
echo "$s3_uri"
20+
}
21+
522
function downloadS3Artifact {
623
# Get temporary access for the account
724
E2E_ROLE_NAME=CodebuildDeveloper
825
E2E_PROFILE_NAME=AmplifyAPIE2EProd
926
authenticate $E2E_ACCOUNT_PROD $E2E_ROLE_NAME "$E2E_PROFILE_NAME"
1027

11-
local s3_object_uri=$1
12-
local destination_dir=$2
28+
echo "Fetching artifact location from build"
29+
s3_arn=$(aws codebuild batch-get-builds --profile="$E2E_PROFILE_NAME" --ids "$1" --region us-east-1 --query 'builds[0].artifacts.location')
30+
# Have to remove double quote for arn
31+
s3_object_uri=$(convertArnToUri ${s3_arn//\"/})
1332

1433
echo "Downloading objects from S3 bucket..."
15-
aws s3 cp "$s3_object_uri" "$destination_dir" --recursive --profile="$E2E_PROFILE_NAME"
16-
echo "Download complete. Files are saved in: $destination_dir"
34+
aws s3 cp $s3_object_uri $2 --recursive --profile="$E2E_PROFILE_NAME"
35+
echo "Download complete. Files are saved in: $2"
1736
}
1837

1938
function playTestArtifact {
2039
# Check if an S3 object URI is provided
2140
if [ $# -eq 0 ]; then
22-
echo "Provide the S3 URI of the artifact: $0 <s3_object_uri>"
41+
echo "Provide the code build id: $0 <code_build_id>"
2342
exit 1
2443
fi
2544

@@ -29,7 +48,7 @@ function playTestArtifact {
2948
trap "cleanup $temp_dir" SIGINT SIGTERM # Register cleanup function to handle Ctrl+C
3049

3150
echo "Starting test artifact playback..."
32-
downloadS3Artifact "$s3_object_uri" "$temp_dir"
51+
downloadS3Artifact "$code_build_id" "$temp_dir"
3352

3453

3554
local subfolders=("$temp_dir"/*/)

scripts/view-test-artifacts.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,8 @@ const downloadSingleTestArtifact = async (tempDir: string, artifact: Required<Te
111111

112112
return Promise.all(
113113
listObjectsResponse.Contents.filter(hasKey).map(({ Key }) => {
114-
const filePath = path.join(artifactDownloadPath, Key.split('/').pop()!);
114+
const filePath = path.join(artifactDownloadPath, Key.split('/').slice(3).join('/'));
115+
fs.ensureDirSync(path.dirname(filePath));
115116
return new Promise((resolve, reject) => {
116117
const writer = fs.createWriteStream(filePath);
117118
s3.getObject({ Bucket, Key }).createReadStream().pipe(writer);

shared-scripts.sh

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,14 @@ function _cleanupE2EResources {
205205
echo "Running clean up script"
206206
build_batch_arn=$(aws codebuild batch-get-builds --ids $CODEBUILD_BUILD_ID | jq -r -c '.builds[0].buildBatchArn')
207207
echo "Cleanup resources for batch build $build_batch_arn"
208-
yarn clean-e2e-resources --buildBatchArn $build_batch_arn
208+
yarn clean-e2e-resources buildBatchArn $build_batch_arn
209+
}
210+
211+
function _unassumeTestAccountCredentials {
212+
echo "Unassume Role"
213+
unset AWS_ACCESS_KEY_ID
214+
unset AWS_SECRET_ACCESS_KEY
215+
unset AWS_SESSION_TOKEN
209216
}
210217

211218
# The following functions are forked from circleci local publish helper
@@ -243,29 +250,29 @@ function retry {
243250
MAX_ATTEMPTS=2
244251
SLEEP_DURATION=5
245252
FIRST_RUN=true
246-
n=0
253+
RUN_INDEX=0
247254
FAILED_TEST_REGEX_FILE="./amplify-e2e-reports/amplify-e2e-failed-test.txt"
248255
if [ -f $FAILED_TEST_REGEX_FILE ]; then
249256
rm -f $FAILED_TEST_REGEX_FILE
250257
fi
251-
until [ $n -ge $MAX_ATTEMPTS ]
258+
until [ $RUN_INDEX -ge $MAX_ATTEMPTS ]
252259
do
253260
echo "Attempting $@ with max retries $MAX_ATTEMPTS"
254261
setAwsAccountCredentials
255-
"$@" && break
256-
n=$[$n+1]
262+
RUN_INDEX="$RUN_INDEX" "$@" && break
263+
RUN_INDEX=$[$RUN_INDEX+1]
257264
FIRST_RUN=false
258-
echo "Attempt $n completed."
265+
echo "Attempt $RUN_INDEX completed."
259266
sleep $SLEEP_DURATION
260267
done
261-
if [ $n -ge $MAX_ATTEMPTS ]; then
268+
if [ $RUN_INDEX -ge $MAX_ATTEMPTS ]; then
262269
echo "failed: ${@}" >&2
263270
exit 1
264271
fi
265272

266273
resetAwsAccountCredentials
267274
TEST_SUITE=${TEST_SUITE:-"TestSuiteNotSet"}
268-
echo "Attempt $n succeeded."
275+
echo "Attempt $RUN_INDEX succeeded."
269276
exit 0 # don't fail the step if putting the metric fails
270277
}
271278

0 commit comments

Comments
 (0)