#!/usr/local/bin/python2.7
#
# src - simple revision control.
#
# Things to know before hacking this:
#
# All the code outside the RCS class is intended to be generic to any
# file-oriented VCS. Try to keep it that way; in particular, support
# for SCCS is an eventual goal.
#
# SRC and RCS have different goals in managing locks. RCS wants to keep
# the workfile read-only except when it's explicitly checked out, SRC wants to
# leave it writeable all the time.  Thus, the checkin sequence is "release
# lock; check in; assert lock". If this seems confusing, it's because in
# RCS terminology, locked is writeable and unlocked is read-only.
#
# Despite appearances, this code does not actually use RCS locks (and
# sets locking to non-strict).  That just happens to be a handy way to
# record which revision the user last checked out, which is significant
# for future checkouts and for branching.
#
# This code uses magic tags with a 0 in the second-to-last slot to designate
# branches.  It's the same format as CVS sticky tags, for the same reason.
# They need to be distinguishable from regular tags pointing at revisions,
# and this way the code to transform the sticky tag into the branch name is
# as simple as possible.
#
# Top of the list of things that people will bikeshed about is the
# letter codes returned by src status. Different VCSes have
# conflicting ideas about this. The universal ones are A = Added, M =
# Modified, and ? = Untracked.  Here's a table of the ones in dispute.
# Entries with '-' mean the VCS does not have a closely corresponding
# status.
#
#                   git     hg     svn      src
# Unmodified        ' '     '='    ' '      '='
# Renamed           'R'      -      -        -
# Deleted           'D'     'R'    'D'       -
# Copied            'C'      -      -        -
# Ignored           '!'     'I'    'I'      'I'
# Updated/unmerged  'U'      -      -        -
# Missing            -      '!'    '!'      '!'
# Locked             -       -     'L'      'L'
#
# (hg used to use 'C' as the code for unmodified status.)
#
# This is a bit oversimplified; it is meant not as a technical comparison
# but rather to illustrate how bad the letter collisions are. SRC follows
# the majority except for absolutely *not* using a space as a status code;
# this makes the reports too hard to machine-parse.

import sys, os, subprocess, time, calendar, stat, glob, shutil, hashlib

version="0.18"

def rfc3339(t):
    "RFC3339 string from Unix time."
    return time.strftime(b"%Y-%m-%dT%H:%M:%SZ", time.gmtime(t))

def announce(msg):
    sys.stdout.write("src: " + msg + "\n")

def croak(msg):
    sys.stdout.flush()
    sys.stderr.write("src: " + msg + "\n")
    sys.exit(1)

debug = 0
DEBUG_SEQUENCE  = 1    # Sequence debugging
DEBUG_COMMANDS  = 2    # Show commands as they are executed
DEBUG_PARSE     = 3    # Debug logfile parse

quiet = False		# option -q: run more quietly
pseudotime = False	# option -T: artificial clock for regression testing

# Repo directory
repodir = ".src"

# How to size cut lines.  We used to do this dynamically from the screen size,
# but that fails under Emacs
WIDTH = 72

def stamp(arg):
    "Name the stamp file used to track revisions."
    if os.sep not in arg:
        return os.path.join(repodir, arg + ".srcstamp")
    else:
        return os.path.join(os.path.dirname(arg),
                            repodir,
                            os.path.basename(arg) + ".stamp")

def is_stamp(arg):
    "Is this the name of a stamp file?"
    return arg.endswith(".srcstamp")

def make_stamp(workfile, length=None, hashval=None):
    "Create a stamp file for a workfile."
    stampfile = stamp(workfile)
    if length is None:
        length = os.path.getsize(workfile)
    with open(stampfile, "wb") as wfp:
        if hashval is None:
            with open(workfile) as rfp:
                hashobj = hashlib.sha1()
                hashobj.update(rfp.read())
                hashval = hashobj.hexdigest()
        wfp.write("%d:%s\n" % (length, hashval))

def is_history(arg):
    "Are we looking at a history file?"
    return arg.endswith(",v") 

def modified(workfile):
    "Has the workfile been modified since it was checked out?"
    # Alas, we can't rely on modification times; it was tried, and
    # os.utime() is flaky from Python - sometimes has no effect.
    # Where the bug is - Python, glibc, kernel - is unknown.
    # Even if we could, it's nice to catch the case where an edit
    # was undone.
    #
    # Try getting the last stored length and hash from the stamp file to
    # compare the workfile length and hash with.
    workfile_content = workfile_length = workfile_hash = None
    try:
        stampfile = stamp(workfile)
        with open(stampfile, "rb") as rfp:
            stampline = rfp.read()
        try:
            (length, sha1) = stampline.strip().split(":")
            try:
                workfile_length = os.path.getsize(workfile)
                # This is the fast path
                if int(length) != workfile_length:
                    return True
                with open(workfile) as rfp:
                    workhash = hashlib.sha1()
                    workfile_content = rfp.read()
                    workhash.update(workfile_content)
                workfile_hash = workhash.hexdigest()
                return workfile_hash != sha1
            except OSError:
                announce("in %s, internal error - workfile is missing!" % workfile)
                return None
        except ValueError:
            announce("in %s, internal error - bad format of stamp file." % arg)
    except IOError:
        pass
    # Stamp file absent or garbled, do it the hard way
    history = History(workfile)
    with backend.lifter(workfile):
        tmp = os.path.join(repodir, "tmp" + str(os.getpid()))
        backend.cat(workfile, history.current().native, tmp)
        base_content = open(tmp).read()
        os.remove(tmp)
    if workfile_content is None:
        workfile_content = open(workfile).read()
    basehash = hashlib.sha1()
    basehash.update(base_content)
    make_stamp(workfile, length=len(base_content), hashval=basehash.hexdigest())
    return base_content != workfile_content

def do_or_die(dcmd, legend=b"", loud=False):
    "Either execute a command or die."
    if legend:
        legend = " "  + legend
    if debug == 0 and not loud:
        mute = " >/dev/null 2>&1"
    else:
        mute = ""
    if debug >= DEBUG_COMMANDS:
        sys.stderr.write(b"executing '%s'%s\n" % (dcmd, legend))
    try:
        retcode = subprocess.call("(" + dcmd + ")" + mute, shell=True)
        if retcode < 0:
            croak(b"%s was terminated by signal %d." % (dcmd, -retcode))
        elif retcode != 0:
            croak(b"%s returned %d." % (dcmd, retcode))
    except (OSError, IOError) as e:
        croak(b"execution of %s%s failed: %s" % (dcmd, legend, e))

class popen_or_die:
    "Read or write from a subordinate process."
    def __init__(self, command, legend=b"", mode=b"rb"):
        assert mode in (b"rb", b"wb")
        self.command = command
        self.legend = legend
        self.mode = mode
        if self.legend:
            self.legend = b" "  + self.legend
        self.fp = None
    def __enter__(self):
        if debug >= DEBUG_COMMANDS:
            if self.mode == "rb":
                sys.stderr.write(b"%s: reading from '%s'%s\n" % (rfc3339(time.time()), self.command, self.legend))
            else:
                sys.stderr.write(b"%s: writing to '%s'%s\n" % (rfc3339(time.time()), self.command, self.legend))
        try:
            self.fp = os.popen(self.command, self.mode)
            return self.fp
        except (OSError, IOError) as oe:
            croak(b"execution of %s%s failed: %s" \
                                 % (self.command, self.legend, oe))
    def __exit__(self, extype, value, traceback_unused):
        if extype:
            if debug > 0:
                raise extype(value)
            croak(b"fatal exception in popen_or_die.")
        if self.fp.close() is not None:
            croak(b"%s%s returned error." % (self.command, self.legend))
        return False

def capture_or_die(command):
    "Run a specified command, capturing the output."
    if debug >= DEBUG_COMMANDS:
        sys.stderr.write(b"%s: capturing %s\n" % (rfc3339(time.time()), command))
    try:
        content = subprocess.check_output(command, shell=True)
    except (subprocess.CalledProcessError, OSError) as oe:
        croak(b"execution of '%s' failed: %s" % (command, oe))
    if debug >= DEBUG_COMMANDS:
        sys.stderr.write(content)
    return content

