intellij: remove custom tooling

- The patch hasn't applied in a long time, and nobody has complained,
  so it would appear that the patch is no longer necessary.

- localconfig and run configs are unused/unmaintained.

Change-Id: I6a6a6964d58dac6b7f2e749059716edf98ac129f
Reviewed-on: https://review.monogon.dev/c/monogon/+/4404
Reviewed-by: Tim Windelschmidt <tim@monogon.tech>
Tested-by: Jenkins CI
diff --git a/.bazelproject b/.bazelproject
index 6fb7b67..83a7607 100644
--- a/.bazelproject
+++ b/.bazelproject
@@ -20,17 +20,3 @@
   # python
   # scala
   # typescript
-
-import_run_configurations:
-  intellij/run/Connect_to_dlv_on__2345.xml
-
-  intellij/run/e2e_test.xml
-  intellij/run/e2e_test_in_dbg_mode.xml
-  intellij/run/e2e_test_in_dbg_mode_with_dlv.xml
-
-  intellij/run/Run__gazelle.xml
-
-  intellij/run/Run_all_tests.xml
-
-  intellij/run/Run_single_node_cluster.xml
-  intellij/run/Run_single_node_cluster_in_dbg_mode.xml
diff --git a/SETUP.md b/SETUP.md
index 908ed0e..9d0113f 100644
--- a/SETUP.md
+++ b/SETUP.md
@@ -104,7 +104,8 @@
 
 - Install the [Bazel](https://plugins.jetbrains.com/plugin/8609-bazel),
   Go and Protocol Buffer plugins in IntelliJ.
-- Make sure that Bazel "*Bazel Binary Location*" in Other Settings → Bazel Settings points to Bazelisk.
+- Make sure that Bazel "*Bazel Binary Location*" in Other Settings → Bazel Settings points to Bazelisk
+  (or tools/bazel, if you're on NixOS).
 - Use _File → Import Bazel project_... and select your monorepo checkout.
 
 After running the first sync (Alt-Y), everything should now resolve in the IDE, including generated code.
diff --git a/intellij/README.md b/intellij/README.md
deleted file mode 100644
index 97c1d78..0000000
--- a/intellij/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# `//intellij`
-
-Supporting infrastructure for using the Bazel IntelliJ plugin with our monorepo.
diff --git a/intellij/localconfig/BUILD.bazel b/intellij/localconfig/BUILD.bazel
deleted file mode 100644
index 4a82aae..0000000
--- a/intellij/localconfig/BUILD.bazel
+++ /dev/null
@@ -1,15 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
-
-go_library(
-    name = "localconfig_lib",
-    srcs = ["localconfig.go"],
-    importpath = "source.monogon.dev/intellij/localconfig",
-    visibility = ["//visibility:private"],
-    deps = ["//intellij/localconfig/watchers"],
-)
-
-go_binary(
-    name = "localconfig",
-    embed = [":localconfig_lib"],
-    visibility = ["//visibility:public"],
-)
diff --git a/intellij/localconfig/localconfig.go b/intellij/localconfig/localconfig.go
deleted file mode 100644
index 9c43d0f..0000000
--- a/intellij/localconfig/localconfig.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright The Monogon Project Authors.
-// SPDX-License-Identifier: Apache-2.0
-
-// localconfig modifies the project's IntelliJ config to include project-specific
-// settings. This is usually done by checking in the .idea directory, but we do not
-// want to do this: it conflicts with the Bazel plugin's way of conducting its
-// workspace business, lacks backwards compatibility, and is a common source of
-// spurious Git diffs, especially when the IDE/JDK/random plugins are updated and
-// team members run different versions.
-//
-// Instead, we use the officially supported way of shipping IntelliJ Bazel project
-// configs - a .bazelproject file that can be imported using the Bazel project
-// import wizard, with local configs. We then use this tool to mangle the local
-// configs to add additional custom configuration beyond run configurations. This
-// avoids merge conflicts and allows us to intelligently handle schema changes.
-package main
-
-import (
-	"log"
-	"os"
-	"path"
-
-	"source.monogon.dev/intellij/localconfig/watchers"
-)
-
-func main() {
-	if len(os.Args) != 2 {
-		log.Fatal("usage: localconfig <project dir>")
-	}
-
-	projectDir := os.Args[1]
-	if _, err := os.Stat(path.Join(projectDir, ".ijwb")); err != nil {
-		log.Fatalf("invalid project dir: %v", err)
-	}
-
-	if err := watchers.RewriteConfig(projectDir); err != nil {
-		log.Fatal(err)
-	}
-}
diff --git a/intellij/localconfig/watchers/BUILD.bazel b/intellij/localconfig/watchers/BUILD.bazel
deleted file mode 100644
index 1571fdf..0000000
--- a/intellij/localconfig/watchers/BUILD.bazel
+++ /dev/null
@@ -1,8 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library")
-
-go_library(
-    name = "watchers",
-    srcs = ["filewatchers.go"],
-    importpath = "source.monogon.dev/intellij/localconfig/watchers",
-    visibility = ["//visibility:public"],
-)
diff --git a/intellij/localconfig/watchers/filewatchers.go b/intellij/localconfig/watchers/filewatchers.go
deleted file mode 100644
index b16ad9d..0000000
--- a/intellij/localconfig/watchers/filewatchers.go
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright The Monogon Project Authors.
-// SPDX-License-Identifier: Apache-2.0
-
-package watchers
-
-import (
-	"encoding/xml"
-	"fmt"
-	"os"
-	"path"
-)
-
-const (
-	fileWatchersPath = ".ijwb/.idea/watcherTasks.xml"
-	templatePath     = "intellij/localconfig/data/watcherTasks.xml"
-)
-
-type config struct {
-	XMLName   xml.Name  `xml:"project"`
-	Version   string    `xml:"version,attr"`
-	Component component `xml:"component"`
-}
-
-type component struct {
-	Name        string       `xml:"name,attr"`
-	TaskOptions []taskOption `xml:"TaskOptions"`
-}
-
-type taskOption struct {
-	IsEnabled string `xml:"isEnabled,attr"`
-	Option    []struct {
-		Name  string `xml:"name,attr"`
-		Value string `xml:"value,attr,omitempty"`
-		Data  string `xml:",innerxml"`
-	} `xml:"option"`
-	Envs struct {
-		Env []struct {
-			Name  string `xml:"name,attr"`
-			Value string `xml:"value,attr"`
-		} `xml:"env"`
-	} `xml:"envs"`
-}
-
-func buildConfig(options []taskOption) *config {
-	return &config{
-		XMLName: xml.Name{Local: "project"},
-		Version: "4",
-		Component: component{
-			Name:        "ProjectTasksOptions",
-			TaskOptions: options,
-		},
-	}
-}
-
-func readConfig(filename string) (cfg *config, err error) {
-	b, err := os.ReadFile(filename)
-	if err != nil {
-		return nil, fmt.Errorf("failed reading file: %w", err)
-	}
-
-	err = xml.Unmarshal(b, &cfg)
-	if err != nil {
-		return nil, fmt.Errorf("failed deserializing XML: %w", err)
-	}
-
-	return
-}
-
-func (cfg *config) atomicWriteFile(filename string) error {
-	b, err := xml.MarshalIndent(cfg, "", "  ")
-	if err != nil {
-		return fmt.Errorf("failed to serialize: %w", err)
-	}
-
-	// Atomic write is needed, IntelliJ has inotify watches on its config and reloads
-	// (but not applies) instantly.
-	tmpPath := filename + ".tmp"
-	defer os.Remove(tmpPath)
-	if err := os.WriteFile(tmpPath, []byte(xml.Header+string(b)), 0664); err != nil {
-		return fmt.Errorf("failed to write: %w", err)
-	}
-	if err := os.Rename(tmpPath, filename); err != nil {
-		return fmt.Errorf("failed to rename: %w", err)
-	}
-
-	return nil
-}
-
-// RewriteConfig adds our watchers to projectDir's watchers config, overwriting
-// existing entries with the same name.
-func RewriteConfig(projectDir string) error {
-	template, err := readConfig(path.Join(projectDir, templatePath))
-	if err != nil {
-		return fmt.Errorf("failed reading template config: %w", err)
-	}
-
-	if template.Version != "4" {
-		return fmt.Errorf("unknown template config version: %s", template.Version)
-	}
-
-	// Read existing tasks, if any.
-	tasks := make(map[string]taskOption)
-	cfg, err := readConfig(path.Join(projectDir, fileWatchersPath))
-
-	switch {
-	case err == nil:
-		// existing config, read tasks
-		if cfg.Version != "4" {
-			return fmt.Errorf("unknown watchers config version: %s", cfg.Version)
-		}
-		for _, v := range cfg.Component.TaskOptions {
-			for _, o := range v.Option {
-				if o.Name == "name" {
-					tasks[o.Value] = v
-				}
-			}
-		}
-	case os.IsNotExist(err):
-		// no existing config - continue with empty tasks
-	default:
-		// error is non-nil and not an ENOENT
-		return fmt.Errorf("failed reading existing config: %w", err)
-	}
-
-	// Overwrite "our" entries, identified by name.
-	for _, v := range template.Component.TaskOptions {
-		for _, o := range v.Option {
-			if o.Name == "name" {
-				tasks[o.Value] = v
-			}
-		}
-	}
-
-	// Build new configuration
-	options := make([]taskOption, 0, len(tasks))
-	for _, t := range tasks {
-		options = append(options, t)
-	}
-
-	out := buildConfig(options)
-
-	err = out.atomicWriteFile(path.Join(projectDir, fileWatchersPath))
-	if err != nil {
-		return fmt.Errorf("failed writing to output file: %w", err)
-	}
-
-	return nil
-}
diff --git a/intellij/patches/bazel_intellij_aspect_filter.patch b/intellij/patches/bazel_intellij_aspect_filter.patch
deleted file mode 100644
index 01642cd..0000000
--- a/intellij/patches/bazel_intellij_aspect_filter.patch
+++ /dev/null
@@ -1,60 +0,0 @@
-Copyright 2020 The Monogon Project Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-  http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-
-# We need to patch the IntelliJ Bazel aspect that is injected via the @intellij_bazel repository
-# to:
-#  - properly resolve go_library rules that have both source files and embeds.
-#  - allow running test/sync against //... which contains cc_toolchain rules
-#    (see https://github.com/bazelbuild/intellij/issues/1344 )
---- a/intellij_info_impl_bundled.bzl
-+++ b/intellij_info_impl_bundled.bzl
-@@ -13,6 +13,7 @@
-     ":make_variables.bzl",
-     "expand_make_variables",
- )
-+load("@io_bazel_rules_go//go:def.bzl", "GoLibrary")
-
- # Defensive list of features that can appear in the C++ toolchain, but which we
- # definitely don't want to enable (when enabled, they'd contribute command line
-@@ -350,6 +351,8 @@
-         "go_appengine_test",
-     ]:
-         sources = [f for src in getattr(ctx.rule.attr, "srcs", []) for f in src.files.to_list()]
-+        sources += [f for embed in getattr(ctx.rule.attr, "embed", []) for f in _collect_generated_go_sources(embed, ctx, semantics) or []]
-+
-         generated = [f for f in sources if not f.is_source]
-     elif ctx.rule.kind == "go_wrap_cc":
-         genfiles = target.files.to_list()
-@@ -372,6 +375,10 @@
-     if go_semantics:
-         import_path = go_semantics.get_import_path(ctx)
-
-+    if import_path == None and getattr(ctx.rule.attr, "embed", None) != None and ctx.rule.kind == "go_library":
-+        embed_attr = getattr(ctx.rule.attr, "embed", None)
-+        import_path = embed_attr[0][GoLibrary].importpath
-+
-     library_labels = []
-     if ctx.rule.kind == "go_test" or ctx.rule.kind == "go_appengine_test":
-         if getattr(ctx.rule.attr, "library", None) != None:
-@@ -457,6 +464,8 @@
-         return False
-     if cc_common.CcToolchainInfo not in target:
-         return False
-+    if type(target[cc_common.CcToolchainInfo]) != 'CcToolchainInfo':
-+        return False
- 
-     # cc toolchain to access compiler flags
-     cpp_toolchain = target[cc_common.CcToolchainInfo]
-
diff --git a/intellij/run/Connect_to_dlv_on__2345.xml b/intellij/run/Connect_to_dlv_on__2345.xml
deleted file mode 100644
index 960e1f5..0000000
--- a/intellij/run/Connect_to_dlv_on__2345.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="Connect to dlv on :2345" type="GoRemoteDebugConfigurationType" factoryName="Go Remote"><method v="2" /></configuration>
\ No newline at end of file
diff --git a/intellij/run/Run__gazelle.xml b/intellij/run/Run__gazelle.xml
deleted file mode 100644
index 31fa1e5..0000000
--- a/intellij/run/Run__gazelle.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration name="Run :gazelle" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeCommandGenericRunConfigurationHandlerProvider" blaze-command="run" kind="sh_binary"><blaze-target>//:gazelle</blaze-target><blaze-user-exe-flag>update</blaze-user-exe-flag></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
\ No newline at end of file
diff --git a/intellij/run/Run_all_tests.xml b/intellij/run/Run_all_tests.xml
deleted file mode 100644
index bff183d..0000000
--- a/intellij/run/Run_all_tests.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="Run all tests" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeCommandGenericRunConfigurationHandlerProvider" blaze-command="test"><blaze-target>//...</blaze-target></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
\ No newline at end of file
diff --git a/intellij/run/Run_single_node_cluster.xml b/intellij/run/Run_single_node_cluster.xml
deleted file mode 100644
index f18fc63..0000000
--- a/intellij/run/Run_single_node_cluster.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="Run single node cluster" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeCommandGenericRunConfigurationHandlerProvider" kind="go_test" blaze-command="run"><blaze-target>//:launch</blaze-target></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
\ No newline at end of file
diff --git a/intellij/run/Run_single_node_cluster_in_dbg_mode.xml b/intellij/run/Run_single_node_cluster_in_dbg_mode.xml
deleted file mode 100644
index 9ec752c..0000000
--- a/intellij/run/Run_single_node_cluster_in_dbg_mode.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="Run single node cluster in dbg mode" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeCommandGenericRunConfigurationHandlerProvider" kind="go_test" blaze-command="run"><blaze-target>//:launch</blaze-target><blaze-user-flag>--compilation_mode=dbg</blaze-user-flag></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
\ No newline at end of file
diff --git a/intellij/run/e2e_test.xml b/intellij/run/e2e_test.xml
deleted file mode 100644
index 0c45c56..0000000
--- a/intellij/run/e2e_test.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="e2e test" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeGoRunConfigurationHandlerProvider" kind="go_test" blaze-command="test"><blaze-target>//metropolis/test/e2e:go_default_test</blaze-target><blaze-user-flag>--test_output=streamed</blaze-user-flag></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
diff --git a/intellij/run/e2e_test_in_dbg_mode.xml b/intellij/run/e2e_test_in_dbg_mode.xml
deleted file mode 100644
index 578e76c..0000000
--- a/intellij/run/e2e_test_in_dbg_mode.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="e2e test in dbg mode" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeGoRunConfigurationHandlerProvider" kind="go_test" blaze-command="test"><blaze-target>//metropolis/test/e2e:go_default_test</blaze-target><blaze-user-flag>--test_output=streamed</blaze-user-flag><blaze-user-flag>--cache_test_results=no</blaze-user-flag><blaze-user-flag>--compilation_mode=dbg</blaze-user-flag><blaze-user-flag>--test_timeout=3600</blaze-user-flag></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
diff --git a/intellij/run/e2e_test_in_dbg_mode_with_dlv.xml b/intellij/run/e2e_test_in_dbg_mode_with_dlv.xml
deleted file mode 100644
index 49f775b..0000000
--- a/intellij/run/e2e_test_in_dbg_mode_with_dlv.xml
+++ /dev/null
@@ -1 +0,0 @@
-<configuration default="false" name="e2e test in dbg mode with dlv" type="BlazeCommandRunConfigurationType" factoryName="Bazel Command"><blaze-settings handler-id="BlazeGoRunConfigurationHandlerProvider" kind="go_test" blaze-command="test"><blaze-target>//metropolis/test/e2e:go_default_test</blaze-target><blaze-user-flag>--local_test_jobs=1</blaze-user-flag><blaze-user-flag>--runs_per_test=1</blaze-user-flag><blaze-user-flag>--test_output=streamed</blaze-user-flag><blaze-user-flag>--cache_test_results=no</blaze-user-flag><blaze-user-flag>--compilation_mode=dbg</blaze-user-flag><blaze-user-flag>--run_under="@//:dlv exec --continue --headless --accept-multiclient --listen=:2345 --api-version=2</blaze-user-flag></blaze-settings><method v="2"><option name="Blaze.BeforeRunTask" enabled="true" /></method></configuration>
diff --git a/tools/bazel b/tools/bazel
index ffc1dcd..1ff2694 100755
--- a/tools/bazel
+++ b/tools/bazel
@@ -55,86 +55,6 @@
   fi
 }
 
