@tool
class_name GDLintPlugin extends EditorPlugin

# If you've installed gdlint in a venv, you may want to overwrite this
const GDLINT: String = "gdlint"


func _enter_tree() -> void:
	assert(not OS.execute(GDLINT, ["-h"]), "Could not find gdLint binary at {0}".format([GDLINT]))
	resource_saved.connect(on_save)


func _exit_tree() -> void:
	resource_saved.disconnect(on_save)


func on_save(resource: Resource) -> void:
	# Run linting when a script resource is saved
	if resource is Script:
		var script: Script = resource
		var filepath: String = ProjectSettings.globalize_path(resource.resource_path)

		var script_editor = EditorInterface.get_script_editor()
		var code_editor: CodeEdit = (
			script_editor.get_current_editor().get_base_editor()
			if script_editor.get_current_script() == script
			else null
		)

		var gdlint_output: Array[String] = []
		var error: int = OS.execute(GDLINT, [filepath], gdlint_output, true)
		if error:
			push_warning("gdLint:\n" + gdlint_output[0])