class HistoryEntry:
    "Capture the state of a native revision item in the log."
    def __init__(self, history):
        self.history = history
        self.revno = None
        self.native = None	# magic cookie only interpreted by back end
        self.log = ""
        self.date = None
        self.parent = None
        self.child = None
        self.branches = set([])
        self.branch = None
    def selected(self):
        return self == self.history.current()
    def unixtime(self):
        try:
            return calendar.timegm(time.strptime(self.date, "%Y-%m-%dT%H:%M:%SZ"))
        except (TypeError, ValueError):
            croak("garbled date %s" % self.date)
    def __str__(self):
        return "<%s = %s>" % (self.revno, self.native)

def registered(workfile):
    "Is this a workfile for a registered history?"
    return os.path.exists(backend.history(workfile))

class History:
    "Encapsulate a revision list and some methods on it"
    def __init__(self, name):
        self.name = name
        self.revlist = []
        self.symbols = {}
        self.branch = "trunk"
        self.lockrevs = []
        if not registered(self.name):
            croak("%s is not registered" % self.name)
        backend.parse(self)
        self.by_revno_d = {}
        self.by_native_d = {}
        self.parent = None
        self.child = None
        self.branches = set([])
        for item in self.revlist:
            self.by_revno_d[item.revno] = item
            self.by_native_d[item.native] = item
        for item in self.revlist:
            item.parent = self.by_native_d.get(backend.pred(item.native))
            item.child  = self.by_native_d.get(backend.succ(item.native))
            if item.parent and item.parent.child != item:
                item.parent.branches.add(item)
        if self.revlist:
            for (name, rev) in self.symbols.items():
                if backend.isbranch(rev):
                    base = backend.branch_to_base(rev, self)
                    tip = backend.branch_to_tip(rev, self)
                    while True:
                        self.by_native_d[base].branch = name
                        if base == tip:
                            break
                        base = backend.succ(base)
        #for item in self.revlist:
        #    print item
        #print self.by_revno_d.keys()
    def __len__(self):
        return len(self.revlist)
    def current(self):
        "Return the revision currently checked out."
        # Yes, this looks weird.  The idea is: Try to return the locked
        # revision. If that blows up, try to return the tip revision
        # of the current branch.  If that blows up, return None.
        try:
            return self.by_native_d[self.lockrevs[0]]
            return self.by_native_d[backend.branch_to_tip(self.symbols[self.branch], self)]
        except IndexError:
            return None
    def current_branch(self, backwards=False):
        "Return a list of items that are descendants or ancestors of current."
        if debug >= DEBUG_SEQUENCE:
            print "current_branch(%s)" % self.current()
        selection = []
        p = self.current()
        if p is not None:
            selection = [p]
            while True:
                if p.parent is None:
                    break
                else:
                    p = p.parent
                selection = [p] + selection
            s = self.current()
            while True:
                s = s.child
                if s is None:
                    break
                selection.append(s)
            if backwards:
                selection.reverse()
        return selection
    def tip(self, rev=None):
        "Return the tip revision of the branch of the given native revision."
        if rev is None:
            rev = self.current().native
        s = self.by_native_d[rev]
        while True:
            if s.child == None:
                return s
            else:
                s = s.child
    def native_to_revno(self, revision):
        "Map a native ID to a revno"
        item = self.by_native_d.get(revision)
        return item and item.revno
    def by_revno(self, revno):
        "Map a revno to a revision item."
        try:
            return self.by_revno_d[revno]
        except KeyError:
            if revno == 0:
                raise ValueError
                # This case comes up if we try to select the
                # tip revision of a history without revisions. 
                croak("{0} has no revisions".format(self.name))
            else:
                croak("{0} has no revno {1}".format(self.name, revno))
    def revno_to_native(self, revno):
        "Map a revno to a native ID"
        return self.by_revno(revno).native

