Unnamed: 0
int64
0
305k
body
stringlengths
7
52.9k
name
stringlengths
1
185
7,600
void (@Nullable PlaybackContext context, String text, Type type) { if (type == Type.error) { LOG.error(text); } else { LOG.info(text); } }
message
7,601
void (Project project, CompletableFuture<?> callback) { EP_NAME.getExtensionList().forEach(extension -> extension.patchCommandCallback(project, callback) ); }
applyPatchesToCommandCallback
7,602
void () { performanceTestSpan = TRACER.spanBuilder(SPAN_NAME).setNoParent().startSpan(); performanceScope = performanceTestSpan.makeCurrent(); }
startSpan
7,603
void () { if (performanceScope != null) performanceScope.close(); if (performanceTestSpan != null) performanceTestSpan.end(); }
endSpan
7,604
Context () { if (performanceTestSpan != null) return Context.current().with(performanceTestSpan); return Context.current(); }
getContext
7,605
IJTracer (boolean noopTracer) { return noopTracer ? WARMUP_TRACER : TRACER; }
getTracer
7,606
Span (@NotNull String name, @NotNull Attributes attributes) { return span.addEvent(name, attributes); }
addEvent
7,607
Span (@NotNull String name, @NotNull Attributes attributes, long timestamp, @NotNull TimeUnit unit) { return span.addEvent(name, attributes, timestamp, unit); }
addEvent
7,608
Span (@NotNull StatusCode statusCode, @NotNull String description) { return span.setStatus(statusCode, description); }
setStatus
7,609
Span (@NotNull Throwable exception, @NotNull Attributes additionalAttributes) { return span.recordException(exception, additionalAttributes); }
recordException
7,610
Span (@NotNull String name) { return span.updateName(name); }
updateName
7,611
void () { listener.onEnd(this); span.end(); }
end
7,612
void (long timestamp, @NotNull TimeUnit unit) { listener.onEnd(this); span.end(timestamp, unit); }
end
7,613
SpanContext () { return span.getSpanContext(); }
getSpanContext
7,614
boolean () { return span.isRecording(); }
isRecording
7,615
void () { }
activityFinished
7,616
ActivityTracker (@NotNull Supplier<@NotNull @NlsSafe String> debugMessageProducer) { if (disabledOutsideIntegrationTests) return dumbTracker; long keyNumber = keyNumberCounter.getAndIncrement(); synchronized (LOCK) { activities.put(keyNumber, debugMessageProducer); } return new MyActivityTracker(keyNumber); }
registerBeginningOfInitializationActivity
7,617
boolean () { if (disabledOutsideIntegrationTests) return true; if (!StartupManager.getInstance(myProject).postStartupActivityPassed()) { LOG.info("Project startup activities are not finished yet."); return false; } Supplier<@NotNull @NlsSafe String> nextMessage; synchronized (LOCK) { if (activities.isEmpty()) return true; nextMessage = activities.values().iterator().next(); } LOG.info("Project initialization & indexing not finished. " + nextMessage.get() + " is still running"); return false; }
isProjectInitializationAndIndexingFinished
7,618
void () { synchronized (LOCK) { activities.remove(code); } }
activityFinished
7,619
void (Project project, CompletableFuture<?> callback) { }
patchCommandCallback
7,620
void () { try { if (isProfilingEnabled()) { PropertiesComponent.getInstance(project).setValue(PROFILE_INDEXING_COMPONENT, false); PropertiesComponent.getInstance(project).setValue(PROFILE_WITH_ASYNC, false); Profiler.getCurrentProfilerHandler(project).startProfiling(project.getName(), new ArrayList<>()); DumbService.getInstance(project).runReadActionInSmartMode(()->{ runScriptAfterDumb(project); }); } } catch (Exception e) { new ActionCallbackProfilerStopper().reject(e.getMessage()); } }
enteredDumbMode
7,621
void (Project project) { DumbService.getInstance(project).smartInvokeLater(() -> myAlarm.addRequest(() -> { if (DumbService.isDumb(project)) { runScriptAfterDumb(project); } else { ProfilersController.getInstance(); if (Profiler.isAnyProfilingStarted()) { try { ProfilersController.getInstance().getCurrentProfilerHandler().stopProfiling(new ArrayList<>()); ProfilersController.getInstance().setStoppedByScript(true); } catch (Exception e) { new ActionCallbackProfilerStopper().setRejected(); } ApplicationManager.getApplication().invokeLater(() -> new FinishScriptDialog(project).show()); } } }, TIMEOUT)); }
runScriptAfterDumb
7,622
boolean () { return PropertiesComponent.getInstance(project).getBoolean(PROFILE_INDEXING_COMPONENT); }
isProfilingEnabled
7,623
void (@Nullable Project project) { myProject = project; if (project != null && !project.isDefault() && !project.isDisposed()) { Disposer.register(project, () -> { if (project == myProject) { Disposer.dispose(onStop); } }); } }
setProject
7,624
Project () { return myProject; }
getProject
7,625
void (MessageBusConnection connection) { super.subscribeListeners(connection); connection.subscribe(DynamicPluginListener.TOPIC, myDynamicPluginListener); }
subscribeListeners
7,626
void () { super.onStop(); myStopped = true; }
onStop
7,627
PlaybackCommand (@NotNull String _command, int line, @NotNull File scriptDir) { String command = _command.replaceAll("[\r\n]+$", ""); String[] cmdline = command.split("\\s+"); PlaybackCommand playbackCommand = null; if (cmdline.length > 0) { String commandName = cmdline[0]; CreateCommand createCommand = CommandProvider.findCommandCreator(commandName); if (createCommand != null) { playbackCommand = createCommand.invoke(command, line); if (playbackCommand instanceof AbstractCommand) { ((AbstractCommand)playbackCommand).setScriptDir(scriptDir); } } } if (playbackCommand == null) { playbackCommand = super.createCommand(command, line, scriptDir); } return playbackCommand; }
createCommand
7,628
void (@NotNull String fullCommandLine) { myChainedReporter.startOfCommand(fullCommandLine); myOTSpanLogger.startSpan(fullCommandLine); }
startOfCommand
7,629
void (@Nullable String errDescriptionOrNull) { myOTSpanLogger.endSpan(errDescriptionOrNull); myChainedReporter.endOfCommand(errDescriptionOrNull); }
endOfCommand
7,630
void (@Nullable Project project) { myChainedReporter.startOfScript(project); SpanBuilder spanBuilder = PerformanceTestSpan.TRACER.spanBuilder("Script Runner"); if (SystemProperties.getBooleanProperty(REPORT_RUNNER_SPAN_AS_ROOT, false)) { spanBuilder = spanBuilder.setNoParent(); } mySpan = spanBuilder.startSpan(); myOTSpanLogger = new SafeSpanStack(PerformanceTestSpan.TRACER, Context.current().with(mySpan)); }
startOfScript
7,631
void () { myChainedReporter.scriptCanceled(); }
scriptCanceled
7,632
void (@Nullable Project project) { Disposer.dispose(myOTSpanLogger); mySpan.end(); myChainedReporter.endOfScript(project); }
endOfScript
7,633
void (@NotNull Object file, @NotNull Path path) { try { objectMapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), file); } catch (IOException e) { throw new RuntimeException("Failed to write data to " + path, e); } }
dump
7,634
String (@NotNull Project project) { return collectHardwareInfo(); }
collectInfo
7,635
String () { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); info.add("=====OS SUMMARY=====\n"); printOperatingSystem(os); printComputerSystem(hal.getComputerSystem()); info.add("\n=====CPU SUMMARY=====\n"); printProcessor(hal.getProcessor()); printCpu(hal.getProcessor()); info.add("\n=====MEMORY SUMMARY=====\n"); printMemory(hal.getMemory()); info.add("\n=====PROCESSES SUMMARY=====\n"); printProcesses(os, hal.getMemory()); info.add("\n=====FILESYSTEM SUMMARY=====\n"); printDisks(hal.getDiskStores()); printLVgroups(hal.getLogicalVolumeGroups()); printFileSystem(os.getFileSystem()); info.add("\n=====NETWORK SUMMARY=====\n"); printNetworkInterfaces(hal.getNetworkIFs()); printNetworkParameters(os.getNetworkParams()); info.add("\n=====GRAPHICS SUMMARY=====\n"); printDisplays(hal.getDisplays()); printGraphicsCards(hal.getGraphicsCards()); StringBuilder output = new StringBuilder(); for (String s : info) { output.append(s); if (s != null && !s.endsWith("\n")) { output.append('\n'); } } return output.toString(); }
collectHardwareInfo
7,636
void (final OperatingSystem os) { info.add(String.valueOf(os)); info.add("Booted: " + Instant.ofEpochSecond(os.getSystemBootTime())); info.add("Uptime: " + FormatUtil.formatElapsedSecs(os.getSystemUptime())); info.add("Running with" + (os.isElevated() ? "" : "out") + " elevated permissions."); }
printOperatingSystem
7,637
void (final ComputerSystem computerSystem) { info.add("System: " + computerSystem.toString()); }
printComputerSystem
7,638
void (CentralProcessor processor) { info.add(processor.toString()); info.add(" Cores:"); for (CentralProcessor.PhysicalProcessor p : processor.getPhysicalProcessors()) { info.add(" " + p.getPhysicalProcessorNumber() + ": efficiency=" + p.getEfficiency() + ", id=" + p.getIdString()); } }
printProcessor
7,639
void (GlobalMemory memory) { info.add("Physical Memory: \n " + memory.toString()); VirtualMemory vm = memory.getVirtualMemory(); info.add("Virtual Memory: \n " + vm.toString()); List<PhysicalMemory> pmList = memory.getPhysicalMemory(); if (!pmList.isEmpty()) { info.add("Physical Memory: "); for (PhysicalMemory pm : pmList) { info.add(" " + pm.toString()); } } }
printMemory
7,640
void (CentralProcessor processor) { long[] prevTicks = processor.getSystemCpuLoadTicks(); long[][] prevProcTicks = processor.getProcessorCpuLoadTicks(); // Wait a second... Util.sleep(1000); long[] ticks = processor.getSystemCpuLoadTicks(); long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal; info.add(String.format( "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%", 100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu, 100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu)); info.add(String.format("CPU load: %.1f%%", processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100)); double[] loadAverage = processor.getSystemLoadAverage(3); info.add("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0])) + (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1])) + (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2]))); // per core CPU StringBuilder procCpu = new StringBuilder("CPU load per processor:"); double[] load = processor.getProcessorCpuLoadBetweenTicks(prevProcTicks); for (double avg : load) { procCpu.append(String.format(" %.1f%%", avg * 100)); } info.add(procCpu.toString()); long freq = processor.getProcessorIdentifier().getVendorFreq(); if (freq > 0) { info.add("Vendor Frequency: " + FormatUtil.formatHertz(freq)); } freq = processor.getMaxFreq(); if (freq > 0) { info.add("Max Frequency: " + FormatUtil.formatHertz(freq)); } long[] freqs = processor.getCurrentFreq(); if (freqs[0] > 0) { StringBuilder sb = new StringBuilder("Current Frequencies: "); for (int i = 0; i < freqs.length; i++) { if (i > 0) { sb.append(", "); } sb.append(FormatUtil.formatHertz(freqs[i])); } info.add(sb.toString()); } }
printCpu
7,641
void (OperatingSystem os, GlobalMemory memory) { OSProcess myProc = os.getProcess(os.getProcessId()); if (myProc == null) { return; } info.add( "My PID: " + myProc.getProcessID() + " with affinity " + Long.toBinaryString(myProc.getAffinityMask())); info.add("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount()); // Sort by highest CPU List<OSProcess> procs = os.getProcesses(OperatingSystem.ProcessFiltering.ALL_PROCESSES, OperatingSystem.ProcessSorting.CPU_DESC, 5); info.add(" PID %CPU %MEM VSZ RSS Name"); for (int i = 0; i < procs.size() && i < 5; i++) { OSProcess p = procs.get(i); info.add(String.format(" %5d %5.1f %4.1f %9s %9s %s", p.getProcessID(), 100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(), 100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()), FormatUtil.formatBytes(p.getResidentSetSize()), p.getName())); } OSProcess p = os.getProcess(os.getProcessId()); info.add("Current process environment: "); for (Map.Entry<String, String> e : p.getEnvironmentVariables().entrySet()) { info.add(" " + e.getKey() + "=" + e.getValue()); } }
printProcesses
7,642
void (List<HWDiskStore> list) { info.add("Disks:"); for (HWDiskStore disk : list) { info.add(" " + disk.toString()); List<HWPartition> partitions = disk.getPartitions(); for (HWPartition part : partitions) { info.add(" |-- " + part.toString()); } } }
printDisks
7,643
void (List<LogicalVolumeGroup> list) { if (!list.isEmpty()) { info.add("Logical Volume Groups:"); for (LogicalVolumeGroup lvg : list) { info.add(" " + lvg.toString()); } } }
printLVgroups
7,644
void (FileSystem fileSystem) { info.add("File System:"); info.add(String.format(" File Descriptors: %d/%d", fileSystem.getOpenFileDescriptors(), fileSystem.getMaxFileDescriptors())); for (OSFileStore fs : fileSystem.getFileStores()) { long usable = fs.getUsableSpace(); long total = fs.getTotalSpace(); info.add(String.format( " %s (%s) [%s] %s of %s free (%.1f%%), %s of %s files free (%.1f%%) is %s " + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s") + " and is mounted at %s", fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(), FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total, FormatUtil.formatValue(fs.getFreeInodes(), ""), FormatUtil.formatValue(fs.getTotalInodes(), ""), 100d * fs.getFreeInodes() / fs.getTotalInodes(), fs.getVolume(), fs.getLogicalVolume(), fs.getMount())); } }
printFileSystem
7,645
void (List<NetworkIF> list) { StringBuilder sb = new StringBuilder("Network Interfaces:"); if (list.isEmpty()) { sb.append(" Unknown"); } else { for (NetworkIF net : list) { if (net.getIfAlias() != null) { sb.append("\n ").append(net); } } } info.add(sb.toString()); }
printNetworkInterfaces
7,646
void (NetworkParams networkParams) { info.add("Network parameters:\n " + networkParams.toString()); }
printNetworkParameters
7,647
void (List<Display> list) { info.add("Displays:"); int i = 0; for (Display display : list) { info.add(" Display " + i + ":"); info.add(String.valueOf(display)); i++; } }
printDisplays
7,648
void (List<GraphicsCard> list) { info.add("Graphics Cards:"); if (list.isEmpty()) { info.add(" None detected."); } else { for (GraphicsCard card : list) { info.add(" " + card); } } }
printGraphicsCards
7,649
String () { return "Hardware"; }
toString
7,650
ScriptRunner (@Nullable PlaybackCommandReporter scriptRunnerReporter) { myScriptRunnerReporter = scriptRunnerReporter; return this; }
setScriptRunnerReporter
7,651
void (@NotNull final Project project, @NotNull String text, @Nullable File workingDir) { PlaybackRunnerExtended runner = new PlaybackRunnerExtended(text, new CommandLogger(), project); runner.setScriptDir(workingDir); runner.setCommandStartStopProcessor(myScriptRunnerReporter != null ? myScriptRunnerReporter : SystemProperties.getBooleanProperty(ReporterCommandAsTelemetrySpan.USE_SPAN_WRAPPER_FOR_COMMAND, false) ? new ReporterCommandAsTelemetrySpan(new ReporterWithTimer()) : new ReporterWithTimer()); Task.Backgroundable task = new Task.Backgroundable(project, PerformanceTestingBundle.message("task.title.executing.performance.script")) { @Override public void run(@NotNull ProgressIndicator indicator) { CountDownLatch countDownLatch = new CountDownLatch(1); runner.run().whenComplete((o, throwable) -> { countDownLatch.countDown(); }); final ScheduledExecutorService myExecutor = ConcurrencyUtil.newSingleScheduledThreadExecutor("Performance plugin script runner"); myExecutor.scheduleWithFixedDelay(() -> { if (indicator.isCanceled()) { runner.stop(); } }, 0, 100, TimeUnit.MILLISECONDS); try { countDownLatch.await(); } catch (InterruptedException ignored) { } myExecutor.shutdownNow(); } }; ProgressManager.getInstance().run(task); }
doRunScript
7,652
void (@NotNull ProgressIndicator indicator) { CountDownLatch countDownLatch = new CountDownLatch(1); runner.run().whenComplete((o, throwable) -> { countDownLatch.countDown(); }); final ScheduledExecutorService myExecutor = ConcurrencyUtil.newSingleScheduledThreadExecutor("Performance plugin script runner"); myExecutor.scheduleWithFixedDelay(() -> { if (indicator.isCanceled()) { runner.stop(); } }, 0, 100, TimeUnit.MILLISECONDS); try { countDownLatch.await(); } catch (InterruptedException ignored) { } myExecutor.shutdownNow(); }
run
7,653
void () { super.setRejected(); try { Profiler.getCurrentProfilerHandler().stopProfiling(new ArrayList<>()); } catch (Exception ignored) { } final Notification errorNotification = new Notification(PlaybackRunnerExtended.NOTIFICATION_GROUP, PerformanceTestingBundle.message("callback.stop"), errorText(), NotificationType.ERROR); Notifications.Bus.notify(errorNotification); }
setRejected
7,654
String () { return Strings.notNullize(getError()); }
errorText
7,655
DataContext (@NotNull Editor editor) { Editor hostEditor = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor; DataContext parent = DataManager.getInstance().getDataContext(editor.getContentComponent()); return SimpleDataContext.builder() .setParent(parent) .add(CommonDataKeys.HOST_EDITOR, hostEditor) .add(CommonDataKeys.EDITOR, editor) .build(); }
createEditorContext
7,656
void (Path jsonPath, String name, @Nullable Integer value, @Nullable Long startTime) { String stringToWrite; if (value != null && startTime != null) { stringToWrite = String.format("{\"%s_count\":%d,\"%1$s_time\":%d}", name, value, System.currentTimeMillis() - startTime); } else if (startTime != null) { stringToWrite = String.format("{\"%s_time\":%d}", name, System.currentTimeMillis() - startTime); } else if (value != null) { stringToWrite = String.format("{\"%s_count\":%d}", name, value); } else { LOG.error("value or startTime has to be provided"); return; } try { File file = jsonPath.toFile(); if (file.length() != 0) { String fileContent = String.valueOf(FileUtil.loadFileText(file)).replace("\n", "").replace("\t", ""); stringToWrite = new String(fileContent.substring(0, fileContent.length() - 1) + stringToWrite.replace("{", ",")); } FileUtil.writeToFile(file, stringToWrite); } catch (IOException ex) { LOG.error("Could not create json file " + jsonPath + " with the performance metrics."); } } }
writeMetricsToJson
7,657
void (@Nullable Project project) { isCanceled = false; timer.start(); }
startOfScript
7,658
void () { isCanceled = true; }
scriptCanceled
7,659
void (@Nullable Project project) { timer.stop(); ApplicationManager .getApplication() .invokeLater(() -> { Notifications.Bus.notify(getDelayNotification(timer.getTotalTime(), timer.getAverageDelay(), timer.getLongestDelay()), project); if (!isCanceled && ProfilersController.getInstance().isStoppedByScript()) { new FinishScriptDialog(project).show(); } }); }
endOfScript
7,660
Notification (long totalTime, long averageDelay, long maxDelay) { return new Notification(PlaybackRunnerExtended.NOTIFICATION_GROUP, PerformanceTestingBundle.message("delay.notification.title"), PerformanceTestingBundle.message("delay.notification.message", totalTime, averageDelay, maxDelay), NotificationType.INFORMATION); }
getDelayNotification
7,661
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback callback = createCallback(); try { execute(callback, context); } catch (Throwable throwable) { callback.reject(throwable.getMessage()); } return Promises.toPromise(callback); }
_execute
7,662
ActionCallback () { return new ActionCallbackProfilerStopper(); }
createCallback
7,663
Holder (VirtualFile file) { final Holder holder = new Holder(); VfsUtilCore.iterateChildrenRecursively(file, null, virtualFile -> { if (virtualFile.is(VFileProperty.SYMLINK) && !virtualFile.is(VFileProperty.HIDDEN)) { holder.setSymlink(); } if (!virtualFile.isDirectory()) { holder.increaseByOne(); } return true; }); return holder; }
analyzeFiles
7,664
String (boolean addGeneralInfo) { StringBuilder output = new StringBuilder(); FileEditorManagerImpl fileEditorManager = (FileEditorManagerImpl)FileEditorManager.getInstance(project); VirtualFile baseDir = ProjectUtil.guessProjectDir(project); if (baseDir != null) { Holder holder = analyzeFiles(baseDir); output.append("Filesystem Info:\n"); output.append("File system is case sensitive: ").append(baseDir.getFileSystem().isCaseSensitive()).append('\n'); output.append("File is case sensitive: ").append(baseDir.isCaseSensitive()).append('\n'); output.append("Are there symlinks: ").append(holder.isSymlink()).append('\n'); output.append("Number of files: ").append(holder.getNumOfFiles()).append('\n'); output.append('\n'); } output.append("Project Info:\n"); output.append("Number of opened files: ").append(fileEditorManager.getOpenedFiles().size()).append('\n'); ReadAction.run(() -> { Editor selectedTextEditor = fileEditorManager.getSelectedTextEditor(true); if (selectedTextEditor != null) { Document document = selectedTextEditor.getDocument(); output.append("File size (in lines): ").append(document.getLineCount()).append('\n'); output.append("File size in characters: ").append(document.getTextLength()).append('\n'); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); if (psiFile != null) { output.append("Number of injections: ") .append(InjectedLanguageManager.getInstance(project).getCachedInjectedDocumentsInRange(psiFile, psiFile .getTextRange()).size()).append('\n'); } } }); if (addGeneralInfo) { output.append('\n'); output.append(new CompositeGeneralTroubleInfoCollector().collectInfo(project)); } return output.toString(); }
collectMetrics
7,665
boolean () { return isSymlink; }
isSymlink
7,666
void () { isSymlink = true; }
setSymlink
7,667
int () { return numOfFiles; }
getNumOfFiles
7,668
void () { numOfFiles++; }
increaseByOne
7,669
Promise<Object> (final @NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); String input = extractCommandArgument(PREFIX); try { pressKey(EditorKey.valueOf(input), context.getProject()); actionCallback.setDone(); } catch (Throwable e) { actionCallback.reject(e.getMessage()); } return Promises.toPromise(actionCallback); }
_execute
7,670
void (EditorKey editorKey, Project project) { String actionID = editorKey.action; Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { ApplicationManager.getApplication().runWriteAction(Context.current().wrap(() -> { TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, DelayTypeCommand.SPAN_NAME, span -> { AnAction action = ActionManagerEx.getInstanceEx().getAction(actionID); AnActionEvent actionEvent = AnActionEvent.createFromAnAction(action, null, "", EditorUtils.createEditorContext(editor)); ActionUtil.performDumbAwareWithCallbacks(action, actionEvent, () -> { CommandProcessor.getInstance().executeCommand(project, () -> { action.actionPerformed(actionEvent); }, "", null, editor.getDocument()); }); span.addEvent("Typing " + actionID); }); })); } else { throw new IllegalStateException("Editor is not opened"); } }
pressKey
7,671
Promise<Object> (@NotNull PlaybackContext context) { ActionCallback myActionCallback = new ActionCallbackProfilerStopper(); ReformatCodeProcessor codeProcessor = new ReformatCodeProcessor(context.getProject(), false); codeProcessor.setPostRunnable(() -> { context.message(PerformanceTestingBundle.message("command.reformat.finish"), getLine()); myActionCallback.setDone(); }); ApplicationManager.getApplication().invokeLater(() -> codeProcessor.run()); return Promises.toPromise(myActionCallback); }
_execute
7,672
void (@NotNull ActionCallback callback, @NotNull PlaybackContext context) { writeExitMetricsIfNeeded(); String[] arguments = getText().split(" ", 2); ApplicationManager.getApplication().executeOnPooledThread(() -> { try { TimeUnit.SECONDS.sleep(Long.parseLong(arguments[1])); ApplicationManager.getApplication().exit(true, true, false); callback.setDone(); } catch (InterruptedException e) { callback.reject(e.getMessage()); } }); }
execute
7,673
Promise<Object> (@NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); final MessageBusConnection busConnection = context.getProject().getMessageBus().connect(); busConnection.subscribe(PowerSaveMode.TOPIC, () -> actionCallback.setDone()); ApplicationManager.getApplication().invokeAndWait(() -> { PowerSaveMode.setEnabled(true); }); return Promises.toPromise(actionCallback); }
_execute
7,674
void () { }
dispose
7,675
String () { return PREFIX + getName(); }
getPrefix
7,676
Boolean () { return extractCommandArgument(getPrefix()).contains("WARMUP"); }
isWarmupMode
7,677
Boolean () { return extractCommandArgument(getPrefix()).contains("ENABLE_SYSTEM_METRICS"); }
systemMetricsEnabled
7,678
SpanBuilder (SpanBuilder spanBuilder) { if (systemMetricsEnabled()) { return new SpanBuilderWithSystemInfoAttributes(spanBuilder); } return spanBuilder; }
wrapIfNeed
7,679
Span (String name) { SpanBuilder spanBuilder = wrapIfNeed(tracer.spanBuilder(name)); return spanBuilder.startSpan(); }
startSpan
7,680
Promise<Object> (@NotNull final PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); String extension = extractCommandArgument(PREFIX); @NotNull Project project = context.getProject(); DumbService.getInstance(project).smartInvokeLater(() -> { InspectionManagerEx inspectionManagerEx = (InspectionManagerEx)InspectionManager.getInstance(project); //noinspection TestOnlyProblems GlobalInspectionContextImpl inspectionContext = new GlobalInspectionContextImpl(project, inspectionManagerEx.getContentManager()) { @Override protected void notifyInspectionsFinished(@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); context.message(PerformanceTestingBundle.message("command.inspection.finish"), getLine()); actionCallback.setDone(); } }; //set up list of files AnalysisScope scope = getAnalysisScope(extension, project); if (scope == null) { context.message(PerformanceTestingBundle.message("command.inspection.extension") + " " + extension, getLine()); } else { inspectionContext.doInspections(scope); } }); return Promises.toPromise(actionCallback); }
_execute
7,681
void (@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); context.message(PerformanceTestingBundle.message("command.inspection.finish"), getLine()); actionCallback.setDone(); }
notifyInspectionsFinished
7,682
AnalysisScope (String extension, @NotNull Project project) { AnalysisScope scope; if (extension.isEmpty()) { scope = new AnalysisScope(project); } else { Collection<VirtualFile> files = getFiles(extension, project); if (files.isEmpty()) { return null; } scope = new AnalysisScope(project, getFiles(extension, project)); } return scope; }
getAnalysisScope
7,683
Collection<VirtualFile> (@NotNull final String extension, @NotNull Project project) { final Collection<VirtualFile> files = new HashSet<>(100); FileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); index.iterateContent(fileOrDir -> { if (StringUtil.equals(fileOrDir.getExtension(), extension)) { files.add(fileOrDir); } return true; }); return files; }
getFiles
7,684
Editor (PlaybackContext context) { TypingTarget typingTarget = findTarget(context); if (typingTarget == null) throw new IllegalStateException("typingTarget is null"); if (!(typingTarget instanceof EditorComponentImpl)) throw new IllegalStateException("typingTarget is not EditorComponentImpl, but " + typingTarget.getClass()); return ((EditorComponentImpl) typingTarget).getEditor(); }
getEditor
7,685
Promise<Object> (final @NotNull PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); Project project = context.getProject(); String[] args = getArgs(); final String tab = myOptions.tab; final String insertText = args.length > 1 ? args[1] : ""; Ref<String> tabId = new Ref<>(); switch (tab) { case "text" -> tabId.set(TextSearchContributor.class.getSimpleName()); case "file" -> tabId.set(FileSearchEverywhereContributor.class.getSimpleName()); case "class" -> tabId.set(ClassSearchEverywhereContributor.class.getSimpleName()); case "action" -> tabId.set(ActionSearchEverywhereContributor.class.getSimpleName()); case "symbol" -> tabId.set(SymbolSearchEverywhereContributor.class.getSimpleName()); case "all" -> tabId.set(SearchEverywhereManagerImpl.ALL_CONTRIBUTORS_GROUP_ID); default -> throw new RuntimeException("Tab is not set"); } LOG.info(tabId.get()); int numberOfPermits; if(insertText.isEmpty() && myOptions.typingText.isEmpty()){ numberOfPermits = 1; //we don't wait for any text insertion } else if(!insertText.isEmpty() && !myOptions.typingText.isEmpty()){ numberOfPermits = -1; //we wait till both operations are finished } else { numberOfPermits = 0; //we wait till one operation is finished } Semaphore typingSemaphore = new Semaphore(numberOfPermits); TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, "searchEverywhere", globalSpan -> { ApplicationManager.getApplication().invokeAndWait(Context.current().wrap(() -> { try { TypingTarget target = findTarget(context); Component component; if(!(target instanceof EditorComponentImpl)){ LOG.info("Editor is not opened, focus owner will be used."); component = IdeFocusManager.getInstance(project).getFocusOwner(); } else{ component = (EditorComponentImpl) target; } DataContext dataContext = DataManager.getInstance().getDataContext(component); IdeEventQueue.getInstance().getPopupManager().closeAllPopups(false); AnActionEvent actionEvent = AnActionEvent.createFromDataContext(ActionPlaces.EDITOR_POPUP, null, dataContext); if(actionEvent.getProject() == null && !(tab.equals("action") || tab.equals("all"))) { actionCallback.reject("Project is null, SE requires project to show any tab except actions."); } TraceUtil.runWithSpanThrows(PerformanceTestSpan.TRACER, "searchEverywhere_dialog_shown", dialogSpan -> { var manager = SearchEverywhereManager.getInstance(project); manager.show(tabId.get(), "", actionEvent); attachSearchListeners(manager.getCurrentlyShownUI()); }); if (!insertText.isEmpty()) { insertText(context.getProject(), insertText, typingSemaphore); } if (!myOptions.typingText.isEmpty()) { typeText(context.getProject(), myOptions.typingText, typingSemaphore); } } catch (Exception e) { LOG.error(e); } })); try { typingSemaphore.acquire(); SearchEverywhereUI ui = SearchEverywhereManager.getInstance(project).getCurrentlyShownUI(); if (myOptions.close) { ApplicationManager.getApplication().invokeAndWait(() -> ui.closePopup()); } if (myOptions.selectFirst) { WriteAction.runAndWait(() -> { ApplicationManager.getApplication().invokeAndWait(() -> ui.selectFirst()); }); } } catch (InterruptedException e) { LOG.error(e); } finally { actionCallback.setDone(); } }); return Promises.toPromise(actionCallback); }
_execute
7,686
String[] () { return getArgs(PREFIX); }
getArgs
7,687
String[] (String prefix) { String input = extractCommandArgument(prefix); String[] args = input.split("\\|"); Args.parse(myOptions, args[0].split(" ")); return args; }
getArgs
7,688
void (Project project, String insertText, Semaphore typingSemaphore) { SearchEverywhereUI ui = SearchEverywhereManager.getInstance(project).getCurrentlyShownUI(); Span insertSpan = PerformanceTestSpan.TRACER.spanBuilder("searchEverywhere_items_loaded").startSpan(); Span firstBatchAddedSpan = PerformanceTestSpan.TRACER.spanBuilder("searchEverywhere_first_elements_added").startSpan(); ui.addSearchListener(new SearchAdapter(){ @Override public void elementsAdded(@NotNull List<? extends SearchEverywhereFoundElementInfo> list) { super.elementsAdded(list); firstBatchAddedSpan.setAttribute("number", list.size()); firstBatchAddedSpan.end(); } }); //noinspection TestOnlyProblems Future<List<Object>> elements = ui.findElementsForPattern(insertText); ApplicationManager.getApplication().executeOnPooledThread(Context.current().wrap((Callable<Object>)() -> { insertSpan.setAttribute("text", insertText); List<Object> result = elements.get(); insertSpan.setAttribute("number", result.size()); insertSpan.end(); typingSemaphore.release(); return result; })); }
insertText
7,689
void (@NotNull List<? extends SearchEverywhereFoundElementInfo> list) { super.elementsAdded(list); firstBatchAddedSpan.setAttribute("number", list.size()); firstBatchAddedSpan.end(); }
elementsAdded
7,690
void (Project project, String typingText, Semaphore typingSemaphore) { SearchEverywhereUI ui = SearchEverywhereManager.getInstance(project).getCurrentlyShownUI(); Document document = ui.getSearchField().getDocument(); Semaphore oneLetterLock = new Semaphore(1); ThreadPoolExecutor typing = ConcurrencyUtil.newSingleThreadExecutor("Performance plugin delayed type"); Ref<Boolean> isTypingFinished = new Ref<>(false); Ref<Span> oneLetterSpan = new Ref<>(); Ref<Span> firstBatchAddedSpan = new Ref<>(); ui.addSearchListener(new SearchAdapter() { @Override public void elementsAdded(@NotNull List<? extends SearchEverywhereFoundElementInfo> list) { firstBatchAddedSpan.get().setAttribute("number", list.size()); firstBatchAddedSpan.get().end(); } @Override public void searchFinished(@NotNull List<Object> items) { super.searchFinished(items); oneLetterLock.release(); oneLetterSpan.get().setAttribute("number", items.size()); oneLetterSpan.get().end(); if (isTypingFinished.get()) { typingSemaphore.release(); typing.shutdown(); } } }); for (int i = 0; i < typingText.length(); i++) { final int index = i; typing.execute(Context.current().wrap(() -> { try { oneLetterLock.acquire(); } catch (InterruptedException e) { throw new RuntimeException(e); } ApplicationManager.getApplication().invokeAndWait(Context.current().wrap(() -> { try { char currentChar = typingText.charAt(index); oneLetterSpan.set( PerformanceTestSpan.TRACER.spanBuilder("searchEverywhere_items_loaded").startSpan() .setAttribute("text", String.valueOf(currentChar))); firstBatchAddedSpan.set(PerformanceTestSpan.TRACER.spanBuilder("searchEverywhere_first_elements_added").startSpan()); document.insertString(document.getLength(), String.valueOf(currentChar), null); if (index == typingText.length() - 1) { isTypingFinished.set(true); } } catch (BadLocationException e) { throw new RuntimeException(e); } })); })); } }
typeText
7,691
void (@NotNull List<? extends SearchEverywhereFoundElementInfo> list) { firstBatchAddedSpan.get().setAttribute("number", list.size()); firstBatchAddedSpan.get().end(); }
elementsAdded
7,692
void (@NotNull List<Object> items) { super.searchFinished(items); oneLetterLock.release(); oneLetterSpan.get().setAttribute("number", items.size()); oneLetterSpan.get().end(); if (isTypingFinished.get()) { typingSemaphore.release(); typing.shutdown(); } }
searchFinished
7,693
void (@NotNull SearchEverywhereUI ui) {}
attachSearchListeners
7,694
Promise<Object> (@NotNull final PlaybackContext context) { final ActionCallback actionCallback = new ActionCallbackProfilerStopper(); final String[] commandArguments = extractCommandArgument(PREFIX).split("\\s+", 2); String shortInspectionName = commandArguments[0]; String extension = ""; if (commandArguments.length > 1) { extension = commandArguments[1]; } @NotNull Project project = context.getProject(); final InspectionProfile currentProfile = InspectionProjectProfileManager.getInstance(project).getCurrentProfile(); final InspectionToolWrapper toolWrapper = currentProfile.getInspectionTool(shortInspectionName, project); InspectionManagerEx inspectionManagerEx = (InspectionManagerEx)InspectionManager.getInstance(project); if (toolWrapper != null) { final InspectionProfileImpl model = RunInspectionIntention.createProfile(toolWrapper, inspectionManagerEx, null); //noinspection TestOnlyProblems GlobalInspectionContextImpl inspectionContext = new GlobalInspectionContextImpl(project, inspectionManagerEx.getContentManager()) { private long numberOfProblems = 0; @Override protected void notifyInspectionsFinished(@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); try { File tempDirectory = FileUtil.createTempDirectory("inspection", "result"); final InspectionResultsView view = getView(); if (view != null) { ExportToXMLActionKt.dumpToXml(view.getCurrentProfile(), view.getTree(), view.getProject(), view.getGlobalInspectionContext(), tempDirectory.toPath()); File[] files = tempDirectory.listFiles(); if (files != null) { for (File file : files) { if (file.isHidden()) { continue; } Path path = file.toPath(); try (Stream<String> lines = Files.lines(path).filter(line -> line.contains("<problem>"))) { this.numberOfProblems = lines.count(); } } } else { LOGGER.error("tempDirectory.listFiles() is null"); } } } catch (IOException ex) { LOGGER.error(ex); } context.message(PerformanceTestingBundle.message("command.inspection.finish") + " " + PerformanceTestingBundle.message("command.inspection.finish.result", this.numberOfProblems), getLine()); actionCallback.setDone(); } }; inspectionContext.setExternalProfile(model); AnalysisScope scope = InspectionCommand.getAnalysisScope(extension, project); if (scope == null) { context.message(PerformanceTestingBundle.message("command.inspection.extension") + " " + extension, getLine()); } else { inspectionContext.doInspections(scope); } } else { actionCallback.reject(PerformanceTestingBundle.message("command.singleInspection.noinspection", shortInspectionName)); } return Promises.toPromise(actionCallback); }
_execute
7,695
void (@NotNull AnalysisScope scope) { super.notifyInspectionsFinished(scope); try { File tempDirectory = FileUtil.createTempDirectory("inspection", "result"); final InspectionResultsView view = getView(); if (view != null) { ExportToXMLActionKt.dumpToXml(view.getCurrentProfile(), view.getTree(), view.getProject(), view.getGlobalInspectionContext(), tempDirectory.toPath()); File[] files = tempDirectory.listFiles(); if (files != null) { for (File file : files) { if (file.isHidden()) { continue; } Path path = file.toPath(); try (Stream<String> lines = Files.lines(path).filter(line -> line.contains("<problem>"))) { this.numberOfProblems = lines.count(); } } } else { LOGGER.error("tempDirectory.listFiles() is null"); } } } catch (IOException ex) { LOGGER.error(ex); } context.message(PerformanceTestingBundle.message("command.inspection.finish") + " " + PerformanceTestingBundle.message("command.inspection.finish.result", this.numberOfProblems), getLine()); actionCallback.setDone(); }
notifyInspectionsFinished
7,696
String () { return PREFIX; }
getSpanName
7,697
String () { return IdeActions.GROUP_MAIN_MENU; }
getGroupId
7,698
String () { return ActionPlaces.MAIN_MENU; }
getPlace
7,699
String (Iterator<String> args, @NotNull String text) { if (!args.hasNext()) throw new RuntimeException("Too few arguments in " + text); return args.next(); }
nextArg