from __future__ import print_function
from __future__ import unicode_literals

import io
import re

import yaml
from aspy.yaml import ordered_load


def _indent(s):
    lines = s.splitlines(True)
    return ''.join(' ' * 4 + line if line.strip() else line for line in lines)


def _is_header_line(line):
    return (line.startswith(('#', '---')) or not line.strip())


def _migrate_map(contents):
    # Find the first non-header line
    lines = contents.splitlines(True)
    i = 0
    while _is_header_line(lines[i]):
        i += 1

    header = ''.join(lines[:i])
    rest = ''.join(lines[i:])

    if isinstance(ordered_load(contents), list):
        # If they are using the "default" flow style of yaml, this operation
        # will yield a valid configuration
        try:
            trial_contents = header + 'repos:\n' + rest
            ordered_load(trial_contents)
            contents = trial_contents
        except yaml.YAMLError:
            contents = header + 'repos:\n' + _indent(rest)

    return contents


def _migrate_sha_to_rev(contents):
    reg = re.compile(r'(\n\s+)sha:')
    return reg.sub(r'\1rev:', contents)


def migrate_config(config_file, quiet=False):
    with io.open(config_file) as f:
        orig_contents = contents = f.read()

    contents = _migrate_map(contents)
    contents = _migrate_sha_to_rev(contents)

    if contents != orig_contents:
        with io.open(config_file, 'w') as f:
            f.write(contents)

        print('Configuration has been migrated.')
    elif not quiet:
        print('Configuration is already migrated.')

pre_commit/commands/migrate_config.py
from __future__ import print_function
from __future__ import unicode_literals

import io
import re

import yaml
from aspy.yaml import ordered_load


def _indent(s):
    lines = s.splitlines(True)
    return ''.join(' ' * 4 + line if line.strip() else line for line in lines)


def _is_header_line(line):
    return (line.startswith(('#', '---')) or not line.strip())


def _migrate_map(contents):
    # Find the first non-header line
    lines = contents.splitlines(True)
    i = 0
    # Only loop on non empty configuration file
    while i < len(lines) and _is_header_line(lines[i]):
        i += 1

    header = ''.join(lines[:i])
    rest = ''.join(lines[i:])

    if isinstance(ordered_load(contents), list):
        # If they are using the "default" flow style of yaml, this operation
        # will yield a valid configuration
        try:
            trial_contents = header + 'repos:\n' + rest
            ordered_load(trial_contents)
            contents = trial_contents
        except yaml.YAMLError:
            contents = header + 'repos:\n' + _indent(rest)

    return contents


def _migrate_sha_to_rev(contents):
    reg = re.compile(r'(\n\s+)sha:')
    return reg.sub(r'\1rev:', contents)


def migrate_config(config_file, quiet=False):
    with io.open(config_file) as f:
        orig_contents = contents = f.read()

    contents = _migrate_map(contents)
    contents = _migrate_sha_to_rev(contents)

    if contents != orig_contents:
        with io.open(config_file, 'w') as f:
            f.write(contents)

        print('Configuration has been migrated.')
    elif not quiet:
        print('Configuration is already migrated.')

pre_commit/commands/migrate_config.py
diff --git a/pre_commit/commands/migrate_config.py b/pre_commit/commands/migrate_config.py
index 3f73bb83e..bac423193 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])
diff --git a/tests/commands/migrate_config_test.py b/tests/commands/migrate_config_test.py
index 8f9153fdc..c58b9f74b 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

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
```