help_topics = {
    "topics": """
The following help topics are available:

intro       -- Basic concepts: commits, tags, branches. The form of commands.
revisions   -- How to specify ranges of commits to operate on.
commands    -- a summary of the commands.
commit      -- the commit command: how to commit changes to a file.
amend       -- the amend command: editing stored change comments.
checkout    -- the checkout command: retrieving historical versions of files.
cat         -- the cat command: dumping revisions to standard output.
status      -- the status command: more details and unusual status codes.
log         -- the log command: dump commit log information to standard output.
list        -- the list command: dump commit summaries to standard output.
diff        -- the diff command: dump revision differences to standard output.
fast-export -- the fast-export command: export history to other systems.
fast-import -- the fast-import command: import history from other systems.
ignores     -- .srcignore files and their uses.

The 'help', 'rename', 'ls', 'move', 'copy', and 'version' commands are
completely described in the command summary.
""",
    "intro": """
SRC (or src) is designed for version control on single-file projects.

A SRC history is a sequence of commits numbered in strict time order
starting from 1.  Each holds a modification to the file, a comment,
and the date-time of the commit.

The sequence also has a branch structure.  By default there is just
one branch named 'trunk'.  You can start a new named branch at any
commit. Branches can later be renamed or deleted.  Because of
branching, parent and child commits do not necessarily have
consecutive numbers.

Commits will always be be added to the tip of the current branch.
You can change the current branch by either checking out a revision
that is on that branch, or using a 'src branch' command to
explictly change the current branch.

You can assign tags (names) to point to commits. They too can be
renamed later or deleted.

The general form of a SRC command is

	src verb [switches] [revision-spec] [files...]

That is, a command verb is followed by optional switches, which are
(sometimes) optionally followed by a range of commits to operate on,
which is optionally followed by a list of files to operate on. Usually
you will specify either a revision range or multiple files, but not both.

The token "--" tells the command-line interpreter that subcommands,
switches, and revision-specs are done - everything after it is a filename,
even if it looks like a subcommand or revision number.

Actually, at least one file operand is usually required.  The
exceptional case is when you have only one SRC-controlled file
in the directory; in that case SRC knows you must mean that one.

A good help topics to read after this one would be 'revisions'.
""",
    "revisions": """
A 'revision' is a 1-origin integer, or a tag name designating an
integer revision, or a branch name designating the tip revision of its
branch, or '@' meaning the currently fetched revision. Revision
numbers always increase in commit-date order.

A revision range is a single revision, or a pair of revisions M-N (all
revisions numerically from M to N) or M..N (all revisions that are
branch ancestors of N and branch successors of M).  If N is less than
M, the range is generated as if N >= M then reversed.

If src complains that your revision spec looks like a nonexistent
filename, you can prefix it with @ (this is always allowed).

Some commands (help, commit, status, delete/rename commands for tags
and branches, ls, move, copy, fast-import, release, version) don't
take a revision spec at all and will abort if you give one.

Some commands (amend, checkout, cat, tag and branch creation) optionally
take a singleton revision spec.

Some commands (log, list, diff, fast-export) accept a range or a singleton.

Unless otherwise noted under individual commands, the default revision
is the tip revision on the current branch.

A good topic to read next would be 'commands'.
""",
    "commands": """
src help [command]
   Displays help for commands.

src commit [- | -m 'string' | -f 'file' | -e] ['file'...]
   Enters a commit for specified files. Separately to each one.
   A history is created for the file if it does not already exist.
   With '-', take comment text from stdin; with '-m' use the
   following string as the comment; with '-f' take from a file.
   With '-e', edit even after '-f' or '-m'.  'ci' is a synonym for commit.

src amend [- | -m string | -f file | -e] ['revision'] ['file'...]
   Amends the stored comment for a specified revision, defaulting to the
   latest revision on the current branch. Flags are as for commit.

src checkout ['revision'] ['file'...]
   Refresh the working copies of the file(s) from their history files.
   'co' is a synonym for checkout.

src cat ['revision'] ['file'...]
   Send the specified revisions of the files to standard output.

src status [-a] ['file'...]
   'A' = added, '=' = unmodified, 'M' = modified, '!' = missing, '?' = not
   tracked, 'I' = ignored, 'L' = locked (recover with src checkout).
   Find more details under 'help status'. 'st' is a synonym for status.

src tag [list|-l|create|-c|delete|del|-d] ['name'] ['revision'] ['file'...] 
   List tags, create tags, or delete tags. Takes a singleton
   revision, defaulting to the current branch tip.

src branch [list|create|-c-l|delete|del|-d] ['name'] ['file'...]
   List, create, or delete branches. When listing, the active branch
   is first in the list. The default branch is 'trunk'.

src rename ['tag'|'branch'] ['oldname'] ['newname']  ['file'...]
   Rename a tag or branch. Refuses to step on an existing symbol or
   rename a nonexistent one.  'rn' is a synonym for 'rename'.

src list [-l n] [-f fmt] ['revision-range'] ['file'...]
   Sends summary information about the specified commits to standard output.
   The summary line tagged with '*' is the state that the file would
   return to on checkout without a revision-spec. See 'help list' for
   information about custom formats. Use -l n to omit the listing length.
   Default range is thec current branch, reversed.

src log [-l n] ['revision-range'] ['file'...]
   Sends log information about the specified commits to standard output.
   Use -l n to omit the listing length.  Default range is the current branch,
   reversed.

src diff ['revision-range'] ['file'...]
   Sends a diff listing to standard output. With no revision spec, diffs
   the working copy against the last version checked in. With one revno,
   diffs the working copy against that stored revision; with a range,
   diff between the beginning and end of the range.

src ls
   List all registered files.

src move 'old' 'new'
   Rename a workfile and its history. Refuses to step on existing
   workfiles or histories.  'mv' is a synonym for 'move'.

src copy 'old' 'new'
   Copy a workfile and its history. Refuses to step on existing files
   or histories.  'cp' is a synonym.

src fast-export ['revision-range'] ['file'...]
   Export one or more projects to standard output as a git fast-import stream.
   The committer identification is copied from your Git configuration.
   The default range is all commits.

src fast-import [-p] ['file'...]
   Parse a git-fast-import stream from standard input. The modifications for
   each individual file become separate SRC histories.  Mark, committer and
   author data, and mark cross-references to parent commits, are preserved
   in RFC-822-style headers on log comments unless the -p (plain) option
   is given, in which case this metadata is discarded. Give arguments to
   restrict the files imported.

src release ['file'...]
   Release locks on files.  This is never necessary in a normal workflow,
   which will be repeated edit-commit cycles, but it may be handy if you
   have to interoperate with other tools that expect RCS masters to be
   in their normal (unlocked) stare.

src version
   Report the version of src.

The omission of 'src remove' is a deliberate speed bump.
""",
    "status": """
src status [-a] ['file'...]

The status command shows you the version-control status of files.  It is
designed to be useful for both humans and software front ends such as
Emacs VC mode.

The status codes, in roughly most common to rarest, are:

= - Unmodified.  File is the same as the latest stored revision.

M - Modified.  File has been changed since the latest stored revision

? - Not tracked.  SRC does not keep a history for this file.

I - ignored.  This file matches the patterns in .srcignore

! - Missing.  There is a history for this file but the workfile is missing.

A - The file has been registered into SRC but has no commits.

L - The file is locked.

Modification status is by content (using a SHA1 hash) rather than date.
Thus, if you make changes to a work file in your editor, then undo
them, the file's status returns to '='.

You can usually recover of file from A, L, and ! status with src
checkout.  A and L statuses should only occur if you have used RCS
directly on a file, or if you have called 'src add' manually.

If you give 'src status' no filename arguments, it surveys all files
in the current directory but untracked and ignored files
are not listed.  If you give it filename arguments, status is listed
for all of them.

The -a option forces status listing of all files.  This differs from
'src status *' because the latter will not see dotfiles and thus not list
the status of them.
""",
    "commit":"""
src commit [-a] [- | -m 'string' | -f 'file' | -e] ['file'...]

The commit command is how you add revisions to your file history.  It
always adds the contents of the workfile as a revision to the tip of
the current branch.

You also use commit on files that have not been registered to start
an SRC history for them.

When you commit, you must specify a change comment to go with
the revision. There are sevaral ways to do this.

The '-m' option to the command takes the following string argument
as the comment.  The '-' option takes the comment text from standard
input.  The -f option takes the comment from a named file.

If you use none of these, or if you use one of them and the -e option,
SRC wlll start an editor in which you can compose the comment.  Text
specified via -m, -f, or - becomes the initial contents of the comment.

SRC respects the EDITOR variable and calls it on a temporary file
to create your comment.  Th file will have a footer including its
name and revision which will be discarded when you finish editing.

If you leave the comment empty (except for the generated footer)
or consisting only of whitespace, the commit will be aborted.  The
commit will also be aborted if your editor returns a failure status.

If you commit to multiple files at once, separate changes will be
registered for each one, and you may get a separate edit session for
each (if you have not set the comment text with options, or have
forced editing with -e).  This is a major difference from other VCSes,
which are usually designed to create changesets common to multiple
files.

'ci' is a synonym for commit.
""",
    "amend" : """
src amend [- | -m string | -f file | -e] ['revision'] ['file'...]

Use this command to amend (modify) the change comment in a saved revision.
The commit date is not changed.

Takes a singleton revision number, tag, or branch, defaulting to the
latest revision on the current branch.

The edit flags and EDITOR variable are interpreted are as for commit.
The only difference is that existing change comment is appended to
any text you specify with switches as the initial comment passed
to your editor.

'am' is a synonym for 'amend'
""",
    "checkout":"""
src checkout ['revision'] ['file'...]

Refresh the working copies of the file(s) from their history files.
'co' is a synonym for checkout.

Takes a single revision number, tag, or branch name.  The default if
you give none is the tip revision of the current branch.

This command is how you discard the contents of a modified workfile.

You can also use it to revert the workfile to match a previous
stored revision. Doing do may, as a side effect, change your current
branch.
""",
   "cat" : """
src cat ['revision'] ['file'...]

Send the specified revision of each file to standard output. This is
not normally very useful with more than one file argument, but SRC
does not prevent that.

Takes a single revision number, tag, or branch name.  The default if
you give none is the tip revision of the current branch.

This command is mainly intended for use in scripts.
""",   
   "tag" : """
src tag [list|-l|create|-c|delete|del|-d] ['name'] ['revision'] ['file'...] 

List tags (with -l), create tags (with -c), or delete tags (with -d).

Takes at most a singleton revision; the default is the current branch tip.

Tag creation and deletion require a following name argument. Tag
creation will not step on an existing tag name, and a nonexistent branch
cannot be deleted.
""",   
   "branch" : """
src branch [list|-l|create|-c|delete|del|-d] ['name'] ['file'...]

List branches (with -l), create branches (with -c), or delete branches
(with -d).

In the list produced by '-', the active branch is first in the list.

Branch creation and deletion require a following name argument. Branch
creation will not step on an existing branch name, and a nonexistent branch
cannot be deleted.
""",
   "log" : """
src log [-l n] ['revision-range'] ['file'...]

Sends log information about the specified commits of each file
to standard output.  The log information includes the revision
number, the date, and the log comment.

With no revision, dumps a log of the entire current branch.

The -l option can be used to limit the listing length.  It is not
primarily intended for use by humans, but rather for Emacs VC mode.
""",   
   "list" : """
src list [-l n] [-f fmt] ['revision-range'] ['file'...]

Sends summary information about the specified commits of each file
to standard output.  The summary information includes the revision
number, the date, and the first line of the log comment.

This command is provided assuming you will use the good practice
of beginning each commit with a self-contained summary line.

With no revision, dumps a log of the entire current branch.

The -f option allows you to set a custom fomat string.  Available
substitutions are:

{0}   The file name
{1}   The revision number
{2}   The mark - * is this is the currently checked out revision, else '-'.
{3}   The date in RFC3339 format
{4}   The summary line

The -l option can be used to limit the listing length.  It is not
primarily intended for use by humans, but rather for Emacs VC mode.

'li' is a synonym for 'list'.
""",   
   "diff" : """
src diff ['revision-range'] ['file'...]

Sends a diff listing to standard output. 'di' is a synonym.

With no revision spec, diffs the working copy against the last version
checked in. With one revno, diffs the working copy against that stored
revision; with a range, diff between the beginning and end of the
range.

The actual difference generation is done with diff(1),  The default
diff format is -u, but if you specify options such as -c or -b after
the verb they will be passed to the command.
""",   
   "fast-export" : """
src fast-export ['revision-range'] ['file'...]

Export one or more projects to standard output as a git fast-import stream.
This can be consumed by 'git fast-import' to create a Git reppository
containing the project history.  

It is possible (though probably not very useful) to fast-export a limited
range of commits, producing an incremental dump.  In this case branch
joins are done with the magic ^0 suffix.

Fast-exporting multiple files profuces a single stream with a joint
history.

The committer identification is copied from your Git configuration.

The default range is all commits.
""",   
   "fast-import" : """
src fast-import [-p] ['file'...]

Parse a git-fast-import stream from standard input. The modifications
for each individual file become separate SRC histories. Give arguments
to restrict the files imported.

The import is actually done with the rcs-fast-import(1) tool, which
must be on your $PATH for this command to work.

Some gitspace metadata cannot be represented in the SRC/RCS model of
version control. Mark, committer and author data, and mark
cross-references to parent commits. These are preserved in
RFC-822-style headers on log comments unless the -p (plain) option is
given, in which case this metadata is discarded.

This command is not expected to be very useful. It is included mainly
as a good example to more capable version-control systems that could
have native importers of their own but don't.
""",   
   "ignores" : """
You can have a file named .srcignore containing the names of files that
SRC should ignore, or more commonly patterns describing files to ignore.

When SRC is told to ignore a file, it won't show up in src status
listings unless the '-a' (all) flag is used or you give it as an
explicit argument. It will also be ignored when commands that expect a
list of registered files see it (which could easily happen when you
use shell wildcards in SRC commands).

Other version-control systems have these too. The classic example of
how to do this is using the pattern '*.o' to ignore C object files.
But if you need to do that, you should probably be using a multi-file
VCS with changesets, not this one.

Patterns that might be useful with single-file projects include "*~"
to ignore editor backup files, or '*.html' if you're writing documents
that render to HTML but aren't sourced in it.

The repo subdirectory - normally .src - is always ignored, but .srcignore
iyself is not automatically ignored.

SRC's pattern syntax is that of Unix glob(3), with initial '!' treated
as a negation operator.  This is forward-compatible to Git's ignore
syntax.

* matches any string of characters.

? matches any single character.

[] brackets a character class; it matches any character in the class.
So, for example, [0123456789] would match any decimal digit.

[!] brackets a negated character class; [!0123456789] would match
any character not a decimal digit.
""",
    }

