
Deployment Readiness Check
- 15 installs
- 787 repo stars
- Updated August 5, 2026
- forcedotcom/afv-library
Runs a pre-deployment validation checklist for Salesforce releases to catch metadata issues, test coverage gaps, and configuration errors before production.
About
Provides a comprehensive pre-deployment validation checklist that verifies metadata quality, test coverage, security settings, and configuration before a Salesforce production release. A developer uses it before promoting metadata to production or higher environments.
- Validates metadata completeness, test coverage, and security settings
- Requires Salesforce CLI, jq, and bash on an authenticated org
Deployment Readiness Check by the numbers
- 15 all-time installs (skills.sh)
- Ranked #953 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/forcedotcom/afv-library --skill deployment-readiness-checkAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 15 |
|---|---|
| repo stars | ★ 787 |
| Last updated | August 5, 2026 |
| Repository | forcedotcom/afv-library ↗ |
What it does
Runs a pre-deployment validation checklist for Salesforce releases to catch metadata issues, test coverage gaps, and configuration errors before production.
Files
When to Use This Skill
Use this skill before deploying Salesforce metadata to production (or higher environments) to:
- Validate metadata quality and completeness
- Check test coverage meets organizational standards
- Verify security settings and permissions
- Identify configuration issues before deployment
- Generate deployment documentation
Prerequisites
- Salesforce CLI installed and authenticated to target org
jqcommand-line JSON processor installed- Bash shell (Linux, macOS, or WSL on Windows)
- Source metadata in SFDX project format
Step 1: Run Metadata Validation
Execute the validation script to check for common metadata issues:
bash scripts/check_metadata.shThe script validates:
- Metadata format - Ensures all XML is well-formed
- API versions - Checks for outdated API versions
- Deprecated features - Identifies deprecated components
- Naming conventions - Validates standard naming patterns
- File completeness - Ensures meta.xml files are present
Review the output for any warnings or errors before proceeding.
Step 2: Verify Test Coverage
Check that your Apex test coverage meets organizational standards:
# Run all tests and generate coverage report
sf apex test run --test-level RunLocalTests --result-format human --code-coverage --wait 10
# Check coverage percentage
sf apex get test --test-run-id <test-run-id> --code-coverage --result-format json | jq '.summary.testRunCoverage'Minimum requirements:
- Overall org coverage: ≥75% (Salesforce minimum)
- Individual class coverage: ≥75% (recommended)
- No classes with 0% coverage
If coverage is below threshold: 1. Identify uncovered classes using the coverage report 2. Add test methods to increase coverage 3. Rerun tests until requirements are met
Step 3: Security and Permissions Review
Review security settings and permissions to ensure proper access controls:
1. Profile and Permission Set Review
- Check that custom profiles/permission sets follow least-privilege principle
- Verify admin permissions are not granted to standard users
- Ensure sensitive objects have appropriate FLS
2. Sharing Rules and OWD
- Review Organization-Wide Defaults are appropriate
- Validate sharing rules grant necessary access without over-sharing
- Check for public groups with excessive membership
3. API Access
- Verify Connected Apps have appropriate scopes
- Check Named Credentials use secure authentication
- Review Remote Site Settings are necessary
Consult the security checklist reference for detailed guidance.
Step 4: Configuration Validation
Verify configuration settings are deployment-ready:
# Check for hardcoded URLs or IDs
grep -r "https://.*\.salesforce\.com" force-app/main/default/
grep -r "[a-zA-Z0-9]{15,18}" force-app/main/default/ | grep -v "meta.xml"
# Validate Custom Settings and Custom Metadata
sf project retrieve start --metadata CustomObject:*__cConfiguration checklist:
- [ ] No hardcoded production URLs in code
- [ ] No hardcoded record IDs
- [ ] Custom Settings configured correctly for target org
- [ ] Custom Metadata Types populated appropriately
- [ ] Email templates reference correct org email
- [ ] Reports and Dashboards folders have correct permissions
Step 5: Review Dependencies
Check for dependency conflicts or missing components:
# Generate dependency report
sf project deploy validate --manifest package.xml --test-level RunLocalTests --verbose
# Check for missing dependencies
grep -i "error.*component" deployment_log.txtCommon dependency issues:
- Missing Custom Fields referenced in code
- Validation Rules referencing deleted fields
- Workflows or Process Builders using deprecated actions
- Lightning Components with missing design resources
See dependency troubleshooting guide for solutions.
Step 6: Generate Deployment Checklist
Use the deployment checklist template to document your release:
cp assets/deployment_checklist.md deployment_checklist_$(date +%Y%m%d).mdFill out the checklist with:
- [ ] Deployment date and time window
- [ ] Components being deployed (attach package.xml)
- [ ] Test execution results and coverage
- [ ] Backup verification (data and metadata)
- [ ] Rollback procedure documented
- [ ] Stakeholders notified
- [ ] Post-deployment validation steps
- [ ] Monitoring plan for 24-48 hours
Step 7: Execute Pre-Deployment Validation
Run a validation-only deployment to catch issues before actual deployment:
# Validate deployment without committing
sf project deploy validate \
--manifest package.xml \
--test-level RunLocalTests \
--verbose
# Save the validation ID for quick deploy
sf project deploy start --use-most-recent-validation --asyncBenefits of validation:
- Tests run in production environment
- Identifies environment-specific issues
- Generates Quick Deploy ID for faster deployment
- No changes committed until you confirm
Review validation results and address any failures before scheduling deployment.
Step 8: Prepare Rollback Plan
Document rollback procedures before deploying:
1. Backup current state
sf project retrieve start --manifest package.xml --target-org production
git tag pre-deployment-$(date +%Y%m%d) && git push --tags2. Test rollback procedure in sandbox:
- Deploy previous version of metadata
- Verify functionality is restored
- Document any data cleanup required
3. Establish rollback criteria:
- Critical bugs found within 2 hours
- Core functionality broken
- Performance degradation >50%
- Data integrity issues
See rollback procedures reference for detailed steps.
Post-Deployment Validation
After successful deployment, verify the release:
1. Smoke tests - Execute critical user workflows 2. Monitor logs - Check debug logs for errors (24-48 hours) 3. Query test data - Verify triggers and automation work correctly 4. User acceptance - Confirm with stakeholders functionality works 5. Performance check - Review governor limit usage in logs
Common Issues and Solutions
Issue: Test Coverage Drops Below 75%
Cause: New Apex classes added without sufficient tests.
Solution: 1. Run sf apex test run --code-coverage to identify gaps 2. Add test methods covering uncovered lines 3. Revalidate coverage
Issue: Validation Fails with "Component Not Found"
Cause: Missing dependency in package.xml.
Solution: 1. Review error message for missing component 2. Add component to package.xml 3. Retrieve component from source org if needed 4. Revalidate
Issue: Permission Errors After Deployment
Cause: FLS or object permissions not deployed correctly.
Solution: 1. Verify profiles/permission sets are in package.xml 2. Check that CustomObject metadata includes field permissions 3. Deploy profiles separately if needed 4. Use Permission Set Groups for complex permission hierarchies
Best Practices
1. Always validate before deploying - Never deploy directly to production without validation 2. Run full test suite - Use RunLocalTests, not NoTestRun 3. Deploy during maintenance windows - Minimize impact on users 4. Communicate with stakeholders - Notify before, during, and after deployment 5. Monitor post-deployment - Watch logs and user feedback for 24-48 hours 6. Document everything - Maintain deployment logs and decisions 7. Use version control tags - Tag releases for easy rollback
References
- Security Checklist - Detailed security review steps
- Dependency Resolution Guide - Solve dependency conflicts
- Rollback Procedures - Step-by-step rollback guide
- Deployment Checklist Template - Reusable checklist
Automation Opportunities
Consider automating this skill:
- CI/CD Integration - Run validation script in pipeline
- Scheduled Coverage Checks - Monitor test coverage daily
- Auto-generated Documentation - Create deployment notes from package.xml
- Slack/Email Notifications - Alert team of deployment status
Salesforce Deployment Checklist
Deployment Date: _________________ Deployment Time Window: _________ to _________ Environment: ☐ Production ☐ Sandbox ☐ UAT Deployment Lead: _________________ Release Version: _________________
---
Pre-Deployment
1. Code & Configuration Review
- [ ] All code reviewed and approved via pull request
- [ ] Code follows organizational coding standards
- [ ] No debugging statements or console.logs in production code
- [ ] API versions are current (API 56.0+)
- [ ] Hard-coded IDs/URLs removed (use Custom Settings or Custom Metadata)
- [ ] Comments and documentation are up-to-date
2. Testing
- [ ] All unit tests pass locally
- [ ] Test coverage meets minimum requirements (≥75% org-wide)
- [ ] Integration tests executed successfully
- [ ] User acceptance testing (UAT) completed
- [ ] Regression testing performed for existing features
- [ ] Performance testing validates no degradation
Test Results:
- Total classes: _____
- Test coverage: _____%
- Failed tests: _____
- Test run ID: _________________
3. Security Review
- [ ] Profile/permission set changes reviewed
- [ ] Field-level security validated
- [ ] Sharing rules appropriate for data sensitivity
- [ ] No admin permissions granted to standard users
- [ ] Connected Apps use appropriate OAuth scopes
- [ ] Named Credentials use secure authentication
- [ ] Sensitive data is encrypted or masked
4. Dependencies
- [ ] All metadata dependencies identified
- [ ] Missing components added to package.xml
- [ ] External system dependencies documented
- [ ] API integrations tested in target environment
- [ ] Third-party packages compatible with deployment
5. Backup & Rollback
- [ ] Pre-deployment backup completed
- Metadata backup: ☐ Yes ☐ N/A
- Data backup: ☐ Yes ☐ N/A
- Backup location: _________________
- [ ] Rollback procedure documented and tested
- [ ] Rollback criteria defined
- [ ] Emergency contacts list current
6. Documentation
- [ ] Release notes prepared
- [ ] Deployment guide created
- [ ] User training materials ready (if applicable)
- [ ] Help documentation updated
- [ ] Known issues documented
- [ ] FAQ prepared for support team
7. Communication
- [ ] Stakeholders notified of deployment schedule
- [ ] Users notified of system downtime (if applicable)
- [ ] Support team briefed on changes
- [ ] Change advisory board approval obtained
- [ ] Post-deployment communication template ready
8. Validation
- [ ] Validation deployment successful in production
- [ ] Quick Deploy ID obtained: _________________
- [ ] Validation results reviewed and approved
- [ ] All deployment warnings addressed
Validation Command:
sf project deploy validate --manifest package.xml --test-level RunLocalTests --verbose---
Deployment Execution
9. Pre-Deployment Actions
- [ ] Announced maintenance window to users
- [ ] Disabled scheduled jobs/batch processes (if required)
- Jobs disabled: _________________
- [ ] Created deployment tag in git: _________________
- [ ] Verified target org connectivity
- [ ] Team on standby for deployment
10. Deployment
Deployment Start Time: _________
- [ ] Deployment initiated via validated package or change set
- [ ] Deployment progress monitored
- [ ] Test execution in progress
- [ ] Any deployment errors addressed immediately
Deployment Command:
sf project deploy start --use-most-recent-validation
# OR
sf project deploy start --manifest package.xml --test-level RunLocalTestsDeployment ID: _________________
Deployment End Time: _________
Duration: _________ minutes
11. Post-Deployment Verification
- [ ] Deployment completed successfully
- [ ] All tests passed in production
- [ ] Deployment results reviewed (no warnings/errors)
- [ ] Smoke tests executed successfully
- [ ] Critical user workflows verified:
- [ ] Workflow 1: _________________
- [ ] Workflow 2: _________________
- [ ] Workflow 3: _________________
- [ ] Re-enabled scheduled jobs/batch processes
- [ ] Debug logs show no new errors
12. Post-Deployment Actions
- [ ] Stakeholders notified of successful deployment
- [ ] Users notified system is available
- [ ] Release notes published
- [ ] Support team provided with deployment summary
- [ ] Monitoring dashboard reviewed
---
Post-Deployment Monitoring (24-48 Hours)
13. System Monitoring
- [ ] Day 1 - Monitor debug logs for errors
- Errors found: ☐ Yes ☐ No
- If yes, describe: _________________
- [ ] Day 1 - Review governor limit usage
- Limits exceeded: ☐ Yes ☐ No
- [ ] Day 1 - Check user-reported issues
- Issues reported: ☐ Yes ☐ No
- [ ] Day 2 - Confirm automation working correctly
- [ ] Day 2 - Validate data integrity
- [ ] Day 2 - Review performance metrics
14. User Acceptance
- [ ] Key users confirmed functionality works
- [ ] No critical bugs reported
- [ ] User feedback collected
- [ ] Support tickets categorized by severity
Feedback Summary: _________________
---
Rollback (If Required)
Rollback Decision: ☐ Yes ☐ No
Reason: _________________
- [ ] Stakeholder approval for rollback obtained
- [ ] Users notified of rollback
- [ ] Rollback procedure executed
- [ ] Rollback verified successful
- [ ] Post-rollback communication sent
Rollback Time: _________
---
Deployment Summary
Components Deployed
| Component Type | Count | Examples |
|---|---|---|
| Apex Classes | ||
| Apex Triggers | ||
| LWC | ||
| Flows | ||
| Custom Objects | ||
| Custom Fields | ||
| Profiles | ||
| Perm Sets | ||
| Other |
Total Components: _____
Deployment Metrics
- Validation time: _________ minutes
- Deployment time: _________ minutes
- Test execution time: _________ minutes
- Total elapsed time: _________ minutes
- Downtime (if any): _________ minutes
Issues Encountered
| Issue | Severity | Resolution | Time to Resolve |
|---|---|---|---|
Total Issues: _____
---
Sign-Off
Deployment Team
Deployment Lead: _________________ Date: _________ Developer(s): _________________ Date: _________ QA Lead: _________________ Date: _________ DevOps Engineer: _________________ Date: _________
Stakeholders
Product Owner: _________________ Date: _________ Business Analyst: _________________ Date: _________ Release Manager: _________________ Date: _________
---
Post-Deployment Review
Review Date: _________________
What Went Well
1. _________________ 2. _________________ 3. _________________
What Could Be Improved
1. _________________ 2. _________________ 3. _________________
Action Items
- [ ] Action: _________________ Owner: _________ Due: _________
- [ ] Action: _________________ Owner: _________ Due: _________
- [ ] Action: _________________ Owner: _________ Due: _________
---
Attachments
- [ ] package.xml
- [ ] Test results report
- [ ] Deployment log
- [ ] Release notes
- [ ] Rollback procedure (if executed)
- [ ] Post-deployment monitoring reports
Storage Location: _________________
---
Notes: _________________ _________________ _________________
Rollback Procedures
This guide provides step-by-step instructions for rolling back a Salesforce deployment if issues are discovered after release.
When to Rollback
Execute a rollback when:
- Critical functionality is broken and cannot be hotfixed quickly
- Data integrity issues are discovered
- Performance degradation exceeds 50% of baseline
- Security vulnerabilities are introduced
- Stakeholder approval to rollback is obtained
Do NOT rollback for:
- Minor UI issues that don't impact functionality
- Issues that can be hotfixed in < 2 hours
- Edge cases affecting < 5% of users
- Cosmetic problems
Pre-Rollback Checklist
Before initiating rollback:
- [ ] Confirm the issue severity justifies rollback
- [ ] Obtain stakeholder approval
- [ ] Notify all users of upcoming rollback
- [ ] Backup current production state (post-deployment)
- [ ] Verify pre-deployment backup is available
- [ ] Review rollback plan with team
- [ ] Prepare communication for completion
Rollback Methods
Method 1: Redeploy Previous Version (Recommended)
Best for: Metadata-only deployments with no data changes.
Steps:
1. Retrieve pre-deployment state from version control:
git checkout pre-deployment-YYYYMMDD2. Validate rollback deployment:
sf project deploy validate \
--manifest manifest/package.xml \
--test-level RunLocalTests \
--target-org production3. Deploy previous version:
sf project deploy start \
--manifest manifest/package.xml \
--test-level RunLocalTests \
--target-org production4. Verify rollback:
- Test critical user flows
- Check for errors in debug logs
- Confirm with stakeholders
Timeline: 30-60 minutes
Method 2: Selective Component Rollback
Best for: When only specific components are problematic.
Steps:
1. Identify problematic components:
- Review error logs
- Isolate failing functionality
- List components to rollback
2. Create targeted package.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>ProblematicClass</members>
<name>ApexClass</name>
</types>
<version>59.0</version>
</Package>3. Retrieve previous version of components:
git show pre-deployment-YYYYMMDD:force-app/main/default/classes/ProblematicClass.cls > temp/ProblematicClass.cls4. Deploy only those components:
sf project deploy start \
--manifest rollback-package.xml \
--target-org productionTimeline: 15-30 minutes
Method 3: Destructive Changes
Best for: When new components must be removed entirely.
Steps:
1. Create destructiveChanges.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<types>
<members>NewComponentToDelete</members>
<name>ApexClass</name>
</types>
<version>59.0</version>
</Package>2. Create empty package.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
<version>59.0</version>
</Package>3. Deploy destructive changes:
sf project deploy start \
--manifest package.xml \
--pre-destructive-changes destructiveChanges.xml \
--test-level RunLocalTests \
--target-org production4. Verify deletion:
sf org list metadata --metadata-type ApexClass --target-org productionTimeline: 20-40 minutes
Data Rollback Considerations
If the deployment included data changes:
Option A: Restore from Backup
1. Locate pre-deployment data backup:
- Data Export Service snapshot
- Backup tool (OwnBackup, Spanning, etc.)
- Manual CSV exports
2. Restore data:
sf data import tree --plan data-backup/data-plan.json --target-org production3. Validate data integrity:
- Run data quality checks
- Verify record counts
- Check relationships
Timeline: 1-4 hours (depending on data volume)
Option B: Reverse Data Changes (Scripted)
1. Identify affected records:
sf data query --query "SELECT Id FROM Account WHERE LastModifiedDate >= YESTERDAY"2. Apply reverse operations:
- Create Apex script to reverse changes
- Test in sandbox first
- Execute in production
Timeline: 2-6 hours
Post-Rollback Steps
After rollback is complete:
1. Verify Functionality:
- [ ] Execute smoke tests
- [ ] Confirm critical workflows work
- [ ] Check automation (triggers, flows) operates correctly
- [ ] Review debug logs for errors
2. Communication:
- [ ] Notify users rollback is complete
- [ ] Send post-mortem summary to stakeholders
- [ ] Update status page / internal wiki
3. Root Cause Analysis:
- [ ] Document what went wrong
- [ ] Identify why issues weren't caught pre-deployment
- [ ] Update deployment checklist to prevent recurrence
- [ ] Schedule retrospective with team
4. Next Steps:
- [ ] Fix issues in development environment
- [ ] Add test cases to catch similar issues
- [ ] Re-validate deployment in sandbox
- [ ] Schedule new deployment with fixes
Emergency Contacts
Production Issues:
- On-call DevOps: [contact info]
- Salesforce Support: [premier support phone]
- Release Manager: [contact info]
Stakeholder Notifications:
- Product Owner: [contact info]
- Business Analyst: [contact info]
- Executive Sponsor: [contact info]
Rollback Decision Matrix
| Severity | Impact | Rollback? | Timeline |
|---|---|---|---|
| Critical | >50% users affected, core functionality broken | Yes | Immediate (< 1 hour) |
| High | 10-50% users affected, workaround exists | Consider | Within 2-4 hours |
| Medium | <10% users affected, non-critical features | No, hotfix instead | Plan fix for next release |
| Low | Edge case, cosmetic issues | No | Address in backlog |
Lessons Learned Template
After each rollback, document lessons learned:
# Rollback Post-Mortem: [Date]
## Deployment Summary
- Deployment date/time: [timestamp]
- Components deployed: [list]
- Rollback date/time: [timestamp]
- Rollback method used: [method]
## Issue Description
[Describe what went wrong]
## Root Cause
[Why did the issue occur?]
## Detection
- How was the issue discovered?
- How long after deployment?
- Who reported it?
## Impact
- Number of users affected: [count]
- Business processes impacted: [list]
- Duration of impact: [timespan]
## Resolution
- Rollback timeline: [start - end]
- Additional fixes required: [list]
## Prevention
- What tests would have caught this?
- Process improvements needed:
- Deployment checklist updates:
## Action Items
- [ ] [Action item with owner]
- [ ] [Action item with owner]Best Practices
1. Practice rollbacks in sandbox - Don't wait for an emergency to learn the process 2. Maintain detailed backups - Automate metadata and data backups before every deployment 3. Use version control tags - Tag every production deployment for easy identification 4. Document everything - Keep a deployment log with timestamps and decisions 5. Communicate proactively - Keep stakeholders informed throughout the process 6. Set time limits - If rollback takes >2 hours, consider alternative approaches 7. Test the rollback - Validate in sandbox that the rollback process works
Rollback Scripts Repository
Keep commonly-used rollback scripts in version control:
scripts/rollback/
├── rollback-apex.sh # Rollback Apex classes
├── rollback-lwc.sh # Rollback Lightning Web Components
├── rollback-flows.sh # Rollback flows and processes
├── rollback-data.sh # Restore data from backup
└── verify-rollback.sh # Post-rollback verificationTesting Rollback Procedures
Quarterly rollback drill: 1. Deploy a test change to sandbox 2. Wait 1 hour 3. Execute full rollback procedure 4. Time the process 5. Document any issues 6. Update procedures as needed
This ensures the team is prepared when a real rollback is needed.
#!/bin/bash
# Metadata validation script for Salesforce deployments
# Checks for common issues before deployment
set -e
# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
ERRORS=0
WARNINGS=0
echo "=========================================="
echo "Salesforce Metadata Validation"
echo "=========================================="
echo ""
# Check if we're in an SFDX project
if [ ! -f "sfdx-project.json" ]; then
echo -e "${RED}ERROR: Not in an SFDX project directory${NC}"
echo "Please run this script from your project root"
exit 1
fi
echo "✓ Found SFDX project"
echo ""
# 1. Check XML format
echo "Checking XML format..."
XML_ERRORS=0
find force-app -name "*.xml" -o -name "*.object" -o -name "*.layout" | while read file; do
if ! xmllint --noout "$file" 2>/dev/null; then
echo -e "${RED}✗ Invalid XML: $file${NC}"
XML_ERRORS=$((XML_ERRORS + 1))
fi
done
if [ $XML_ERRORS -eq 0 ]; then
echo -e "${GREEN}✓ All XML files are well-formed${NC}"
else
echo -e "${RED}✗ Found $XML_ERRORS XML errors${NC}"
ERRORS=$((ERRORS + XML_ERRORS))
fi
echo ""
# 2. Check API versions
echo "Checking API versions..."
MIN_API_VERSION=56.0
find force-app -name "*.cls-meta.xml" -o -name "*.trigger-meta.xml" | while read file; do
VERSION=$(grep -o '<apiVersion>[0-9.]*</apiVersion>' "$file" | grep -o '[0-9.]*')
if [ -n "$VERSION" ] && (( $(echo "$VERSION < $MIN_API_VERSION" | bc -l) )); then
echo -e "${YELLOW}⚠ Old API version $VERSION in: $file${NC}"
WARNINGS=$((WARNINGS + 1))
fi
done
echo -e "${GREEN}✓ API version check complete${NC}"
echo ""
# 3. Check for deprecated features
echo "Checking for deprecated features..."
# Check for old-style custom settings
DEPRECATED_SETTINGS=$(find force-app -name "*.object-meta.xml" -exec grep -l "customSettingsType>List" {} \; | wc -l)
if [ $DEPRECATED_SETTINGS -gt 0 ]; then
echo -e "${YELLOW}⚠ Found $DEPRECATED_SETTINGS list custom settings (consider Custom Metadata Types)${NC}"
WARNINGS=$((WARNINGS + 1))
fi
# Check for old Aura components (should migrate to LWC)
AURA_COMPONENTS=$(find force-app -name "*.cmp" | wc -l)
if [ $AURA_COMPONENTS -gt 5 ]; then
echo -e "${YELLOW}⚠ Found $AURA_COMPONENTS Aura components (consider migrating to LWC)${NC}"
WARNINGS=$((WARNINGS + 1))
fi
echo -e "${GREEN}✓ Deprecation check complete${NC}"
echo ""
# 4. Check naming conventions
echo "Checking naming conventions..."
# Check for spaces in API names (not allowed)
SPACE_ERRORS=$(find force-app -name "*.xml" -exec grep -l "fullName>.*\s.*<" {} \; | wc -l)
if [ $SPACE_ERRORS -gt 0 ]; then
echo -e "${RED}✗ Found $SPACE_ERRORS files with spaces in API names${NC}"
ERRORS=$((ERRORS + SPACE_ERRORS))
fi
# Check for lowercase custom object names (should be PascalCase)
LOWERCASE_OBJECTS=$(find force-app/main/default/objects -name "*.object-meta.xml" -exec basename {} \; | grep -E "^[a-z]" | wc -l)
if [ $LOWERCASE_OBJECTS -gt 0 ]; then
echo -e "${YELLOW}⚠ Found $LOWERCASE_OBJECTS custom objects with lowercase names${NC}"
WARNINGS=$((WARNINGS + 1))
fi
echo -e "${GREEN}✓ Naming convention check complete${NC}"
echo ""
# 5. Check for hardcoded IDs or URLs
echo "Checking for hardcoded values..."
# Check for record IDs (15 or 18 character Salesforce IDs)
HARDCODED_IDS=$(grep -r -E "'[a-zA-Z0-9]{15,18}'" force-app/main/default/classes force-app/main/default/triggers 2>/dev/null | wc -l)
if [ $HARDCODED_IDS -gt 0 ]; then
echo -e "${YELLOW}⚠ Found $HARDCODED_IDS potential hardcoded record IDs in Apex${NC}"
echo " Review and replace with custom settings or custom metadata"
WARNINGS=$((WARNINGS + 1))
fi
# Check for hardcoded URLs
HARDCODED_URLS=$(grep -r "https://.*\.salesforce\.com" force-app/main/default/ 2>/dev/null | wc -l)
if [ $HARDCODED_URLS -gt 0 ]; then
echo -e "${YELLOW}⚠ Found $HARDCODED_URLS hardcoded Salesforce URLs${NC}"
echo " Consider using Named Credentials or Custom Settings"
WARNINGS=$((WARNINGS + 1))
fi
echo -e "${GREEN}✓ Hardcoded value check complete${NC}"
echo ""
# 6. Check meta.xml files
echo "Checking for missing meta.xml files..."
MISSING_META=0
find force-app -name "*.cls" | while read file; do
if [ ! -f "${file}-meta.xml" ]; then
echo -e "${RED}✗ Missing meta.xml for: $file${NC}"
MISSING_META=$((MISSING_META + 1))
fi
done
if [ $MISSING_META -eq 0 ]; then
echo -e "${GREEN}✓ All source files have meta.xml files${NC}"
else
echo -e "${RED}✗ Found $MISSING_META missing meta.xml files${NC}"
ERRORS=$((ERRORS + MISSING_META))
fi
echo ""
# 7. Check for test classes
echo "Checking test coverage..."
TOTAL_CLASSES=$(find force-app -name "*.cls" | wc -l)
TEST_CLASSES=$(find force-app -name "*Test.cls" -o -name "*_Test.cls" | wc -l)
if [ $TOTAL_CLASSES -gt 0 ]; then
TEST_RATIO=$(echo "scale=2; $TEST_CLASSES / $TOTAL_CLASSES * 100" | bc)
echo "Test class ratio: $TEST_CLASSES/$TOTAL_CLASSES (${TEST_RATIO}%)"
if (( $(echo "$TEST_RATIO < 50" | bc -l) )); then
echo -e "${YELLOW}⚠ Low test class coverage (${TEST_RATIO}%)${NC}"
echo " Consider adding more test classes"
WARNINGS=$((WARNINGS + 1))
else
echo -e "${GREEN}✓ Good test class coverage (${TEST_RATIO}%)${NC}"
fi
else
echo "No Apex classes found"
fi
echo ""
# 8. Check package.xml
echo "Checking package.xml..."
if [ -f "manifest/package.xml" ]; then
echo -e "${GREEN}✓ Found package.xml${NC}"
# Validate it's well-formed XML
if xmllint --noout manifest/package.xml 2>/dev/null; then
echo -e "${GREEN}✓ package.xml is valid XML${NC}"
else
echo -e "${RED}✗ package.xml is invalid XML${NC}"
ERRORS=$((ERRORS + 1))
fi
else
echo -e "${YELLOW}⚠ No package.xml found in manifest/ directory${NC}"
WARNINGS=$((WARNINGS + 1))
fi
echo ""
# Summary
echo "=========================================="
echo "Validation Summary"
echo "=========================================="
echo -e "Errors: ${RED}$ERRORS${NC}"
echo -e "Warnings: ${YELLOW}$WARNINGS${NC}"
echo ""
if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
echo -e "${GREEN}✓ Metadata validation passed!${NC}"
echo "Your metadata is ready for deployment."
exit 0
elif [ $ERRORS -eq 0 ]; then
echo -e "${YELLOW}⚠ Validation passed with warnings${NC}"
echo "Review warnings before deploying."
exit 0
else
echo -e "${RED}✗ Validation failed${NC}"
echo "Fix errors before deploying."
exit 1
fi