You may borrow an implementation from, say, Mercurial or Subversion. For me it looks easy.