def help_method(*args):
    "Summarize src commands, or (with argument) show help for a single command."
    if not args:
        sys.stdout.write(help_topics['topics'])
    for arg in args:
        if arg in args:
            if arg in help_topics:
                sys.stdout.write(help_topics[arg])
            else:
                croak("%s is not a known help topic.\n%s" % (arg, help_topics['topics']))

def parse_as_revspec(token):
    "Does this look like something that should be parsed as a revision spec?"
    if "/" in token:
        return False
    elif "-" in token or ".." in token:
        return True
    elif token.isdigit():
        return True
    elif token.startswith("@"):	# Escape clause for tags that look like files
        return True
    else:
        return False

ignorable = None

def ignore(filename):
    "Should the specified file be ignored?"
    global ignorable
    if ignorable is None:
        ignorable = set([])
        ignorable = set()
        if os.path.exists(".srcignore"):
            for line in open(".srcignore"):
                if line.startswith("#") or not line.strip():
                    continue
                elif line.startswith("!"):
                    ignorable -= set(glob.glob(line[1:].strip()))
                else:
                    ignorable |= set(glob.glob(line.strip()))
    return (filename == repodir) or (filename in ignorable)

class CommandContext:
    "Consume a revision specification or range from an argument list"
    def __init__(self, cmd, args,
                 require_empty=False,
                 default_to=None,
                 parse_revspec=True):
        if not os.path.exists(repodir):
            croak("repository subdirectory %s does not exist" % repodir)
        self.start = self.end = None
        self.seq = None
        self.branchwise = None
        if type(args) == type(()):
            args = list(args)
        self.args = list(args)
        self.default_to = default_to
        revspec = None
        if self.args:
            if self.args[0] == "--":
                self.args.pop(0)
            elif parse_revspec and parse_as_revspec(args[0]):
                revspec = self.args.pop(0)
                if revspec.startswith("@"):
                    revspec = revspec[1:]
                try:
                    if "-" in revspec or ".." in revspec:
                        self.branchwise = ".." in revspec
                        try:
                            (self.start, self.end) = revspec.split("-")
                        except ValueError:
                            try:
                                (self.start, self.end) = revspec.split("..")
                            except ValueError:
                                croak("internal error - argument parser is confused")
                        try:
                            self.start = int(self.start)
                        except ValueError:
                            pass
                        try:
                            self.end = int(self.end)
                        except ValueError:
                            pass
                    else:
                        try:
                            self.end = self.start = int(revspec)
                        except ValueError:
                            self.end = self.start = revspec
                except ValueError:
                    croak("malformed revision spec: %s" % revspec)
        if require_empty and not self.is_empty():
            croak("%s doesn't take a revision spec" % cmd)
        if not self.args:
            try:
                masters = [fn for fn in os.listdir(repodir) if is_history(fn)]
            except OSError:
                croak("repo directory %s does not exist" % repodir)
            if len(masters) == 1:
                self.args += [backend.workfile(master) for master in masters]
            else:
                croak("%s requires at least one file argument" % cmd)
    def is_empty(self):
        "Is the spec empty?"
        return self.start is None
    def is_singleton(self):
        "Is the spec a singleton?"
        return self.start is not None and self.start == self.end
    def is_range(self):
        "Is the spec a range?"
        return self.start is not None and self.start != self.end
    def select_all(self, metadata):
        "Set the range to all revisions."
        self.start = 1
        self.end = len(metadata)
        self.seq = [metadata.by_revno(i) for i in range(self.start, self.end+1)]
    def select_tip(self, metadata):
        "Set the range to the tip revision."
        self.start = len(metadata)
        self.end = None
        self.seq = [metadata.by_revno(self.start)]
    def __contains__(self, i):
        "Does the spec contain the given revno?"
        if self.seq is None:
            croak("revision spec hasn't been resolved")
        return i in self.seq
    def resolve(self, metadata):
        "Resolve a revision spec that may contain tags into revnos."
        if debug >= DEBUG_SEQUENCE:
            sys.stderr.write("Entering resolve with start=%s, end=%s\n" % (self.start, self.end))
        if self.is_empty():
            if self.default_to == "branch":
                self.seq = metadata.current_branch(backwards=False)
            elif self.default_to == "branch_reversed":
                self.seq = metadata.current_branch(backwards=True)
            else:
                self.seq = []
            return self.seq
        def subresolve(token):
            part = token
            if type(part) == type(0):
                return part
            if token == '':	# User specified @
                current = metadata.current()
                if current is None:
                    croak("in {0}, no current revision".format(metadata.name))
                return current.revno
            if part not in metadata.symbols:
                croak("in {0}, can't resolve symbol {1}".format(metadata.name,token))
            else:
                part = metadata.symbols[part]
            if backend.isbranch(part):
                part = backend.branch_to_tip(part, metadata)
            return metadata.native_to_revno(part)
        self.start = subresolve(self.start)
        self.end = subresolve(self.end)
        reversed = (self.start > self.end)
        if reversed:
            swapme = self.end
            self.end = self.start
            self.start = swapme
        if self.end > len(metadata):
            croak("{0} has no {1} revision".format(metadata.name, self.end))
        if not self.branchwise:
            self.seq = [metadata.by_revno(i) for i in range(self.start, self.end+1)]
        else:
            self.seq = []
            e = metadata.by_revno(self.end)
            while True:
                self.seq.append(e)
                if e.revno == self.start:
                    break
                if e.parent is None:
                    croak("%s is not an ancestor of %s" % (self.start, self.end))
                else:
                    e = e.parent
        if debug >= DEBUG_SEQUENCE:
            sys.stderr.write("selection: %s, branchwise is %s\n" % ([x.revno for x in self.seq], "on" if self.branchwise else "off"))
            for item in metadata.revlist:
                sys.stdout.write("%s\t%s\t%s\n" % (item.revno, item.date, item.native))
        # Because in the branchwise case the sequence is generated in reverse
        if self.branchwise:
            self.seq.reverse()
        # Range might have been reversed
        if reversed:
            self.seq.reverse()
        return self.seq

