Repository: pre-commit/pre-commit

Issue:
pre-commit autoupdate fails when config is empty
Running `pre-commit autoupdate` with an empty `.pre-commit-config.yaml` results in the below error:
```An unexpected error has occurred: IndexError: list index out of range
Traceback (most recent call last):
  File "/usr/local/Cellar/pre-commit/1.14.2/libexec/lib/python3.7/site-packages/pre_commit/error_handler.py", line 46, in error_handler
    yield
  File "/usr/local/Cellar/pre-commit/1.14.2/libexec/lib/python3.7/site-packages/pre_commit/main.py", line 286, in main
    repos=args.repos,
  File "/usr/local/Cellar/pre-commit/1.14.2/libexec/lib/python3.7/site-packages/pre_commit/commands/autoupdate.py", line 117, in autoupdate
    migrate_config(config_file, quiet=True)
  File "/usr/local/Cellar/pre-commit/1.14.2/libexec/lib/python3.7/site-packages/pre_commit/commands/migrate_config.py", line 52, in migrate_config
    contents = _migrate_map(contents)
  File "/usr/local/Cellar/pre-commit/1.14.2/libexec/lib/python3.7/site-packages/pre_commit/commands/migrate_config.py", line 24, in _migrate_map
    while _is_header_line(lines[i]):
IndexError: list index out of range
```

Discussion:

Patch:
diff --git a/pre_commit/commands/migrate_config.py b/pre_commit/commands/migrate_config.py
index 3f73bb8..bac4231 100644
--- a/pre_commit/commands/migrate_config.py
+++ b/pre_commit/commands/migrate_config.py
@@ -21,7 +21,8 @@ def _migrate_map(contents):
     # Find the first non-header line
     lines = contents.splitlines(True)
     i = 0
-    while _is_header_line(lines[i]):
+    # Only loop on non empty configuration file
+    while i < len(lines) and _is_header_line(lines[i]):
         i += 1
 
     header = ''.join(lines[:i])


Test patch:
diff --git a/tests/commands/migrate_config_test.py b/tests/commands/migrate_config_test.py
index 8f9153f..c58b9f7 100644
--- a/tests/commands/migrate_config_test.py
+++ b/tests/commands/migrate_config_test.py
@@ -147,3 +147,13 @@ def test_migrate_config_sha_to_rev(tmpdir):
         '    rev: v1.2.0\n'
         '    hooks: []\n'
     )
+
+
+@pytest.mark.parametrize('contents', ('', '\n'))
+def test_empty_configuration_file_user_error(tmpdir, contents):
+    cfg = tmpdir.join(C.CONFIG_FILE)
+    cfg.write(contents)
+    with tmpdir.as_cwd():
+        assert not migrate_config(C.CONFIG_FILE)
+    # even though the config is invalid, this should be a noop
+    assert cfg.read() == contents