#!/usr/bin/env python

"""
From http://stefaanlippens.net/svnignorescript
"""

from __future__ import print_function
import argparse
import os
import subprocess


def svn_propget(svnprop, path):
    """Fetch a svn property of a file or directory."""
    subproc = subprocess.Popen(
        ["svn", "propget", svnprop, path],
        stdout=subprocess.PIPE
    )
    subproc.wait()
    data = subproc.stdout.read().strip().decode()
    print(data)
    return data


def svn_propset(svnprop, value, path):
    """Set a svn property on a file or directory."""
    subproc = subprocess.Popen(["svn", "propset", svnprop, value, path])
    subproc.wait()


def main():
    """main"""
    arg_parser = argparse.ArgumentParser(
        description="Add (or remove) files and dirs to subversion ignore list."
    )
    arg_parser.add_argument(
        "-u",
        "--unignore",
        action="store_true",
        dest="unignore",
        default=False,
        help="unignore the file or directory"
    )
    arg_parser.add_argument(
        "--no-sort",
        action="store_false",
        dest="sort",
        default=True,
        help="do not sort property values"
    )
    arg_parser.add_argument(
        "files",
        metavar="file|dir",
        nargs="+",
        help="file or directory"
    )
    args = arg_parser.parse_args()

    for path in args.files:
        dirpath, filename = os.path.split(path)

        # Get svn:ignore property, with standardized line endings.
        svnignore_data = svn_propget("svn:ignore", dirpath).replace("\r", "")

        # Transform to a list.
        svnignore_data = svnignore_data.split("\n")

        # Add or remove filename.
        if args.unignore:
            if filename not in svnignore_data:
                continue
            svnignore_data.remove(filename)
        else:
            if filename in svnignore_data:
                continue
            svnignore_data.append(filename)

        # Optionally sort.
        if args.sort:
            svnignore_data = sorted(svnignore_data)

        svn_propset("svn:ignore", "\n".join(svnignore_data), dirpath)


if __name__ == "__main__":
    main()