class CommentContext:
    COMMENT_CUTLINE = """\
.............................................................................
"""
    COMMENT_EXPLANATION = """\
The cut line and things below it will not become part of the comment text.
"""
    def __init__(self, legend, args):
        "Attempt to collect a comment from command line args."
        self.leader = ""
        self.comment = None
        self.force_edit = False
        self.parse_revspec = True
        if args:
            if args[0] == '--':
                self.parse_revspec = False
                args.pop(0)
            elif args[0] == "-":
                self.leader = sys.stdin.read()
                args.pop(0)
            elif args[0] == "-e":
                self.force_edit = True
            elif args[0] == "-m":
                args.pop(0)
                try:
                    self.leader = args[0]
                    args.pop(0)
                except IndexError:
                    croak("%s -m requires a following string" % legend)
            elif args[0].startswith("-m"):
                self.leader = args[2:]
                args.pop(0)
            elif args[0] == "-f":
                args.pop(0)
                try:
                    self.leader = open(args[0]).read()
                    args.pop(0)
                except IndexError:
                    croak("%s -f requires a following filename argument" % legend)
                except OSError:
                    croak("couldn't open %s." % args[1])
            elif args[0].startswith("-"):
                croak("unexpected %s option" % args[0])
    def edit(self, content="", trailer=""):
        "Interactively edit a comment if required, then prepare for handoff."
        if self.leader and not self.force_edit:
            self.comment = self.leader
        else:
            if self.leader:
                content = self.leader + content
            if trailer:
                content += "\n" + CommentContext.COMMENT_CUTLINE + CommentContext.COMMENT_EXPLANATION + trailer
            editor = os.getenv("EDITOR") or "emacsclient"
            try:
                commentfile = "/tmp/src%dtmp" % os.getpid()
                open(commentfile, "w").write(content)
                do_or_die(editor + " " + commentfile, loud=True)
                self.comment = open(commentfile).read()
                if not self.comment.strip():
                    return False
            except IOError:
                croak("edit aborted.")
            where = self.comment.find(CommentContext.COMMENT_CUTLINE)
            if where != -1:
                self.comment = self.comment[:where]
            # Can be removed if we ever parse RC files directly
            for badnews in backend.delimiters:
                if badnews in self.comment:
                    croak("malformed comment")
        if not self.comment.endswith("\n"):
            self.comment += "\n"
        return True
    def content(self):
        "Return the edited comment."
        return self.comment

def commit_method(*args):
    "Commit changes to files."
    if not os.path.exists(repodir):
        try:
            os.mkdir(repodir)
        except OSError:
            croak(" %s creation failed, check directory permissions." % repodir)
    args = list(args)
    addonly = False
    parse_revspec = True
    while args:
        if args[0] == '--':
            args.pop(0)
            parse_revspec = False
            break
        elif args[0] == '-a':
            addonly = True
            parse_revspec = False
            args.pop(0)
        else:
            break
    if not addonly:
        comment = CommentContext("commit", args)
    ctx = CommandContext("commit", args,
                         require_empty=True,
                         parse_revspec=parse_revspec and comment.parse_revspec)
    for arg in ctx.args:
        if not os.path.exists(arg):
            croak("I see no '%s' here." % arg)
        if os.path.isdir(arg):
            croak("cannot commit directory '%s'" % arg)
    for arg in ctx.args:
        if not registered(arg):
            trailer = "Committing initial revision of {0}".format(arg)
            revcount = 0
        elif addonly:
            croak("attempt to re-add a registeed file failed")
        else:
            metadata = History(arg)
            ctx.resolve(metadata)
            if len(metadata) and ctx.is_empty():
                ctx.select_tip(metadata)
            trailer = "Committing {0} revision {1}.\n".format(arg, ctx.start)
            revcount = len(metadata)
        if not addonly and not comment.edit(content="", trailer=trailer):
            announce("in %s, commit cancelled" % arg)
        else:
            if not registered(arg):
                backend.add(arg)
            if not addonly:
                with backend.lifter(arg):
                    backend.checkin(arg, comment.content())
            make_stamp(arg)
            if not quiet and len(args) > 1:
                announce("%s -> %d" % (arg, revcount))

def amend_method(*args):
    "Amend comments in stored revisions."
    if not os.path.exists(repodir):
        croak("repository subdirectory %s does not exist" % repodir)
    args = list(args)
    comment = CommentContext("amend", args)
    ctx = CommandContext("amend", args, parse_revspec=comment.parse_revspec)
    if ctx.is_range():
        croak("amend cannot take a range")
    for arg in ctx.args:
       if not os.path.exists(arg):
           croak("I see no '%s' here." % arg)
       elif not registered(arg):
           croak("%s is not registered." % arg)
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.start = metadata.tip().revno
        trailer ="Amending {0} revision {1}.\n".format(arg, ctx.start)
        if not comment.edit(metadata.by_revno(ctx.start).log, trailer):
            announce("in %s, amend cancelled" % arg)
        else:
            with backend.lifter(arg):
                backend.amend(arg,
                          metadata.revno_to_native(ctx.start),
                          comment.content())
    if not quiet and len(args) > 1:
        announce("%s : %d" % (arg, ctx.start))

def list_method(*args):
    "Generate a summary listing of commits, one line per commit."
    args = list(args)
    custom = None
    limit = None
    parse_revspec = True
    if args:
        if args[0] == '--':
            parse_revspec = False
            args.pop(0)
        elif args[0] == "-f":
            args.pop(0)
            try:
                custom = args[0]
                args.pop(0)
            except IndexError:
                croak("list -f requires a following string")
        elif args[0].startswith("-f"):
            custom = args[0][2:]
            args.pop(0)
        elif args[0] == "-l":
            args.pop(0)
            try:
                limit = args[0]
                args.pop(0)
                limit = int(limit)
            except IndexError:
                croak("list -f requires a following string")
            except ValueError:
                croak("%s is not an integer" % limit)
    ctx = CommandContext("list", args,
                         default_to="branch_reversed",
                         parse_revspec=parse_revspec)
    for arg in ctx.args:
        if ignore(arg) or os.path.isdir(arg) or not registered(arg):
            continue
        if custom is None:
            sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 3) * "=")))
        for item in ctx.resolve(History(arg)):
            # Must allow enough room for revno and date
            if item.selected():
                mark = "*"
            else:
                mark = "-"
            summary = item.log.split('\n')[0]
            if custom is None:
                summary = summary[:WIDTH - 34]
                sys.stdout.write("%-4d  %s %s %s\n" \
                             % (item.revno, mark, item.date, summary))
            else:
                sys.stdout.write(custom.format(arg, item.revno, mark, item.date, summary))
            if limit is not None:
                limit -= 1
                if limit <= 0:
                    break

def log_method(*args):
    "Report revision logs"
    limit = None
    args = list(args)
    parse_revspec = True
    if args:
        if args[0] == '--':
            parse_revspec = False
            args.pop(0)
        elif args[0] == "-l":
            args.pop(0)
            try:
                limit = args[0]
                args.pop(0)
                limit = int(limit)
            except IndexError:
                croak("list -f requires a following string")
            except ValueError:
                croak("%s is not an integer" % limit)
    ctx = CommandContext("log", args,
                         default_to="branch_reversed",
                         parse_revspec=parse_revspec)
    for arg in ctx.args:
        if ignore(arg) or os.path.isdir(arg) or not registered(arg):
            continue
        sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 3) * "=")))
        for item in ctx.resolve(History(arg)):
            sys.stdout.write("%-4d | %s | %s\n%s" \
                             % (item.revno, item.date, item.branch, item.log))
            sys.stdout.write(("-" * WIDTH) + "\n")
            if limit is not None:
                limit -= 1
                if limit <= 0:
                    break

def checkout_method(*args):
    "Refresh the working copy from the history file."
    ctx = CommandContext("checkout", args)
    if ctx.is_range():
        croak("checkout needs an empty or singleton revision spec")
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_tip(metadata)
            revision = ""
        elif ctx.start > len(metadata):
            croak("%s has only %d revisions" % (arg, len(metadata)))
        else:
            revision = metadata.revno_to_native(ctx.start)
        with backend.lifter(arg):
            backend.checkout(arg, revision)
        make_stamp(arg)
        if not quiet and len(args) > 1:
            announce("%s <- %d" % (arg, ctx.start))

def status_method(*args):
    "Get status of some or all files."
    try:
        registered = [fn for fn in os.listdir(repodir) if is_history(fn)]
    except OSError:
        croak("repo directory %s does not exist" % repodir)
    args = list(args)
    allflag = False
    if args:
        if args[0] == '--':
            args.pop(0)
        elif args[0] == '-a':
            allflag = True
            args.pop(0)
    if args:
        candidates = args
    else:
        candidates = [f for f in os.listdir(".") if f != repodir]
    pairs = []
    for fn in candidates:
        if ignore(fn):
            if allflag or fn in args:
                pairs.append((fn, "I"))
            continue
        masterbase = os.path.basename(backend.history(fn))
        if masterbase not in registered:
            if allflag or fn in args:
                if not os.access(fn, os.R_OK):
                    croak("%s does not exist or is unreadable." % fn)
                else:
                    pairs.append((fn, "?"))
        elif not os.path.exists(fn):
            pairs.append((fn, "!"))
        elif modified(fn):
            pairs.append((fn, "M"))
        elif not os.access(fn, os.W_OK):
            pairs.append((fn, "L"))
        elif not backend.has_revisions(fn):
            pairs.append((fn, "A"))
        else:
            pairs.append((fn, "="))
    if not args:
        for m in registered:
            if backend.workfile(m) not in candidates:
                pairs.append((m, "!"))
    pairs.sort()
    for (fn, status) in pairs:
        sys.stdout.write(status + "\t" + fn + "\n")

