create python script,iterate one by one in flutter lib folder, if import has error -…
- User
create python script,iterate one by one in flutter lib folder, if import has error - target uri doesnot exist, we need add dependency to pubspec, run pub get and check error again, use local lm studio server to fix
Assistant
Okay, this is an interesting and complex task! This script will attempt to automate fixing "Target of URI doesn't exist" errors in a Flutter project by:
- Running
flutter analyzeto find these specific errors. - Extracting the missing package name.
- Querying your local LM Studio instance for the correct
pubspec.yamldependency line. - Adding the dependency to
pubspec.yaml. - Running
flutter pub get. - Looping until no more such errors are found or a configurable limit is reached.
Prerequisites:
- Python 3.x installed.
requestslibrary:pip install requestsruamel.yamllibrary:pip install ruamel.yaml(This is better thanPyYAMLfor preserving comments and formatting inpubspec.yaml).- Flutter SDK: Installed and
fluttercommand available in your PATH. - LM Studio: Running locally, with a model loaded, and its API server active (usually on
http://localhost:1234/v1/chat/completions).
Python Script (
fix_flutter_imports.py):import os import subprocess import re import requests import json from ruamel.yaml import YAML import time import sys # --- Configuration --- LM_STUDIO_API_URL = "http://localhost:1234/v1/chat/completions" # Default LM Studio API # Regex to find "Target of URI doesn't exist" errors and extract package name # Example: info • The target of the URI 'package:http/http.dart' doesn't exist • lib/main.dart:2:8 • uri_does_not_exist # Example: info • The target of the URI 'package:provider' doesn't exist • lib/another.dart:1:8 • uri_does_not_exist ERROR_REGEX = re.compile( r"The target of the URI 'package:([^/:]+)(?:/[^']*)?' doesn't exist.+?•\s*([^•]+?):(\d+:\d+)" ) MAX_FIX_ATTEMPTS = 10 # Max iterations to prevent infinite loops PROJECT_PATH = "." # Default to current directory # --- Helper Functions --- def run_command(command_args, cwd=".", check=False, suppress_output=False): """Runs a shell command and returns its output and exit code.""" print(f"CMD: {' '.join(command_args)} (in {os.path.abspath(cwd)})") try: process = subprocess.Popen( command_args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8' ) stdout, stderr = process.communicate() if not suppress_output: if stdout: print("STDOUT:\n", stdout) if stderr: print("STDERR:\n", stderr) if check and process.returncode != 0: raise subprocess.CalledProcessError(process.returncode, command_args, stdout, stderr) return stdout, stderr, process.returncode except FileNotFoundError: print(f"Error: Command '{command_args[0]}' not found. Is Flutter SDK in your PATH?") return "", f"Command not found: {command_args[0]}", 127 # Common exit code for command not found except Exception as e: print(f"Error running command {' '.join(command_args)}: {e}") return "", str(e), 1 def get_analysis_errors(project_path): """Runs flutter analyze and parses for 'Target of URI doesn't exist' errors.""" print("\n🔍 Running flutter analyze...") # --no-pub is important to avoid getting stuck if pubspec is already inconsistent # --fatal-infos ensures 'info' level errors like uri_does_not_exist are treated as problems stdout, stderr, returncode = run_command( ["flutter", "analyze", "--no-pub", "--fatal-infos", "."], cwd=project_path, suppress_output=True # We'll parse it, so don't print it all now ) # `flutter analyze` can return non-zero for various reasons, # but we are only interested in specific errors. # The output we care about is usually in stdout for these info-level errors. # If stderr has "Target of URI" errors, include that too. combined_output = stdout + "\n" + stderr errors = [] # print("--- Analysis Output ---") # For debugging # print(combined_output) # print("-----------------------") for line in combined_output.splitlines(): match = ERROR_REGEX.search(line) if match: package_name = match.group(1) file_path = match.group(2) # line_col = match.group(3) # Not directly used yet, but good to have errors.append({"package_name": package_name, "file_path": file_path, "full_error_line": line.strip()}) print(f" Detected missing package: '{package_name}' in '{file_path}'") if not errors and returncode != 0 and "No issues found!" not in combined_output : print(f" Flutter analyze returned code {returncode} with no actionable 'URI does not exist' errors. Output:") print(combined_output) # This could mean other types of errors exist. return errors def query_llm_for_dependency(package_name, file_path, error_line): """Queries LM Studio for the pubspec.yaml dependency line.""" print(f"\n🤖 Querying LM Studio for package: {package_name}") prompt = ( f"A Flutter project has a Dart file '{file_path}' with an import that causes this error:\n" f"'{error_line}'\n\n" f"The missing package appears to be '{package_name}'.\n" f"What is the correct dependency line to add to the `dependencies:` section of `pubspec.yaml` " f"for the package '{package_name}'? \n" f"Provide ONLY the dependency line itself, like ' package_name: ^version'. " f"Do not include 'dependencies:' or any other surrounding text. " f"If you are unsure, or if it's a Dart SDK package (like 'dart:io'), respond with 'SDK_PACKAGE'." ) payload = { "model": "loaded-model", # LM Studio uses the currently loaded model "messages": [ {"role": "system", "content": "You are a helpful assistant that provides Flutter pubspec dependency lines."}, {"role": "user", "content": prompt} ], "temperature": 0.1, # Low temperature for more deterministic output "max_tokens": 50, } try: response = requests.post(LM_STUDIO_API_URL, json=payload, timeout=60) response.raise_for_status() data = response.json() # Debug: print full LLM response # print(f"LLM Raw Response: {json.dumps(data, indent=2)}") if data.get("choices") and data["choices"][0].get("message"): content = data["choices"][0]["message"]["content"].strip() # Further clean up potential LLM verbosity # Find lines that look like " package_name: ^version" dep_match = re.search(r"^\s*([a-zA-Z0-9_]+):\s*([^\s]+.*)$", content, re.MULTILINE) if dep_match: extracted_dep = f" {dep_match.group(1)}: {dep_match.group(2)}" print(f" LLM Suggestion (parsed): {extracted_dep}") return extracted_dep elif "SDK_PACKAGE" in content.upper(): print(f" LLM indicates '{package_name}' is likely an SDK package. Skipping.") return "SDK_PACKAGE" else: print(f" LLM provided an unexpected response: {content}") # Fallback: try to use content as is if it looks somewhat like a dependency if len(content.split(':')) == 2 and not content.startswith("dependencies:"): return " " + content.strip() # Add indentation return None else: print(f" LLM response format error: {data}") return None except requests.exceptions.RequestException as e: print(f" Error querying LM Studio: {e}") print(" Is LM Studio server running at " + LM_STUDIO_API_URL + "?") return None except Exception as e: print(f" An unexpected error occurred during LLM query: {e}") return None def add_dependency_to_pubspec(project_path, dependency_line): """Adds the dependency line to pubspec.yaml under 'dependencies:'.""" pubspec_path = os.path.join(project_path, "pubspec.yaml") yaml = YAML() yaml.preserve_quotes = True yaml.indent(mapping=2, sequence=4, offset=2) try: with open(pubspec_path, 'r') as f: data = yaml.load(f) if 'dependencies' not in data: data['dependencies'] = {} # Extract package name from dependency_line (e.g., " http: ^1.0.0" -> "http") package_key_match = re.match(r"\s*([a-zA-Z0-9_]+):", dependency_line) if not package_key_match: print(f" Could not parse package name from LLM suggestion: '{dependency_line}'") return False package_key = package_key_match.group(1) if package_key in data['dependencies']: print(f" Package '{package_key}' already exists in pubspec.yaml. Skipping add.") return False # Or True, if we consider "already exists" as success # Simple way to add, though not perfectly preserving internal order of dependencies # For more precise insertion, ruamel.yaml has more advanced features # This adds the raw string, which is what we want since LLM provides formatting # A bit hacky: re-parse the line to add it as a key-value pair try: temp_yaml_data = yaml.load(dependency_line) new_dep_key = list(temp_yaml_data.keys())[0] new_dep_value = temp_yaml_data[new_dep_key] data['dependencies'][new_dep_key] = new_dep_value except Exception as e: print(f" Could not parse LLM suggestion '{dependency_line}' as YAML: {e}") print(f" Attempting to add as raw line (may break pubspec format).") # This is a risky fallback, as it might break YAML structure if not careful # A safer alternative is to give up here return False with open(pubspec_path, 'w') as f: yaml.dump(data, f) print(f" Successfully added '{dependency_line.strip()}' to pubspec.yaml") return True except Exception as e: print(f" Error updating pubspec.yaml: {e}") return False def run_pub_get(project_path): """Runs flutter pub get.""" print("\n📦 Running flutter pub get...") stdout, stderr, returncode = run_command(["flutter", "pub", "get"], cwd=project_path) if returncode == 0: print(" Flutter pub get successful.") return True else: print(" Flutter pub get FAILED.") # Consider reverting pubspec.yaml change here if desired return False # --- Main Logic --- def main(): project_dir = os.path.abspath(PROJECT_PATH) if not os.path.exists(os.path.join(project_dir, "pubspec.yaml")): print(f"Error: pubspec.yaml not found in {project_dir}") print("Please run this script from the root of your Flutter project.") return print(f"🚀 Starting Flutter Import Fixer for project: {project_dir}") fixed_one_in_iteration = True # Start true to enter the loop attempts = 0 fixed_packages_this_session = set() while fixed_one_in_iteration and attempts < MAX_FIX_ATTEMPTS: attempts += 1 print(f"\n--- Iteration {attempts}/{MAX_FIX_ATTEMPTS} ---") fixed_one_in_iteration = False # Reset for this iteration errors = get_analysis_errors(project_dir) if not errors: print("\n🎉 No 'Target of URI doesn't exist' errors found!") break # Try to fix one error at a time to avoid cascading issues # Pick the first error that hasn't been attempted this session error_to_fix = None for err in errors: if err['package_name'] not in fixed_packages_this_session: error_to_fix = err break if not error_to_fix: print("\n⚠️ All detected missing packages have been attempted this session.") print(" There might be other errors, or the fixes were not successful.") print(f" Packages attempted: {fixed_packages_this_session}") break pkg_name = error_to_fix["package_name"] file_path = error_to_fix["file_path"] full_error_line = error_to_fix["full_error_line"] print(f"🎯 Attempting to fix missing package: '{pkg_name}' from '{file_path}'") dependency_line = query_llm_for_dependency(pkg_name, file_path, full_error_line) if dependency_line == "SDK_PACKAGE": print(f" '{pkg_name}' is an SDK package. No pubspec change needed.") fixed_packages_this_session.add(pkg_name) # Mark as "handled" # It's possible the error was a typo like 'dart.io' instead of 'dart:io' # This script doesn't fix typos within the import statement itself. # We assume if it's SDK, the error is elsewhere or a persistent typo. # To avoid infinite loops on SDK packages, we add to fixed_packages_this_session # and hope the next analysis pass (if any) resolves or shows a different error. fixed_one_in_iteration = True # Count as "progress" to allow loop to continue for other errors time.sleep(1) # Small delay continue # Try next error or re-analyze if dependency_line: if add_dependency_to_pubspec(project_dir, dependency_line): if run_pub_get(project_dir): print(f" ✅ Successfully added '{pkg_name}' and ran pub get.") fixed_one_in_iteration = True fixed_packages_this_session.add(pkg_name) else: print(f" ❌ Failed to run pub get after adding '{pkg_name}'.") print(" Consider manually checking pubspec.yaml and the dependency.") # Potentially revert pubspec.yaml change here # For now, we stop on pub get failure for this package fixed_packages_this_session.add(pkg_name) # Mark as attempted to avoid retrying same bad dep else: print(f" ❌ Failed to add dependency for '{pkg_name}' to pubspec.yaml.") fixed_packages_this_session.add(pkg_name) # Mark as attempted else: print(f" ❌ Could not get dependency suggestion for '{pkg_name}' from LLM.") fixed_packages_this_session.add(pkg_name) # Mark as attempted if not fixed_one_in_iteration and errors: print(f" Could not make progress on package '{pkg_name}'. It might be a complex issue or LLM couldn't help.") time.sleep(2) # Small delay before next analysis if attempts >= MAX_FIX_ATTEMPTS: print(f"\n🏁 Reached max iterations ({MAX_FIX_ATTEMPTS}). Stopping.") print("\n📊 Final check: Running flutter analyze one last time...") # Run with pub this time to ensure everything is resolved run_command(["flutter", "analyze", "."], cwd=project_dir) print("\nScript finished.") if __name__ == "__main__": if len(sys.argv) > 1: PROJECT_PATH = sys.argv[1] if not os.path.isdir(PROJECT_PATH): print(f"Error: Provided project path '{PROJECT_PATH}' is not a valid directory.") sys.exit(1) else: PROJECT_PATH = "." # Default to current directory main()How to Use:
- Save: Save the code above as
fix_flutter_imports.pyin a convenient location (e.g., your user scripts folder, or even the root of your Flutter project temporarily). - LM Studio:
- Start LM Studio.
- Load a capable model (e.g., CodeLlama instruct, Mistral instruct, etc.).
- Go to the "Local Server" tab (usually the
<<=>icon). - Click "Start Server". Note the API endpoint (default
http://localhost:1234/v1).
- Run the Script:
- Open your terminal or command prompt.
- Navigate to the root directory of your Flutter project.
- Execute the script:
- If
fix_flutter_imports.pyis in your project root:python fix_flutter_imports.py - If it's elsewhere and your project is the current dir:
python /path/to/fix_flutter_imports.py . - To specify a project path:
python /path/to/fix_flutter_imports.py /path/to/your/flutter/project
- If
Explanation and Important Notes:
- Iterative Process: The script runs
flutter analyze, attempts to fix one detected missing package, runsflutter pub get, and then repeats. This is safer than trying to fix all at once. - LM Studio Prompt: The prompt engineering is crucial. It tries to guide the LLM to provide only the dependency line. LLMs can be verbose, so the script does some basic parsing of the LLM's output.
ruamel.yaml: This library is used to modifypubspec.yamlbecause it's good at preserving comments, ordering, and overall structure, which is important forpubspec.yamlfiles.- Error Regex: The
ERROR_REGEXis designed to capture the package name from the "Target of URI doesn't exist" error. This might need adjustment if Flutter's error message format changes. --no-puband--fatal-infos:flutter analyze --no-pub: Preventsanalyzefrom runningpub getitself, which could lead to loops ifpubspec.yamlis in a bad state.--fatal-infos: Treats "info" level diagnostics (likeuri_does_not_exist) as errors, making them easier to detect.
- SDK Packages: The script tries to detect if the LLM suggests a package is part of the Dart SDK (e.g.,
dart:io). In such cases, it won't try to add it topubspec.yaml. The underlying issue might be a typo in the import itself (e.g.,import 'dart.io'instead ofimport 'dart:io'), which this script doesn't directly fix. - Robustness:
- This is a fairly complex automation. LLM responses can vary. The script tries to handle some common cases but might fail if the LLM gives a very unusual response or if
pub getfails for reasons other than a missing dependency (e.g., version conflicts). - It includes a
MAX_FIX_ATTEMPTSto prevent infinite loops. - The
fixed_packages_this_sessionset tries to avoid repeatedly trying to fix the same package if the LLM gives a bad suggestion or if it's an SDK package.
- This is a fairly complex automation. LLM responses can vary. The script tries to handle some common cases but might fail if the LLM gives a very unusual response or if
- No Revert on Failure: If
flutter pub getfails after adding a dependency, the script currently doesn't automatically revert the change topubspec.yaml. You might want to add this feature if you use it extensively. - Backup
pubspec.yaml: Before running this on a critical project, it's always a good idea to back up yourpubspec.yamlfile.
This script is a good starting point. You might need to tweak the prompt, error parsing, or LLM response handling based on the specific model you use in LM Studio and its output style.
- Running
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.