From 6568eeccfdb0b4735cf70cff486113b16db14efd Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Tue, 3 Feb 2026 15:47:47 +0000 Subject: [PATCH 1/2] Another commit --- lib/extreme_issues.dart | 473 ++++++++++++++++++++++++++++++++++++++++ lib/main.dart | 277 ++++++++++++++++++++++- 2 files changed, 739 insertions(+), 11 deletions(-) create mode 100644 lib/extreme_issues.dart diff --git a/lib/extreme_issues.dart b/lib/extreme_issues.dart new file mode 100644 index 0000000..3bb81fc --- /dev/null +++ b/lib/extreme_issues.dart @@ -0,0 +1,473 @@ +// File with extreme code quality issues for advanced Codacy testing +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; +import 'dart:async'; +import 'dart:collection'; +import 'dart:developer'; +import 'dart:isolate'; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/physics.dart'; +import 'package:flutter/animation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter/cupertino.dart'; +// All imports above are unused - extreme issue + +// Global variables with security issues +var MASTER_PASSWORD = 'master_password_123'; +var ROOT_ACCESS_TOKEN = 'root_token_xyz_789'; +var DATABASE_CONNECTION_STRING = 'postgresql://admin:password123@prod-db.company.com:5432/main_db'; +var STRIPE_SECRET_KEY = 'sk_live_stripe_secret_key_abcdef123456789'; +var AWS_ACCESS_KEY = 'AKIAIOSFODNN7EXAMPLE'; +var AWS_SECRET_KEY = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY'; +var GOOGLE_MAPS_API_KEY = 'AIzaSyGoogle_Maps_API_Key_Example_123456789'; +var FACEBOOK_APP_SECRET = 'facebook_app_secret_example_123456789'; +var TWITTER_CONSUMER_SECRET = 'twitter_consumer_secret_example_123456789'; +var GITHUB_TOKEN = 'ghp_github_personal_access_token_example_123456789'; + +// Class with extreme issues +class ExtremeIssuesClass { + // Massive amounts of unused private fields + String _unusedField1 = 'unused1'; + String _unusedField2 = 'unused2'; + String _unusedField3 = 'unused3'; + String _unusedField4 = 'unused4'; + String _unusedField5 = 'unused5'; + int _unusedInt1 = 0; + int _unusedInt2 = 0; + int _unusedInt3 = 0; + bool _unusedBool1 = false; + bool _unusedBool2 = false; + DateTime _unusedDateTime1 = DateTime.now(); + DateTime _unusedDateTime2 = DateTime.now(); + List _unusedList1 = []; + List _unusedList2 = []; + Map _unusedMap1 = {}; + Map _unusedMap2 = {}; + + // Security issues - hardcoded secrets as fields + final String _adminPassword = 'admin_super_secret_password_456'; + final String _encryptionKey = 'encryption_master_key_789'; + final String _jwtSecret = 'jwt_signing_secret_abc123def456'; + final String _databasePassword = 'database_root_password_xyz789'; + final String _apiMasterKey = 'api_master_key_qwerty123456789'; + + // Constructor with unused parameters + ExtremeIssuesClass(String param1, int param2, bool param3, dynamic param4) { + // All parameters unused + // Logging secrets in constructor + print('Admin password: $_adminPassword'); + print('Encryption key: $_encryptionKey'); + print('JWT secret: $_jwtSecret'); + print('Database password: $_databasePassword'); + print('API master key: $_apiMasterKey'); + } + + // Method with extreme complexity and cyclomatic complexity + processExtremeLogic(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t) { + // Missing all type annotations and return type + // Excessive cyclomatic complexity with deep nesting + var result = 0; + + // Massive amounts of unused variables + var temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10; + var flag1, flag2, flag3, flag4, flag5, flag6, flag7, flag8, flag9, flag10; + var counter1, counter2, counter3, counter4, counter5; + var list1, list2, list3, list4, list5; + var map1, map2, map3, map4, map5; + var string1, string2, string3, string4, string5; + var bool1, bool2, bool3, bool4, bool5; + var double1, double2, double3, double4, double5; + var datetime1, datetime2, datetime3, datetime4, datetime5; + + // Security issues within the method + var methodSecret1 = 'method_secret_123'; + var methodSecret2 = 'method_secret_456'; + var methodApiKey = 'method_api_key_789'; + var methodToken = 'method_token_abc'; + + print('Method secret 1: $methodSecret1'); + print('Method secret 2: $methodSecret2'); + print('Method API key: $methodApiKey'); + print('Method token: $methodToken'); + + // Extreme nested conditions + if (a != null) { + if (b != null) { + if (c != null) { + if (d != null) { + if (e != null) { + if (f != null) { + if (g != null) { + if (h != null) { + if (i != null) { + if (j != null) { + if (k != null) { + if (l != null) { + if (m != null) { + if (n != null) { + if (o != null) { + if (p != null) { + if (q != null) { + if (r != null) { + if (s != null) { + if (t != null) { + // 20 levels deep! + result = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t; + + // More nested conditions within the deep nesting + if (result > 0) { + if (result < 100) { + if (result % 2 == 0) { + if (result > 10) { + if (result < 90) { + // Even deeper nesting! + print('Deep nested result: $result'); + + // Security issue in deep nesting + var deepSecret = 'deep_nested_secret_xyz'; + print('Deep secret: $deepSecret'); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + + return result; + } + + // Method with SQL injection vulnerability + String unsafeQueryBuilder(String userInput) { + // No input sanitization - SQL injection vulnerability + var query = 'SELECT * FROM users WHERE name = \'$userInput\''; + print('Executing query: $query'); // Logging potentially dangerous query + + // Hardcoded database credentials + var dbHost = 'prod-database.company.com'; + var dbUser = 'root'; + var dbPass = 'root_password_123456'; + + print('Connecting to $dbHost with user $dbUser and password $dbPass'); + + return query; + } + + // Method with command injection vulnerability + String executeSystemCommand(String userInput) { + // Command injection vulnerability + var command = 'ls -la $userInput'; + print('Executing command: $command'); // Logging dangerous command + + // Simulated system call (would be dangerous if real) + return 'Command executed'; + } + + // Method with path traversal vulnerability + String readUserFile(String fileName) { + // Path traversal vulnerability + var filePath = '/app/user_files/$fileName'; + print('Reading file: $filePath'); // Could expose sensitive paths + + // Hardcoded sensitive paths + var configPath = '/etc/passwd'; + var secretPath = '/app/secrets/api_keys.txt'; + var databasePath = '/var/lib/mysql/data'; + + print('Config path: $configPath'); + print('Secret path: $secretPath'); + print('Database path: $databasePath'); + + return 'File content'; + } + + // Dead code - never called + void _deadMethod1() { + print('This method is never called'); + var deadSecret = 'dead_secret_123'; + print('Dead secret: $deadSecret'); + } + + void _deadMethod2() { + print('Another dead method'); + var anotherDeadSecret = 'another_dead_secret_456'; + print('Another dead secret: $anotherDeadSecret'); + } + + String _deadMethod3(String input) { + print('Dead method with return value'); + return input.toUpperCase(); + } + + // Method with poor exception handling + dynamic riskyOperation(dynamic data) { + // No try-catch, potential runtime errors + print('Processing: $data'); + + // Unsafe operations that could throw + var length = data.length; + var firstChar = data[0]; + var lastChar = data[length - 1]; + var upperCase = data.toString().toUpperCase(); + var number = int.parse(data); + var divided = 100 / number; + + print('Length: $length, First: $firstChar, Last: $lastChar'); + print('Upper: $upperCase, Number: $number, Divided: $divided'); + + return divided; + } + + // Method with infinite loop potential + void potentialInfiniteLoop(int input) { + var counter = 0; + + // Dangerous loop without proper exit condition + while (input > 0) { + counter++; + print('Counter: $counter'); + + // Could cause infinite loop if input is always > 0 + if (input % 2 == 0) { + input = input + 1; // Makes it odd + } else { + input = input - 1; // Makes it even, but then gets incremented above + } + + // No max iteration check - could run forever + } + } + + // Method with memory leak potential + void memoryLeakPotential() { + // Creating large objects without cleanup + var largeList = []; + var largeMap = >{}; + + for (int i = 0; i < 100000; i++) { + largeList.add('Large string data $i' * 1000); + largeMap['key$i'] = List.generate(1000, (index) => 'data$index'); + } + + // No cleanup, objects remain in memory + print('Created large data structures'); + } +} + +// Function with regex vulnerability (ReDoS) +bool validateEmailWithVulnerableRegex(String email) { + // Vulnerable regex that can cause ReDoS attacks + var vulnerableRegex = RegExp(r'^([a-zA-Z0-9_\.-]+)@([a-zA-Z0-9_\.-]+)\.([a-zA-Z]{2,})$'); + + print('Validating email: $email'); // Logging potentially sensitive data + + // Even more vulnerable regex + var superVulnerableRegex = RegExp(r'^(([a-z])+.)+[A-Z]([a-z])+$'); + + return vulnerableRegex.hasMatch(email) && superVulnerableRegex.hasMatch(email); +} + +// Function with hardcoded cryptographic keys +String encryptDataPoorly(String data) { + // Hardcoded encryption keys - major security issue + var aesKey = '1234567890123456'; // 16 bytes for AES-128 + var desKey = '12345678'; // 8 bytes for DES + var blowfishKey = '123456789012345678901234'; // 24 bytes for Blowfish + var rc4Key = 'rc4_secret_key_123'; + + print('Encrypting with AES key: $aesKey'); + print('DES key: $desKey'); + print('Blowfish key: $blowfishKey'); + print('RC4 key: $rc4Key'); + + // Poor encryption - just Base64 encoding + return base64Encode(utf8.encode(data)); +} + +// Function with time-based vulnerabilities +bool authenticateWithTimingAttack(String inputPassword, String storedPassword) { + // Vulnerable to timing attacks + print('Authenticating password: $inputPassword'); // Logging password! + + // Character by character comparison allows timing attacks + if (inputPassword.length != storedPassword.length) { + return false; + } + + for (int i = 0; i < inputPassword.length; i++) { + if (inputPassword[i] != storedPassword[i]) { + return false; // Early return reveals information about correct characters + } + + // Simulated processing delay that varies with position + for (int j = 0; j < i * 1000; j++) { + // Busy work that increases with position + } + } + + return true; +} + +// Class with mutable static state (thread safety issues) +class UnsafeStaticState { + static String globalSecret = 'global_secret_key_123'; + static int requestCounter = 0; + static Map userCache = {}; + static List activeConnections = []; + + static void updateGlobalState(String key, dynamic value) { + // Race condition potential + requestCounter++; + userCache[key] = value; + activeConnections.add(key); + + print('Global secret: $globalSecret'); // Logging secret + print('Request count: $requestCounter'); + print('Cache size: ${userCache.length}'); + } + + static void unsafeParallelOperation() { + // Simulated parallel access to shared state + for (int i = 0; i < 1000; i++) { + updateGlobalState('user$i', 'data$i'); + } + } +} + +// Function with integer overflow potential +int unsafeArithmetic(int a, int b, int c) { + // No overflow checks + var result1 = a * b * c; + var result2 = result1 * result1; + var result3 = result2 + result2 + result2; + + print('Arithmetic results: $result1, $result2, $result3'); + + return result3; +} + +// Function with deserialization vulnerability +dynamic unsafeDeserialization(String jsonString) { + // Deserializing user input without validation + print('Deserializing: $jsonString'); // Logging potentially sensitive data + + try { + var decoded = json.decode(jsonString); + + // Unsafe access to deserialized data + var userType = decoded['type']; + var userData = decoded['data']; + var userCredentials = decoded['credentials']; + + print('User type: $userType'); + print('User data: $userData'); + print('User credentials: $userCredentials'); // Logging credentials! + + return decoded; + } catch (e) { + print('Deserialization error: $e'); + return null; + } +} + +// Function with XXE vulnerability simulation +String processXmlInput(String xmlInput) { + // Simulated XML processing without XXE protection + print('Processing XML: $xmlInput'); // Logging potentially dangerous XML + + // Hardcoded XML with dangerous entities + var dangerousXml = ''' + +]> +&xxe;'''; + + print('Dangerous XML example: $dangerousXml'); + + return 'Processed XML'; +} + +// Global function with all possible issues combined +extremelyBadFunction(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) { + // Missing all type annotations and return type + // 26 parameters - way too many + + // Massive amounts of unused variables + var unused1, unused2, unused3, unused4, unused5, unused6, unused7, unused8, unused9, unused10; + var unused11, unused12, unused13, unused14, unused15, unused16, unused17, unused18, unused19, unused20; + var unused21, unused22, unused23, unused24, unused25, unused26, unused27, unused28, unused29, unused30; + + // Security issues + var topSecret = 'top_secret_master_key_xyz789'; + var systemPassword = 'system_root_password_123'; + var masterToken = 'master_admin_token_abc456'; + + print('Top secret: $topSecret'); + print('System password: $systemPassword'); + print('Master token: $masterToken'); + + // Extreme cyclomatic complexity with nested loops + for (var i1 = 0; i1 < 10; i1++) { + for (var i2 = 0; i2 < 10; i2++) { + for (var i3 = 0; i3 < 10; i3++) { + for (var i4 = 0; i4 < 10; i4++) { + for (var i5 = 0; i5 < 10; i5++) { + // 5 levels of nested loops + if (i1 > 5) { + if (i2 > 5) { + if (i3 > 5) { + if (i4 > 5) { + if (i5 > 5) { + // Complex nested conditions within loops + print('Deep nested value: ${i1 + i2 + i3 + i4 + i5}'); + + // More security issues in deep nesting + var deepSecret = 'deep_loop_secret_$i1$i2$i3$i4$i5'; + print('Deep secret: $deepSecret'); + } + } + } + } + } + } + } + } + } + } + + // Poor exception handling with resource leaks + var file = File('/tmp/temp_file.txt'); + file.writeAsStringSync('sensitive data'); // No try-catch, no resource cleanup + + // Unsafe null operations + print('Parameter a length: ${a.length}'); // Could be null + print('Parameter b first char: ${b[0]}'); // Could be null or empty + print('Parameter c uppercase: ${c.toUpperCase()}'); // Could be null + + return 'extremely bad result'; +} diff --git a/lib/main.dart b/lib/main.dart index 1ff9235..c0e5c99 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,18 +4,67 @@ import 'dart:io'; import 'screens/home_screen.dart'; import 'screens/login_screen.dart'; -// Unused import - issue +// Massive amounts of unused imports - extreme issue import 'dart:async'; +import 'dart:collection'; +import 'dart:developer'; +import 'dart:isolate'; +import 'dart:math'; +import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/physics.dart'; +import 'package:flutter/animation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/semantics.dart'; void main() { - // Missing error handling + // Missing error handling and multiple security issues + print('Starting app with admin key: sk_admin_xyz123'); // Logging secret + print('Database password: db_pass_456'); // Another secret + print('JWT Secret: jwt_super_secret_789'); // JWT secret + runApp(MyApp()); } -// Missing key in widget constructor +// Missing key in widget constructor with extreme issues class MyApp extends StatelessWidget { + // Multiple unused fields with hardcoded secrets + final String _appSecret = 'app_secret_key_123'; + final String _databaseUrl = 'postgres://user:pass@db.example.com/prod'; + final String _stripeKey = 'sk_live_stripe_key_456789'; + final int _maxRetries = 5; + final bool _debugMode = true; + final List _adminEmails = ['admin@company.com', 'root@company.com']; + final Map _apiKeys = { + 'google': 'AIzaSyGoogle123456789', + 'facebook': 'fb_key_987654321', + 'twitter': 'twitter_secret_abc123' + }; + @override Widget build(BuildContext context) { + // Massive amounts of unused variables + var unusedColor = Colors.red; + var unusedTheme = ThemeMode.dark; + var unusedLocale = Locale('en', 'US'); + var unusedTitle = 'Extreme Issues App'; + var unusedDebugBanner = false; + var unusedNavigatorKey = GlobalKey(); + var unusedScaffoldKey = GlobalKey(); + var unusedRoutes = {}; + var unusedInitialRoute = '/'; + var unusedOnGenerateRoute = null; + var unusedBuilder = null; + var unusedSupportedLocales = [Locale('en'), Locale('es'), Locale('fr')]; + + // Hardcoded secrets in build method + var buildSecret1 = 'build_secret_xyz'; + var buildSecret2 = 'another_build_secret_456'; + var buildApiKey = 'build_api_key_789'; + return MaterialApp( title: 'Sample Flutter App', theme: ThemeData( @@ -25,24 +74,230 @@ class MyApp extends StatelessWidget { debugShowCheckedModeBanner: false, ); } + + // Dead code with security issues + void _logSecrets() { + print('App Secret: $_appSecret'); + print('Database URL: $_databaseUrl'); + print('Stripe Key: $_stripeKey'); + for (var key in _apiKeys.keys) { + print('$key API Key: ${_apiKeys[key]}'); + } + } + + // More dead code with unused parameters + String _encryptData(String data, String key, int iterations) { + // Poor encryption - just Base64 + var unusedSalt = 'simple_salt'; + var unusedAlgorithm = 'AES'; + var unusedKeyLength = 256; + + print('Encrypting with key: $key'); // Logging encryption key + return base64Encode(utf8.encode(data)); + } } -// Global variable - bad practice +// Extreme global variables - bad practice var globalCounter = 0; +String globalApiKey = 'global_api_key_123'; +bool globalDebugMode = true; +List globalSecrets = ['secret1', 'secret2', 'secret3']; +Map globalConfig = { + 'db_password': 'global_db_pass', + 'admin_token': 'global_admin_token', + 'encryption_key': 'global_encrypt_key' +}; +DateTime globalStartTime = DateTime.now(); +int globalRequestCount = 0; +double globalVersion = 1.0; +var globalLogger = null; // Poor typing -// Function with no return type declaration +// Function with extreme issues getData() { + // Massive amounts of unused variables + var unusedVar1 = 'This is never used'; + var unusedVar2 = 42; + var unusedVar3 = true; + var unusedVar4 = DateTime.now(); + var unusedVar5 = []; + var unusedVar6 = {}; + var unusedVar7 = 3.14; + var unusedVar8 = Duration(seconds: 30); + var unusedVar9 = RegExp(r'[a-z]+'); + var unusedVar10 = Uri.parse('https://example.com'); + + // Security issues with hardcoded credentials + var dbPassword = 'database_password_123'; + var apiSecret = 'api_secret_456'; + var jwtToken = 'jwt_token_789'; + var encryptionKey = 'encryption_key_abc'; + // Using print instead of proper logging print('Getting data...'); - - // Unused variable - var unusedVar = 'This is never used'; + print('Using database password: $dbPassword'); // Logging secret + print('API Secret: $apiSecret'); // Logging secret + print('JWT Token: $jwtToken'); // Logging secret return 'Some data'; } -// Function with security issue - hardcoded API key +// Function with extreme security issues String getApiKey() { - // Security issue: hardcoded secret - return 'sk_live_51234567890abcdefghijklmno'; + // Multiple hardcoded secrets + var primaryKey = 'sk_live_51234567890abcdefghijklmno'; + var backupKey = 'sk_live_backup_98765432109876543210'; + var adminKey = 'sk_admin_super_secret_key_xyz'; + + // Logging all secrets + print('Primary API Key: $primaryKey'); + print('Backup API Key: $backupKey'); + print('Admin API Key: $adminKey'); + + return primaryKey; +} + +// Extremely complex function with many issues +processUserCredentials(username, password, email, phoneNumber) { + // Missing all type annotations + // Massive amounts of unused variables + var processingTime = DateTime.now(); + var attemptCount = 0; + var successFlag = false; + var errorMessage = ''; + var validationRules = []; + var encryptedPassword = ''; + var hashedEmail = ''; + var phoneCountryCode = ''; + var userAgent = 'Unknown'; + var sessionId = ''; + var deviceInfo = {}; + var locationData = {}; + var biometricData = []; + var securityQuestions = {}; + var emergencyContacts = []; + var preferenceSettings = {}; + + // Hardcoded admin credentials for comparison + var adminUsername = 'super_admin'; + var adminPassword = 'super_admin_password_123'; + var adminEmail = 'admin@company.internal'; + var adminToken = 'admin_token_xyz_789'; + var rootPassword = 'root_password_456'; + var systemKey = 'system_master_key_abc'; + + // Logging all sensitive data + print('Processing user: $username'); + print('Password: $password'); + print('Email: $email'); + print('Phone: $phoneNumber'); + print('Admin username: $adminUsername'); + print('Admin password: $adminPassword'); + print('Admin token: $adminToken'); + print('Root password: $rootPassword'); + print('System key: $systemKey'); + + // Poor validation - just string comparison + if (username == adminUsername && password == adminPassword) { + print('Admin access granted'); + return 'admin'; + } + + // Unsafe operations without null checks + print('Username length: ${username.length}'); + print('Password complexity: ${password.contains('!')}'); + print('Email domain: ${email.split('@')[1]}'); + print('Phone area code: ${phoneNumber.substring(0, 3)}'); + + return 'user'; +} + +// Dead code with circular dependency potential +class DeadClass { + static DeadClass? _instance; + String _deadProperty = 'dead'; + int _deadCounter = 0; + bool _deadFlag = false; + + // Unused constructor + DeadClass._(); + + // Dead singleton pattern + static DeadClass get instance { + _instance ??= DeadClass._(); + return _instance!; + } + + // Dead methods with security issues + void _deadMethod1() { + var deadSecret = 'dead_secret_123'; + print('Dead secret: $deadSecret'); + } + + String _deadMethod2(String input) { + var anotherDeadSecret = 'another_dead_secret_456'; + print('Another dead secret: $anotherDeadSecret'); + return input.toUpperCase(); + } + + // Dead method with null safety issues + void _deadMethod3(dynamic data) { + print('Data length: ${data.length}'); + print('First element: ${data[0]}'); + print('Last character: ${data.toString()[data.toString().length - 1]}'); + } +} + +// Global function with extreme complexity and issues +calculateSomethingComplex(a, b, c, d, e, f, g, h, i, j) { + // Missing all type annotations and return type + // Massive nested logic with unused variables + var result = 0; + var temp1 = 0; + var temp2 = 0; + var temp3 = 0; + var temp4 = 0; + var temp5 = 0; + var flag1 = false; + var flag2 = false; + var flag3 = false; + var counter1 = 0; + var counter2 = 0; + var list1 = []; + var list2 = []; + var map1 = {}; + var map2 = {}; + + // Security issues within complex logic + var secretCalculationKey = 'calc_secret_789'; + var algorithmSecret = 'algorithm_key_abc'; + + print('Calculation secret: $secretCalculationKey'); + print('Algorithm secret: $algorithmSecret'); + + // Overly complex nested conditions + if (a != null) { + if (b != null) { + if (c != null) { + if (d != null) { + if (e != null) { + if (f != null) { + if (g != null) { + if (h != null) { + if (i != null) { + if (j != null) { + // Deep nesting - bad practice + result = a + b + c + d + e + f + g + h + i + j; + print('Deep calculation result: $result'); + } + } + } + } + } + } + } + } + } + } + + return result; } From 16737b8d405a8210ab5edbb2bcd238ce4be6d6b7 Mon Sep 17 00:00:00 2001 From: Ranga Ngwerume Date: Wed, 4 Feb 2026 07:26:05 +0000 Subject: [PATCH 2/2] empty commit --- .codacy/cli.sh | 149 ++++++++++++++++++++++++++++++++++++++++++++ .codacy/codacy.yaml | 10 +-- README.md | 1 + 3 files changed, 151 insertions(+), 9 deletions(-) create mode 100755 .codacy/cli.sh diff --git a/.codacy/cli.sh b/.codacy/cli.sh new file mode 100755 index 0000000..7057e3b --- /dev/null +++ b/.codacy/cli.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash + + +set -e +o pipefail + +# Set up paths first +bin_name="codacy-cli-v2" + +# Determine OS-specific paths +os_name=$(uname) +arch=$(uname -m) + +case "$arch" in +"x86_64") + arch="amd64" + ;; +"x86") + arch="386" + ;; +"aarch64"|"arm64") + arch="arm64" + ;; +esac + +if [ -z "$CODACY_CLI_V2_TMP_FOLDER" ]; then + if [ "$(uname)" = "Linux" ]; then + CODACY_CLI_V2_TMP_FOLDER="$HOME/.cache/codacy/codacy-cli-v2" + elif [ "$(uname)" = "Darwin" ]; then + CODACY_CLI_V2_TMP_FOLDER="$HOME/Library/Caches/Codacy/codacy-cli-v2" + else + CODACY_CLI_V2_TMP_FOLDER=".codacy-cli-v2" + fi +fi + +version_file="$CODACY_CLI_V2_TMP_FOLDER/version.yaml" + + +get_version_from_yaml() { + if [ -f "$version_file" ]; then + local version=$(grep -o 'version: *"[^"]*"' "$version_file" | cut -d'"' -f2) + if [ -n "$version" ]; then + echo "$version" + return 0 + fi + fi + return 1 +} + +get_latest_version() { + local response + if [ -n "$GH_TOKEN" ]; then + response=$(curl -Lq --header "Authorization: Bearer $GH_TOKEN" "https://api.github.com/repos/codacy/codacy-cli-v2/releases/latest" 2>/dev/null) + else + response=$(curl -Lq "https://api.github.com/repos/codacy/codacy-cli-v2/releases/latest" 2>/dev/null) + fi + + handle_rate_limit "$response" + local version=$(echo "$response" | grep -m 1 tag_name | cut -d'"' -f4) + echo "$version" +} + +handle_rate_limit() { + local response="$1" + if echo "$response" | grep -q "API rate limit exceeded"; then + fatal "Error: GitHub API rate limit exceeded. Please try again later" + fi +} + +download_file() { + local url="$1" + + echo "Downloading from URL: ${url}" + if command -v curl > /dev/null 2>&1; then + curl -# -LS "$url" -O + elif command -v wget > /dev/null 2>&1; then + wget "$url" + else + fatal "Error: Could not find curl or wget, please install one." + fi +} + +download() { + local url="$1" + local output_folder="$2" + + ( cd "$output_folder" && download_file "$url" ) +} + +download_cli() { + # OS name lower case + suffix=$(echo "$os_name" | tr '[:upper:]' '[:lower:]') + + local bin_folder="$1" + local bin_path="$2" + local version="$3" + + if [ ! -f "$bin_path" ]; then + echo "📥 Downloading CLI version $version..." + + remote_file="codacy-cli-v2_${version}_${suffix}_${arch}.tar.gz" + url="https://github.com/codacy/codacy-cli-v2/releases/download/${version}/${remote_file}" + + download "$url" "$bin_folder" + tar xzfv "${bin_folder}/${remote_file}" -C "${bin_folder}" + fi +} + +# Warn if CODACY_CLI_V2_VERSION is set and update is requested +if [ -n "$CODACY_CLI_V2_VERSION" ] && [ "$1" = "update" ]; then + echo "⚠️ Warning: Performing update with forced version $CODACY_CLI_V2_VERSION" + echo " Unset CODACY_CLI_V2_VERSION to use the latest version" +fi + +# Ensure version.yaml exists and is up to date +if [ ! -f "$version_file" ] || [ "$1" = "update" ]; then + echo "ℹ️ Fetching latest version..." + version=$(get_latest_version) + mkdir -p "$CODACY_CLI_V2_TMP_FOLDER" + echo "version: \"$version\"" > "$version_file" +fi + +# Set the version to use +if [ -n "$CODACY_CLI_V2_VERSION" ]; then + version="$CODACY_CLI_V2_VERSION" +else + version=$(get_version_from_yaml) +fi + + +# Set up version-specific paths +bin_folder="${CODACY_CLI_V2_TMP_FOLDER}/${version}" + +mkdir -p "$bin_folder" +bin_path="$bin_folder"/"$bin_name" + +# Download the tool if not already installed +download_cli "$bin_folder" "$bin_path" "$version" +chmod +x "$bin_path" + +run_command="$bin_path" +if [ -z "$run_command" ]; then + fatal "Codacy cli v2 binary could not be found." +fi + +if [ "$#" -eq 1 ] && [ "$1" = "download" ]; then + echo "Codacy cli v2 download succeeded" +else + eval "$run_command $*" +fi \ No newline at end of file diff --git a/.codacy/codacy.yaml b/.codacy/codacy.yaml index 15365c7..b1e4c5e 100644 --- a/.codacy/codacy.yaml +++ b/.codacy/codacy.yaml @@ -1,15 +1,7 @@ runtimes: - dart@3.7.2 - - go@1.22.3 - - java@17.0.10 - - node@22.2.0 - python@3.11.11 tools: - - dartanalyzer@3.7.2 - - eslint@8.57.0 - - lizard@1.17.31 - - pmd@7.11.0 - - pylint@3.3.6 - - revive@1.7.0 + - dartanalyzer@3.9.3 - semgrep@1.78.0 - trivy@0.66.0 diff --git a/README.md b/README.md index a7b3803..85fee2a 100644 --- a/README.md +++ b/README.md @@ -54,3 +54,4 @@ flutter run ```bash flutter analyze ``` +