Execute IntelliJ Indexing Programmatically

Answered

I want to execute IntelliJ indexing via programming. Basically, I want to create one script(Gradle) which will execute all necessary steps(i.e build project, indexing, etc.) without opening IntelliJ. Does IntelliJ provides any API to do this ?

0
3 comments

You may be able to do this using ApplicationStarter but you'd need to write a custom plugin. You can also check https://www.jetbrains.com/help/idea/working-with-the-ide-features-from-command-line.html#arguments

 I've prototyped something similar but used the embedded web server for controlling IntelliJ while running. 

But why would you want to run the indexing without anything else? Perhaps you're looking for https://www.jetbrains.com/help/idea/shared-indexes.html?

 

 

 

0

Can you please share any examples of ApplicationStarter?

0

I have multiple projects which updates from time to time in order to not waste much time when I will open it after some time I've made this python script(Windows) which I'm running in loop for each directory. I assumed that if there is less than 10% CPU usage, IDE finished indexing and is in idle state.

 

import os
import subprocess
import time
import ctypes

intellij_path = r"C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2023.3.8\bin\idea64.exe"
intellij_process_name = os.path.basename(intellij_path).replace('.exe', '')

def get_cpu_usage(process_name):
    """Return the CPU usage percentage for the specified process."""
    try:
        usage_cmd = f'wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime | findstr /i "{process_name}"'
        result = subprocess.run(usage_cmd, capture_output=True, text=True, shell=True)
        output = result.stdout.strip().splitlines()
        if len(output) >= 1:
            cpu_usage = int(output[0].strip().split()[1])
            num_logical_processors = os.cpu_count()
            return cpu_usage / num_logical_processors
    except Exception as e:
        print(f"Error fetching CPU usage: {e}")
    return 0

def average_cpu_usage(process_name, samples=5):
    """Collect CPU usage samples and return the average."""
    usages = []
    for _ in range(samples):
        usage = get_cpu_usage(process_name)
        usages.append(usage)
        print(f"CPU usage sample: {usage:.2f}%")
        time.sleep(1)
    return sum(usages) / len(usages) if usages else 0

def kill_process(process_name, window_name):
    """Terminate the specified process by window name gracefully, allowing it time to save changes."""
    try:
        # Find the window by the window name
        hwnd = find_windows_with_prefix(window_name)[0]

        if hwnd:
            print(f"Próba zamknięcia {window_name} gracefully...")
            # Send a message to close the window (WM_CLOSE)
            ctypes.windll.user32.SendMessageW(hwnd, 0x0010, 0, 0)  # WM_CLOSE

            # Wait for a few seconds to allow the application to close properly
            print(f"Oczekiwanie na zamknięcie {window_name}...")
            time.sleep(10)  # Adjust the sleep duration as needed
            
            # Check if the window is still open
            if ctypes.windll.user32.IsWindow(hwnd):  # If the window is still open
                print(f"{window_name} nie zamknęło się, wymuszam zakończenie...")
                force_kill_cmd = f'taskkill /f /im {process_name}'
                subprocess.run(force_kill_cmd, shell=True)
        else:
            print(f"Nie znaleziono okna dla {window_name}. Może nie działa.")
            # If no window found, attempt to kill it directly
            print(f"Wymuszone zakończenie {process_name}...")
            force_kill_cmd = f'taskkill /f /im {process_name}'
            subprocess.run(force_kill_cmd, shell=True)

    except Exception as e:
        print(f"Błąd podczas zamykania procesu: {e}")

def run_idea_in_directory(repo):
    """Run IntelliJ IDEA in the specified repository's directory and monitor CPU usage."""
    dir_path = os.path.join(os.getcwd(), repo)
    print(f"Launching IntelliJ in directory: {dir_path}")
    proc = subprocess.Popen([intellij_path, dir_path], shell=True)

    print("Checking CPU usage...")
    while True:
        average_usage = average_cpu_usage(intellij_process_name)
        print(f"Average CPU usage: {average_usage:.2f}%")
        if average_usage < 10:
            print(f"Average CPU usage fell below 10%, closing project in directory: {dir_path}")
            kill_process(f'{intellij_process_name}.exe', repo)
            break
        else:
            print("CPU usage is normal, checking again.")
            
0

Please sign in to leave a comment.