def cat_method(*args):
    "Dump revision content to standard output."
    ctx = CommandContext("cat", args)
    if ctx.is_range():
        croak("cat refuses to cough up a hairball")
    for arg in ctx.args:
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_tip(metadata)
        with backend.lifter(arg):
            for item in ctx.seq:
                backend.cat(arg, item.native)

def diff_method(*args):
    "Dump diffs between revisions to standard output."
    ctx = CommandContext("diff", args)
    if type(args) == type(()):
        args = list(args)
    diffopts = ""
    while args and args[0] != '--' and args[0].startswith("-"):
        diffopts += " " + args.pop(0)
    if args and args[0] == '--':
        args.pop(0)
    if not diffopts:
        diffopts = "-u"
    for arg in ctx.args:
        diffspec1 = diffspec2 = ""
        if not ctx.is_empty():
            metadata = History(arg)
            ctx.resolve(metadata)
            diffspec1 += metadata.revno_to_native(ctx.start)
            if ctx.is_range():
                diffspec2 += metadata.revno_to_native(ctx.end)
        with backend.lifter(arg):
            backend.diff(diffspec1, diffspec2, diffopts, arg)

def tag_helper(args, legend, validation_hook, delete_method, set_method):
    "Dispatch to handlers for tag and branch manipulation."
    if not os.path.exists(repodir):
        croak("repository subdirectory %s does not exist" % repodir)
    args = list(args)
    if not args:
        args = ["list"] + args
    if args[0] == '--':
        args.pop(0)
    else:
        if args[0] in ("-d", "del", "delete"):
            args.pop(0)
            if not args:
                croak("%s deletion requires a name argument" % legend)
            name = args.pop(0)
            ctx = CommandContext(legend, args)
            if not ctx.is_empty():
                croak("can't accept a revision-spec when deleting a %s." % legend)
            for arg in ctx.args:
                metadata = History(arg)
                if name not in metadata.symbols:
                    croak("in %s, %s is not a symbol" % (arg, name))
                elif backend.isbranch(metadata.symbols[name]) != (legend  == "branch"):
                    croak("in %s, %s is not a %s" % (arg, name, legend))
                else:
                    with backend.lifter(arg):
                        delete_method(name, metadata)
                    if not quiet and len(args) > 1:
                        announce("in %s, %s %s removed" % (arg, legend, name))
                return
        if args[0] in ("-l", "list"):
            args.pop(0)
            ctx = CommandContext(legend + " listing", args, require_empty=True)
            for arg in ctx.args:
                metadata = History(arg)
                sys.stdout.write("= %s %s\n" \
                                 % (arg, ((WIDTH - len(arg) - 5) * "=")))
                keys = metadata.symbols.keys()
                if metadata.branch in keys:
                    keys.remove(metadata.branch)
                    keys.sort()
                    keys = [metadata.branch] + keys
                for key in keys:
                    value = metadata.symbols[key]
                    if legend == "branch":
                        # Note! This code relies on backend.branch_to_parent()
                        # returning an empty string when called on a trunk
                        # revision.
                        display = backend.branch_to_parent(value)
                        if not display:
                            display = 0
                        else:
                            display = metadata.native_to_revno(display)
                    else:
                        display = metadata.native_to_revno(value)
                    if backend.isbranch(value) == (legend == "branch"):
                        sys.stdout.write("%4s\t%s\n" % (display,key))
            return
        if args[0] in ("-c", "create"):
            args.pop(0)
            if not args:
                croak("%s setting requires a name argument" % legend)
            name = args.pop(0)
            ctx = CommandContext(legend, args)
            if ctx.is_range():
                croak("can't accept a range when setting a %s" % legend)
            for arg in ctx.args:
                metadata = History(arg)
                revision = validation_hook(ctx, metadata, name)
                with backend.lifter(arg):
                    set_method(name, revision, metadata)
                    if not quiet and len(args) > 1:
                        announce("in %s, %s %s = %s" % (arg, legend, name, ctx.start))
            return
        else:
            croak("%s requires a list, create, or delete modifier" % legend)  

def tag_method(*args):
    "Inspect, create, and delete tags."
    def tag_set_validate(ctx, metadata, name):
        ctx.resolve(metadata)
        if name in metadata.symbols:
            croak("tag %s already set." % name)
        if ctx.is_empty():
            ctx.select_tip(metadata)
        return metadata.revno_to_native(ctx.start)
    tag_helper(args, "tag",
               tag_set_validate,
               backend.delete_tag, backend.set_tag)

def branch_method(*args):
    "Inspect, create, and delete branches."
    def branch_set_validate(ctx, _metadata, _name):
        if not ctx.is_empty():
            croak("cannot accept a revision after a branch name")
    tag_helper(args, "branch",
               branch_set_validate,
               backend.delete_branch, backend.set_branch)

def rename_method(*args):
    "Rename a branch or tag."
    args = list(args)
    if not args or args[0] not in ("tag", "branch"):
        croak("rename requires a following 'tag' or 'branch'")
    legend = args.pop(0)
    if not args:
         croak("rename requires a source name argument")
    name = args.pop(0)
    if not args:
        croak("rename requires a target name argument")
    newname = args.pop(0)
    ctx = CommandContext(legend + " renaming", args, require_empty=True)
    for arg in ctx.args:
        metadata = History(arg)
        if name not in metadata.symbols:
            croak("in %s, cannot rename nonexistent %s %s" % (arg, legend, name))
        if newname in metadata.symbols:
            croak("in %s, cannot rename to existing %s %s" % (arg, legend, name))
        ctx = CommandContext(legend, args)
        if not ctx.is_empty():
            croak("can't accept a revision-spec when renaming a %s." \
                  % legend)
        # In the case of a branch, we want to change only the
        # tag reference.
        with backend.lifter(arg):
            backend.set_tag(newname, metadata.symbols[name], metadata)
            backend.delete_tag(name, metadata)
        if not quiet and len(args) > 1:
            announce("in %s, %s -> %s" % (arg, name, newname))

def filecmd(legend, hook, args):
    CommandContext(legend, args, require_empty=True)
    if len(args) != 2:
        croak("%s requires exactly two arguments" % legend)
    (source, target) = args
    if not os.path.exists(source):
        croak("I see no '%s' here." % source)
    elif not registered(source):
        croak("%s is not registered, skipping" % source)
    elif registered(target):
        croak("%s is registered, I won't step on it" % source)
    elif os.path.exists(target):
        croak("%s exists, please delete manually if you want it gone" % target)
    else:
        hook(source, target)

def move_method(*args):
    "Move a file and its history."
    filecmd("move", backend.move, args)

def copy_method(*args):
    "Copy a file and its history."
    filecmd("copy", backend.copy, args)

def release_method(*args):
    "Release locks."
    ctx = CommandContext("release", args, require_empty=True)
    for arg in ctx.args:
        if not os.path.exists(arg):
            croak("I see no '%s' here." % arg)
        elif not registered(arg):
            croak("%s is not registered, skipping" % arg)
        else:
            with backend.lifter(arg):
                backend.release(arg)

def ls_method(*args):
    "List registered files."
    if args:
        croak("ls cannot accept arguments")
    try:
        masters = [fn for fn in os.listdir(repodir) if is_history(fn)]
    except OSError:
        croak("repo directory %s does not exist" % repodir)
    masters.sort()
    for master in masters:
        sys.stdout.write(backend.workfile(master) + "\n")