-intellij_patch() {
-  # When IntelliJ's Bazel plugin uses //scripts/bin/bazel to either build targets
-  # or run syncs, it adds a --override_repository flag to the bazel command
-  # line that points @intellij_aspect into a path on the filesystem. This
-  # external repository contains a Bazel Aspect definition which Bazel
-  # executes to provide the IntelliJ Bazel plugin with information about the
-  # workspace / build targets / etc...
-  #
-  # We need to patch the aspect definition to fix a number of bugs
-  # to make it work with the Monogon monorepo.
-
-  # Find all IntelliJ installation/config directories.
-  local ij_home_paths=("${HOME}/.local/share/JetBrains/IntelliJIdea"*)
-  # Get the newest one, if any.
-  local ij_home=""
-  if ! [[  ${#ij_home_paths[@]} -eq 0 ]]; then
-      # Reverse sort paths by name, with the first being the newest IntelliJ
-      # installation.
-      IFS=$'\n'
-      local sorted=($(sort -r <<<"${ij_home_paths[*]}"))
-      unset IFS
-      ij_home="${sorted[0]}"
-  fi
-
-
-  # If we don't have or can't find ij_home, don't bother with attempting to patch anything.
-  if [[ -d "${ij_home}" ]]; then
-      # aspect_path is the path to the aspect external repository that IntelliJ will
-      # inject into bazel via --override_repository.
-      local aspect_path="${ij_home}/ijwb/aspect"
-      if [[ -d "${aspect_path}" ]]; then
-          # aspect_path is the path to the aspect external repository that IntelliJ will
-          # inject into bazel via --override_repository.
-          local aspect_path="${ij_home}/ijwb/aspect"
-          # Our copy of it.
-          local patched_path="${ij_home}/ijwb/aspect-monogon"
-          # Checksum of the patch that was used to create patched_path.
-          local checksum_file="${patched_path}/checksum"
-          # The patch
-          local patch_file="${DIR}/../intellij/patches/bazel_intellij_aspect_filter.patch"
-          # The checksum of the patch we're about to apply.
-          local checksum
-          checksum=$(sha256sum "$patch_file" | cut -d' ' -f1)
-
-          # If the patched aspect repository doesn't exist, or the checksum of the patch
-          # we're about to apply doesn't match the checksum of the patch that was used
-          # to create the patched aspect repository, apply the patch.
-
-          if ! [[ -d "${patched_path}" ]] || ! [[ "$(cat "${checksum_file}")" == "${checksum}" ]]; then
-              echo "IntelliJ found at ${ij_home}, patching aspect repository." >&2
-              # Copy the aspect repository to the patched path.
-              rm -rf "${patched_path}"
-              cp -r "${aspect_path}" "${patched_path}"
-              # Apply the patch.
-              patch -d "${patched_path}" -p1 < "${patch_file}"
-              # Write the checksum of the patch to the checksum file.
-              echo "${checksum}" > "${checksum_file}"
-          else
-              echo "IntelliJ found at ${ij_home}, aspect repository already patched." >&2
-          fi
-      else
-        echo "IntelliJ found at ${ij_home}, but aspect repository is missing. Skipping..." >&2
-      fi
-  fi
-}
-
 prechecks
-intellij_patch
-
-# Find the --override_repository=intellij_aspect=[path]
-# argument in $@ and replace the path with the patched version.
-# This is surprisingly tricky - bash special-cases "$@" to expand
-# as "$1" "$2" ... "$n" so that argv is preserved, so we need to
-# modify the real $@ array.
-
-for i in $(seq 1 $#); do
-  if [[ "${!i}" == "--override_repository=intellij_aspect="* ]]; then
-    new_arg="${!i/\/aspect/\/aspect-monogon}"
-    set -- "${@:1:$((i-1))}" "${new_arg}" "${@:$((i+1))}"
-  fi
-done
 
 exec -a "$0" "${BAZEL_REAL}" "$@"