def fast_export_method(*args):
    "Dump revision content to standard output."
    ctx = CommandContext("fast-export", args)
    mark = 0
    if pseudotime:
        username = "J. Random Hacker"
        useremail = "jrh@nowhere.man"
    else:
        username = capture_or_die("git config --get user.name").strip()
        useremail = capture_or_die("git config --get user.email").strip()
    attribution = "%s <%s>" % (username, useremail)
    for arg in ctx.args:
        if not registered(arg):
            croak("%s is not registered" % arg)
        executable = os.stat(arg).st_mode & stat.S_IXUSR
        if executable:
            perms = "100755"
        else:
            perms = "100644"
        metadata = History(arg)
        ctx.resolve(metadata)
        if ctx.is_empty():
            ctx.select_all(metadata)
        with backend.lifter(arg):
            markmap = {}
            last_commit_mark = 0
            if len(args) == 1:
                branch = "master"
            else:
                # FIXME: Sanitize branch names.
                # FIXME: Make this canonical even with tags
                branch = arg + "master"
            for i in range(ctx.start, ctx.end+1):
                item = metadata.by_revno(i)
                scratchfile = "/tmp/src%dtmp" % os.getpid()
                backend.cat(arg, item.native, scratchfile)
                size = os.path.getsize(scratchfile)
                mark += 1
                markmap[item.revno] = mark
                sys.stdout.write("blob\nmark :%d\ndata %d\n" % (mark, size))
                sys.stdout.write(open(scratchfile).read() + "\n")
                if item.revno == ctx.start:
                    if ctx.start == 1:
                        sys.stdout.write("reset refs/heads/%s\n" % branch)
                    else:
                        sys.stdout.write("from refs/heads/%s^0\n" % branch)
                sys.stdout.write("commit refs/heads/%s\n" % branch)
                sys.stdout.write("mark :%d\n" % (mark + 1))
                sys.stdout.write("author %s %d +0000\n" % (attribution, item.unixtime()))
                sys.stdout.write("committer %s %d +0000\n" % (attribution, item.unixtime()))
                sys.stdout.write("data %s\n%s" % (len(item.log), item.log))
                if last_commit_mark:
                    sys.stdout.write("from :%d\n" % last_commit_mark)
                if len(arg.split()) > 1:
                    arg = '"' + arg + '"'
                sys.stdout.write("M %s :%d %s\n\n" % (perms, mark, arg))
                mark += 1
                last_commit_mark = mark
                markmap[item.revno] = mark
            sys.stdout.write("reset refs/heads/%s\nfrom :%d\n\n" % (branch, mark))
            for (key, val) in list(metadata.symbols.items()):
                val = metadata.native_to_revno(val)
                if val in ctx:
                    sys.stdout.write("reset refs/tags/%s\nfrom :%d\n\n" % (key, markmap[val]))

def fast_import_method(*args):
    "Accept a git fast-import stream on stdin, turn it into file histories."
    if os.path.exists("RCS"):
        croak("refusing to unpack into existing RCS directory!")
    # Force -l to fit SRC's lockless interface.
    do_or_die(r"rcs-fast-import -l " +" ".join(args))
    for fn in os.listdir("RCS"):
        corresponding = os.path.join("RCS", os.path.basename(fn))
        if os.path.exists(fn):
            croak("%s exists, aborting leaving RCS in place!" % corresponding)
        os.rename(fn, corresponding)
    shutil.rmtree("RCS")


def version_method(*args):
    "Report SRC's version"
    sys.stdout.write("%s\n" % version)

dispatch = {
    "help":        help_method,
    "commit":      commit_method,
    "ci":          commit_method,
    "amend":       amend_method,
    "am":          amend_method,
    "list":        list_method,
    "li":          list_method,
    "log":         log_method,
    "checkout":    checkout_method,
    "co":          checkout_method,
    "status":      status_method,
    "st":          status_method,
    "cat":         cat_method,
    "diff":        diff_method,
    "di":          diff_method,
    "tag":         tag_method,
    "branch":      branch_method,
    "rn":          rename_method,
    "rename":      rename_method,
    "ls":          ls_method,
    "move":        move_method,
    "mv":          move_method,
    "copy":        copy_method,
    "cp":          copy_method,
    "fast-export": fast_export_method,
    "fast-import": fast_import_method,
    "release":     release_method,
    "version":     version_method,
}

class RCS:
    "Encapsulate RCS back end methods."
    delimiters = ('----------------------------',
                  '=============================================================================')
    class RCSLifter:
        "Temporarily lift a master to the working directory."
        def __init__(self, name):
            self.name = name
            self.where = os.getcwd()
        def __enter__(self):
            if os.path.dirname(self.name):
                os.chdir(os.path.dirname(self.name))
            do_or_die("mv {0}/{1},v .".format(repodir, self.name))
        def __exit__(self, extype, value, traceback_unused):
            os.chdir(self.where)
            if extype and debug > 0:
                raise extype(value)
            do_or_die("mv {0},v {1}".format(self.name, repodir))
            return True
    def lifter(self, name):
        return RCS.RCSLifter(name)
    def history(self, arg):
        return os.path.join(os.path.dirname(arg),
                            repodir,
                            os.path.basename(arg) + ",v")
    def has_revisions(self, arg):
        "Does the master for this file have any revisions"
        # The magic number 105 is the size of an empty RCS file (no
        # metadata, no revisions) at 76 bytes, plus 29 bytes. We
        # assume that this size has stayed constant or increased since
        # ancient times. In fact the size of an RCS file with revisions
        # goes up more - by the 78 bytes for the final, fixed line of the
        # log display.  This gives us plenty of slack to cope with
        # minor format differences.
        #
        # The motivation here is to make "src status" faster by avoiding
        # the need for an entire log parse when checking for "A"
        # status.
        return os.path.getsize(self.history(arg)) > 105
    def workfile(self, arg):
        "Workfile corresponding to an RCS master"
        return arg[:-2]
    def splitrev(self, rev):
        "RCS revision to numeric tuple."
        return [int(d) for d in rev.split(".")]
    def joinrev(self, rev):
        "Numeric tuple to RC revision."
        return ".".join([str(d) for d in rev])
    def pred(self, rev):
        "Our predecessor. Walks up parent branch."
        n = self.splitrev(rev)
        if n[-1] > 1:
            n[-1] -= 1
            rev = self.joinrev(n)
        else:
            rev = self.joinrev(n[:-2])
        return rev
    def succ(self, rev):
        "Our successor."
        if rev:
            n = self.splitrev(rev)
            n[-1] += 1
            return self.joinrev(n)
        else:
            return "1.1"
    def isbranch(self, symbol):
        "Is this a branch symbol?"
        return "0." in symbol
    def branch_to_parent(self, revid):
        "Go from a branch ID sticky tag to the revision it was based on."
        # Must return an empty string for the fake root sticky tag.
        return self.joinrev(self.splitrev(revid)[:-2])
    def branch_to_base(self, revid, metadata):
        "Go from a branch ID sticky tag to the first revision of its branch."
        rev = self.branch_to_parent(revid)
        if rev:
            rev += ".1.1"
        else:
            rev = "1.1"
        return rev
    def branch_to_tip(self, revid, metadata):
        "Go from a branch ID sticky tag to the tip revision of its branch."
        rev = self.branch_to_base(revid, metadata)
        while True:
            nxt = self.succ(rev)
            if metadata.native_to_revno(nxt) is None:
                return rev
            else:
                rev = nxt
        croak("internal error: couldn't find branch tip of %s" % rev)
    def add(self, arg):
        "Register a file"
        # Key choices here: -b suppresses all keyword expansion, -U sets
        # non-strict locking (which makes branch appends less painful).
        do_or_die("grcs -q -U -kb -i {0} </dev/null && mv {0},v {1}".format(arg, repodir))
    def checkin(self, arg, comment):
        "Check in a commit, with comment."
        comment = "'" + comment.replace("'", r"'\''") + "'"
        # If the user changed the executable bit while modifying the
        # workfile, propagate this change to the master.  Without this
        # hack, the sequence (1) Commit workfile (2) Make workfile
        # executable, (3) checkin workfile fails to work as expected
        # because RCS doesn't propagate the changed executable bit to
        # the master, leading to misbehavior on the next checkout.
        if os.path.exists(arg + ",v"):
            oldmastermode = newmastermode = os.stat(arg + ",v").st_mode
            userworkmode = os.stat(arg).st_mode
            for bitmask in (stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH):
               if bitmask & userworkmode: 
                   newmastermode |= bitmask
               else:
                   newmastermode &=~ bitmask
            if newmastermode != oldmastermode:
                os.chmod(self.history(arg), newmastermode)
        # By unlocking the file before checkin we invoke the following
        # property described on the rcs(1) manual page: "If rev is
        # omitted and the caller has no lock, but owns the file and
        # locking is not set to strict, then the revision is appended
        # to the default branch (normally the trunk; see the -b option
        # of rcs(1))."  This is the behavior we want and why locking
        # is set to non-strict.
        do_or_die("grcs -q -U -u {0},v && gci -l -m{1} {0}".format(arg, comment))
    def checkout(self, arg, revision):
        "Check out a revision. Leaves it writeable."
        do_or_die("rm -f {0} && grcs -q -u {0},v && gco -q -l{1} {0}".format(arg, revision))
    def amend(self, arg, rev, comment):
        "Amend a commit comment."
        # Relies on caller to escape comment string
        comment = "'" + comment.replace("'", r"'\''") + "'"
        do_or_die("grcs -m{0}:{1} {2}".format(rev, comment, arg))
    def cat(self, arg, revision, fn=""):
        "Ship the contents of a revision to stdout or a named file."
        if fn:
            arg += " >" + fn
        do_or_die("gco -q -p -r{1} {0}".format(arg, revision), loud=True)
    def delete_tag(self, tagname, metadata):
        "Delete a specified tag."
        do_or_die("grcs -n{0} {1}".format(tagname, metadata.name))
    def set_tag(self, tagname, revision, metadata):
        "Set a specified tag."
        do_or_die("grcs -n{0}:{1} {2}".format(tagname, revision, metadata.name))
    def delete_branch(self, branchname, metadata):
        "Delete a specified branch."
        # From rcs(1): -orange deletes ("outdates") the revisions
        # given by range.  A range consisting of a single revision
        # number means that revision. A range consisting of a branch
        # number means the latest revision on that branch.  A range of
        # the form rev1:rev2 means revisions rev1 to rev2 on the same
        # branch, :rev means from the beginning of the branch
        # containing rev up to and including rev, and rev: means from
        # revision rev to the end of the branch containing rev.  None
        # of the outdated revisions can have branches or locks.
        #
        # What we need do is find the branch tip, then walk back to
        # just after the first point where it joins another branch,
        # then do a delete to end of branch from there.
        base = self.branch_to_tip(metadata.symbols[branchname], metadata)
        while True:
            if base is not None and metadata.by_native_d[base].branches:
                break
            else:
                base = self.pred(base)
        do_or_die("grcs -o{0}: {1}".format(self.succ(base), metadata.name))
        self.delete_tag(branchname, metadata)
    def set_branch(self, name, revision, metadata):
        "Set the specified branch to be default, creating it if required."
        if name in metadata.symbols:
            # Must unstickify...
            base = metadata.symbols[name].split(".")
            base = base[:-2] + base[-1:]
            base = ".".join(base)
        else:
            def branchfrom(c, p):
                "Is c a branch child (not direct descendant) of parent p?"
                c = c.split(".")
                p = p.split(".")
                return len(c) == len(p) + 2 and c[len(p):] == p
            baserev = metadata.current()
            newsib = len([item for item in metadata.revlist \
                         if branchfrom(item.native, baserev)])
            newsib += 1
            base = baserev + "." + str(newsib)
            sticky = baserev + ".0." + str(newsib)
            do_or_die("grcs -n{0}:{1} {2}".format(name, sticky, arg), loud=True)
        do_or_die("grcs -b%s %s" % (base, metadate.name), loud=True)
    def move(self, source, target):
        "Move a file and its history."
        do_or_die("mv {0} {1} && mv {2} {3}".format(source, target,
                                                    self.history(source),
                                                    self.history(target)))
    def copy(self, source, target):
        "Copy a file and its history."
        do_or_die("cp {0} {1} && cp {2} {3}".format(source, target,
                                                    self.history(source),
                                                    self.history(target)))
    def diff(self, diffspec1, diffspec2, diffopts, arg):
        "Report a diff."
        if diffspec1:
            diffspec1 = "-r" + diffspec1
        if diffspec2:
            diffspec2 = "-r" + diffspec2
        # The || : is a hacky shell trick that suppresses the error
        # return from diff(1).
        do_or_die("grcsdiff -q {0} {1} {2} {3} || :\n".format(diffspec1, diffspec2, diffopts, arg), loud=True)
    def release(self, arg):
        "Release locks."
        do_or_die("grcs -q -u {0},v".format(arg))
    def parse(self, metadata):
        "Get and parse the RCS log output for this file."
        metadata.symbols["trunk"] = "0.1"
        with popen_or_die("cd %s >/dev/null; rlog %s 2>/dev/null; cd ..>/dev/null" % (repodir, metadata.name)) as fp:
            if debug >= DEBUG_PARSE:
                sys.stderr.write("\t-> init\n")
            state = "init"
            for line in fp:
                if debug >= DEBUG_PARSE:
                    sys.stderr.write("in: %s\n" % repr(line))
                if state == "init":
                    if line.startswith("locks:"):
                        if debug >= DEBUG_PARSE:
                            sys.stderr.write("\t-> locks\n")
                        state = "locks"
                    elif line.startswith("symbolic names:"):
                        if debug >= DEBUG_PARSE:
                            sys.stderr.write("\t-> symbols\n")
                        state = "symbols"
                    elif line.startswith("branch:"):
                        branch = line.split(":")[1].strip()
                        # Undocumented fact about RCS: The branch "1" is
                        # the same as the blank branch.  Significant because
                        # you can't reset to the blank branch using grcs -b,
                        # that resets to the dynamically highest branch.
                        if not branch or branch == "1":
                            metadata.branch = "trunk"
                    elif line.startswith("----------------------------"):
                        if debug >= DEBUG_PARSE:
                            sys.stderr.write("\t-> logheader\n")
                        state = "logheader"
                        metadata.revlist.append(HistoryEntry(metadata))
                elif state == "locks":
                    if not line[0].isspace():
                        if debug >= DEBUG_PARSE:
                            sys.stderr.write("\t-> init\n")
                        state = "init"
                    else:
                        fields = line.strip().split()
                        metadata.lockrevs.append(fields[1])
                elif state == "symbols":
                    if not line[0].isspace():
                        if debug >= DEBUG_PARSE:
                            sys.stderr.write("\t-> init\n")
                        state = "init"
                    else:
                        fields = line.strip().split()
                        name = fields[0]
                        if name.endswith(":"):
                            name = name[:-1]
                        rev = fields[1]
                        metadata.symbols[name] = rev
                elif state == "logheader":
                    if line.startswith("revision "):
                        fields = line.split()
                        metadata.revlist[-1].native = fields[1]
                    elif line.startswith("----------------------------"):
                        metadata.revlist.append(HistoryEntry(metadata))
                    elif line.startswith("date: "):
                        fields = line.split()
                        date = fields[1] + " " + fields[2]
                        if date.endswith(";"):
                            date = date[:-1]
                        date = date.replace("/","-").replace(" ","T") + "Z"
                        metadata.revlist[-1].date = date
                    elif line.startswith("branches:"):
                        continue
                    elif line.startswith("======================="):
                        if not metadata.revlist[-1].log.endswith("\n"):
                            metadata.revlist[-1].log += "\n"
                        break
                    elif line.strip() == "*** empty log message ***":
                        continue
                    elif metadata.revlist:
                        metadata.revlist[-1].log += line
            # Now that we have the symbol table...
            if metadata.branch != "trunk":
                for (k, v) in list(metadata.symbols.items()):
                    if v == metadata.branch:
                        metadata.branch = k
                        break
                else:
                    croak("unrecognized branch ID '%s'" % branch)
            metadata.revlist.sort(key=lambda x: x.date)
            for (i, item) in enumerate(metadata.revlist):
                if pseudotime:
                    # Artificial date one day after the epoch
                    # to avoid timezone issues.
                    item.date = rfc3339(86400 + i * 60)
                item.revno = i + 1
            metadata.revlist.reverse()
            if debug >= DEBUG_PARSE:
                #print "\t%d revisions" % len(metadata.revlist)
                print("\tlockrevs:", metadata.lockrevs)
                print("\tsymbols:", metadata.symbols)

if __name__ == "__main__":
    try:
        commandline = list(sys.argv[1:])
        explicit = False
        while commandline and commandline[0].startswith("-"):
            if commandline[0] == '-d':
                debug += 1
            elif commandline[0] == '-q':
                quiet = True
            elif commandline[0] == '-T':
                pseudotime = True
            elif commandline[0] == '-S':
                repodir = commandline[1]
                explicit = True
                commandline.pop(0)
            else:
                croak("unknown option %s before command verb" % commandline[0])
            commandline.pop(0)

        # RCS backwards-compatibility hack
        if not explicit and not os.path.exists(repodir) and  os.path.exists("RCS"):
            repodir = "RCS"

        # Presently there is only one backend
        backend = RCS()

        if not commandline:
            help_method()
        else:
            if commandline[0] in dispatch:
                dispatch[commandline[0]](*commandline[1:])
            else:
                croak("no such command as '%s'.  Try 'src help'" \
                               % commandline[0])
    except KeyboardInterrupt:
        pass

# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End:
