src-1.33/control0000664000175000017500000000150314544356354012014 0ustar esresr# This is not a real Debian control file # It's project metadata for the shipper tool # SPDX-FileCopyrightText: Copyright Eric S. Raymond # SPDX-License-Identifier: BSD-2-Clause Package: src Description: Simple Revision Control is RCS/SCCS reloaded with a modern UI, designed to manage single-file solo projects kept more than one to a directory. Use it for FAQs, ~/bin directories, config files, and the like. Features integer sequential revision numbers, a command set that will seem familiar to Subversion/Git/Mercurial users, and no binary blobs anywhere. Homepage: http://www.catb.org/~esr/src XBS-Repository-URL: https://gitlab.com/esr/src XBS-HTML-Target: index.html XBS-Logo: src-logo.png #XBS-Project-Tags: RCS, SCCS, version control XBS-VC-Tag-Template: %(version)s XBS-Validate: make check src-1.33/COPYING0000664000175000017500000000235514412657706011451 0ustar esresr BSD 2-Clause LICENSE Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. src-1.33/FAQ.adoc0000664000175000017500000002261314544356237011655 0ustar esresr= SRC FAQ = version 1.7 // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: CC-BY-4.0 [[why]] == Why SRC instead of $VCS? == Most version control systems today are multi-user, multi-file, and multi-branch oriented. These are all good features and properties to have, but they neglect the occasional need to maintain simple single-file documents, such as HOWTOs and FAQs, much like the very file you are reading now. There is even a good use-case for small programs and scripts. Do you presently keep your `~/bin` contents under version control? If not, consider using SRC for them. [[another-vcs]] == $VCS already does single-file version control, why another one? == It is true, other VCSes already fulfill this simple criterion, SCCS and RCS being some of the earliest examples dating back to the 1970s and 1980s. While SCCS died off due to its proprietary nature, https://www.gnu.org/software/rcs[RCS] has kept a niche for itself precisely for single-file projects. In fact, SRC is built on top of RCS, rather than reimplementing all of the gritty master file details. The idea that spawned the development of SRC was that it would have these five properties: 1. Only deals with single files. Use for HOWTOs, memoranda, scripts, etc. 2. Allows multiple histories to live in the same directory without entanglement. 3. Has a human-readable master-file representation - no binary blobs. 4. Modern CLI user-interface. Commands familiar to Subversion, Hg, Git users. 5. Integer sequential revision numbers a la Subversion. Notably, RCS itself fails on the latter two criteria. Designed both as an early attempt at VCS and for multi-user environments, the commands are awkward to deal with and it requires complicated processes of locking and unlocking files in order to edit and commit them. None of this is appropriate anymore. Modern DVCSes with a non-locking model have proven more effective even for multi-user projects, let alone single-user ones that will never have contention issues. Other projects to mold Mercurial and Git for a single-file purpose will at the _very_ least fail criteria #3 and #5, and often #4 as well. [[dvcs-obsoletion]] == Does SRC mean that $DVCS is obsolete? == Absolutely not! SRC and DVCSes serve entirely opposite needs. SRC’s strength is precisely when there is neither need nor desire for collaboration or publishing features, when there is only a single file and a single author for a file. In fact, if your script grows into a full project in its own right, SRC has a `src fast-export` command that can be used to jump-start a DVCS repository with the entire existing history intact. SRC might make certain uses of DVCS obsolete, such as keeping individual documents tucked away in their own directories so that the DVCS (which usually has a special repository directory named like `.hg` or `.git`) can operate. Scripts to impose a single-file concept on top of these systems do not go <> with respect to the reasons SRC exists. [[self-hosting]] == Is SRC used to develop itself? == No. That would be silly. SRC is a real software project, with several files that do, and should, have joint history. It has a public Git repository. SRC has had real users (that is, other than the author) since day two after it was announced, but not for projects like itself. [[bare-rcs]] == I still use plain RCS for single files. Why move to SRC? == Because process friction matters, even to hackers as ancient as you and the author of SRC. Bare RCS's interface is pretty awful; a competently-designed UI can reduce that friction considerably. Try it and see. If you use RCS through Emacs's VC mode, you already have a pretty good wrapper around it...which, as it happens, the author of SRC also wrote. SRC has a couple of advantages over VC-RCS - running lockless, better scriptability, and ditching RCS's ugly revision numbering are the main ones. SRC is now a fully-supported VC-mode system in Emacs, so you can run SRC through Emacs and get the lockless operation and Subversion-style revision numbers. [[beginners-vcs]] == Is SRC a good system on which to learn about version control? == *YES*! SRC is explicitly designed to have the bare-bones features and commands of a modern version control system. Keep in mind that SRC’s strength is single-file documents and projects. If you have loose scripts and documents not presently under any version control, SRC is a good candidate for playing around with them. If instead you have a large multi-file project, ease yourself into using a DVCS with simple commands, possibly even using SRC’s command set as a guideline for which ones to learn first. You will appreciate having actual changesets that span multiple files in this use case. http://mercurial.selenic.com/[Mercurial] and http://git-scm.com/[Git] are the most common, which means they are also easy to find help for. [[keywords]] == Does SRC have keyword expansion? == No. When SRC commits a file with RCS on the backend, it uses `-kb` which explicitly disables all kind of expansion, and also allows arbitrary binary files to be stored. The SCCS backend always checks out files with -e, implying -k and no keyword expansion. Keyword expansion has, in general, not been well-accepted in the VCS world, most modern VCSes do not support it at all, and the author of SRC thinks it was a terrible idea. Do not even suggest this feature, it will not be implemented. [[missing-features]] == Does SRC have $FEATURE? == If you don’t see it in the `src help` listing, probably not. You are certainly free to suggest features, but SRC is developed with extreme conservatism as to what features to implement or not. Remember, single-file, single-user, private VCS. Before requesting a feature, ask yourself whether it makes SRC more complicated, whether it really helps a single author or developer, and whether it really makes sense to deploy SRC for your use-case instead of a DVCS. These can all be hard questions, and if you are in doubt, you may go forth with your request, others may share their own opinions. SRC shines in its simplicity. Any individual feature is not necessarily against this, but too many can easily creep over into ``too complicated'' territory. [[network]] == How well does SRC handle files over the network? == The answer is either "`completely fine`" or "`not at all`", depending on what is being asked. :-) SRC makes no special provisions, it operates in the current working directory whether that is local storage, NFS, CIFS, sshfs, or any other kind of networking file system. As long as the directory tree is mounted on your system, SRC should be able to handle it. [[status-inconsistency]] == Why doesn’t src status display show the same letters as $VCS? == Ah, yes, everybody's favorite bikeshedding topic. Consistency with other version control systems is an important way to reduce any kind of surprises while using SRC. Unfortunately, the single-letter codes used for statuses are not identical between VCSes and often conflict with each other over specific meanings. For example, *D* means 'deleted' in Subversion and Git, but Mercurial uses *R* for that same meaning. Git uses *R* to mean 'renamed', while Subversion uses it to mean 'replaced'. It is an unfortunate state of affairs. The development philosophy behind SRC is to keep it as un-innovative and unsurprising as possible, but since multiple VCSes in widespread use have not converged on the same meanings for single-letter status codes, SRC needs to settle on its own definitions that may differ from what you are used to. [[SCCS]] == Why did you bother with SCCS support? == Because some hacks that are useless or marginal are way too funny not to do anyway. This one was *hilarious*...if you have a hacker's sense of humor. If you don't, never mind. [[not-a-joke]] == Um. This is all a joke, right? == No, though the author admits he did laugh a lot while roughing out the original design. Resurrect RCS? Wrap it in a decent UI? _Really?_ There's a significant amount of ha-ha-only-serious here. Laugh, but treat SRC as a lesson in several things. Unix minimalism. The virtue of re-use, even of technology as old as RCS. The effectiveness of a carefully crafted UI. The value of a conservative design with no surprises and no undue cleverness. [[reporting-bugs]] == How should I report bugs in SRC? == This isn't really a FAQ, as nobody has asked it frequently enough; SRC is simple, carefully-tested code and bugs in it have been rare. Still... The first thing to do is pull the tip version from the project repository and verify that it still exhibits the bug. If it doesn't, you need read no further. When you have a bug persists with the repository tip version, the author needs three things: 1. An exact description of how you tickled the bug, which should at least include the SRC command or sequence of commands that produced it. 2. A copy of the repository file(s) over which the bug was triggered. 3. The output of "`src version`". Points for style if you send a tarball that unpacks into a directory containing relevant workfiles, their .src/RCS/SCCS subdirectory, a file of SRC commands to reproduce the bug (named 'tickleme' or 'fooup' or something distinctive), and a README listing the "`src version`" output and circumstances. If you can supply all this information, expect bug resolution to be very rapid. [[ack]] == Acknowledgments == Most of this FAQ was originally written by Mike Swanson, aka chungy. // end src-1.33/INSTALL.adoc0000664000175000017500000000225214544356237012351 0ustar esresr= Installing SRC = // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: BSD-2-Clause Either have "python3" on your $PATH and put src somewhere on your $PATH, or call a Python interpreter explicity tor reun SRC. Python 2.7 or any Pyton 3.x interpreter for x >= 3. Have RCS or SCCS or both installed on your system. The RCS this was written against is GNU 5.9.4 under Linux. OS X 5.9.4 has slightly different behavior but works. Amazon Linux running 5.7 also gives good results. The GNU version of SCCS, CSSC or "Compatibly Stupid Source Control", will do; the SunOS and Schilling versions remove some minor limitations. Installing the documentation requires asciidoc. If you want to use the "visualize" command, you will need to install the graphviz package to get dot(1). There's a 'make install' production you can use that also installs the manual page. It will require root permissions. Doing 'make check' performs a comprehensive test of the software. You must have both RCS and SCCS installed for this to work. If you have rcs-fast-import instakked, it mus be at version 1.3 or later. The FAQ has a section on how to report bugs. src-1.33/Makefile0000664000175000017500000000346114544356370012054 0ustar esresr# Makefile for src # # SPDX-FileCopyrightText: Copyright Eric S. Raymond # SPDX-License-Identifier: BSD-2-Clause prefix?=/usr/local mandir?=/share/man target=$(DESTDIR)$(prefix) VERS=$(shell ./src version | sed -n -e "/src: /s///p") SOURCES = README.adoc INSTALL.adoc COPYING NEWS.adoc TODO.adoc src srctest tapview src.adoc FAQ.adoc Makefile control all: src.1 check: pylint shellcheck @./srctest | ./tapview coverage: @./srctest -c coverage-data | ./tapview @coverage report --data-file=coverage-data | grep src @coverage html --data-file=coverage-data .SUFFIXES: .html .adoc .1 # Requires asciidoc and xsltproc/docbook stylesheets. .adoc.1: a2x --doctype manpage --format manpage $< .adoc.html: a2x --doctype manpage --format xhtml -D . $< rm -f docbook-xsl.css FAQ.html: FAQ.adoc asciidoc -a toc FAQ.adoc clean: rm -f *~ *.1 *.html *.tar.gz MANIFEST coverage-data rm -fr .rs* typescript test/typescript htmlconv src-$(VERS).tar.gz: $(SOURCES) src.1 @ls $(SOURCES) src.1 | sed s:^:src-$(VERS)/: >MANIFEST @(cd ..; ln -s src src-$(VERS)) (cd ..; tar -czf src/src-$(VERS).tar.gz `cat src/MANIFEST`) @(cd ..; rm src-$(VERS)) pylint: @pylint --score=n src shellcheck: @-shellcheck -s sh -f gcc srctest version: @echo $(VERS) fixme: @if command -v rg >/dev/null; then \ rg --no-heading FIX''ME; \ else \ find . -type f -exec grep -n FIX''ME {} /dev/null \; | grep -v "[.]git"; \ fi dist: src-$(VERS).tar.gz release: src-$(VERS).tar.gz src.html FAQ.html shipper version=$(VERS) | sh -e -x refresh: src.html FAQ.html shipper -N -w version=$(VERS) | sh -e -x install: all install -d "$(target)/bin" install -d "$(target)$(mandir)/man1" install src "$(target)/bin" install -m644 src.1 "$(target)$(mandir)/man1" uninstall: rm "$(target)/bin/src" "$(target)$(mandir)/man1/src.1" src-1.33/NEWS.adoc0000664000175000017500000002145514544571274012025 0ustar esresr= src project news = // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: CC-BY-4.0 1.33: 2024-01-01:: When standard output is a tty, help is shipped via the pydoc pager. Now works with a .src subdir even when an unrelated RCS subdir exists. SCCS pseudo-branch support is gone (bare SCCS could not see them) Current branch is now set on checkout as well as checkin. Make fast-export issue a sourcetype comment for reposurgeon's use. fast-export renames .srcignore to .gitignore in the stream. src status -q suppresses listing of untracked files. src init command added to reduce surprise. 1.32: 2023-04-24:: File arguments can now be paths, and the right thing will happen. Behave more gracefully if EDITOR is not set and emacsclient is absent. 1.31: 2023-02-27:: Fixed bug in branch creation. ci has new -b option for checkin on a named branch. branch -l now indicates the current branch with "*". 1.30: 2022-01-21:: Now requires python3, since Ubuntu broke the "python" link. Fixed a bug in parsing of diff command with --. 1.29: 2021-08-20:: Resynch fast-export behavior with git - no more branch-tip resets. Filenames with embdedded spaces are now processed correctly. Ubuntu has abolished /usr/bin/python, change shebang to python3. 1.28: 2020-02-03:: Restore terminal-size computation inside Emacs. 1.27: 2019-09-05:: Port fix for Solaris, which lacks a size operation in stty. Cope with the deprecation of the cgi module in Python 3. 1.26: 2019-05-12:: Change name of "lift" command to "srcify". Proper inline documentation for srcify. Repair make check; do setup to perform validation before shipping. 1.25: 2019-05-10:: New "lift" command for changing RCS and SCCS directories to be SRC-managed. 1.24: 2019-02-07:: More fast-export bug fixes - make multifile export work properly. 1.23: 2019-02-06:: Repair a serious bug in src fast-export 1.22: 2018-12-06:: Correct behavior verified with OS X (which provides RCS 5.9.4). Correct behavior verified with Amazon Linux (which provides RCS 5.7). Correct behavior verified under OpenBSD, which has its own RCS port. The SCCS back end now supports tagging. To avoid errors, src will bail out if both .src and RCS directories exist. 1.21: 2018-11-27:: Now tested with Schilling fork of SCCS. One minor bugfix in SCCS back end. 1.20: 2018-10-28:: Add platform to "src version" output to make bug reports easier to generate. Signal-harden backend command execution. 1.19: 2018-10-27:: Filenames containing embedded spaces are handled properly. The '--' token is interpreted correctly in cat commands. 1.18: 2018-03-17:: Fix out-of-order 'revno' assignment when commits share same date. 'list' & 'log' suppress RFC 822 headers inserted by 'fast-import'. 'log' gained '-v' verbosity levels to show imported RFC 822 headers. 'list' & 'log' show author date if in RFC 822 headers rather than committer. Improved 'fast-import/export' round-trip fidelity using RFC 822 headers. 1.17: 2017-11-14:: Show diff of changes to be committed when editing/amending commit comment. 'src commit' no longer opens editor when file has not been changed. 'src diff' and 'src log' accept '-b' & '-w' to ignore whitespace changes. 'git log -p 1' shows "big bang" creation diff (previously no diff for r1). Commands now operate on all managed files (as documented) when none given. Colored output no longer crashes under Python 3. 'src log -' is alias for '-l ' a la 'git log -'; ditto 'src list'. 1.16: 2017-11-05:: Output of src diff & src log are colorized a la git when issuing to terminal. 'src log' now accepts '-p' to emit patches a la 'git log -p'. 1.15: 2017-10-30:: Fixes for fast-import, fast-export, and exec-bit propagation. 1.14: 2017-10-17:: Slightly improved boilerplate commit message. Fix for a minor command-parsing bug. 1.13: 2017-03-26:: Improvement to tempfile handling; avoid wiring in /tmp. 1.12: 2017-01-24:: Pylint cleanup, minor documentation fixes, and Python 3 port tweaks. 1.11: 2016-02-23:: Now handles binary repository data cleanly under Python 3. Version command reports versions for the underlying Python and back end. 1.10: 2016-02-18:: Code now runs under either Python 2 or Python 3. Restore (undocumented) add command for Emacs VC compatibility. 1.9: 2016-02-15:: Fix status-computation bug introduced in 1.8. SCCS parsing can no longer be fooled by comment lines resembing delta headers. 1.8: 2016-02-14:: Stamp files are no longer used; all SRC state is carried in the master itself. 1.7: 2016-02-10:: New 'visualize' command makes a DOT/graphviz visualization of repo structure. It is now possible to range-restrict a tag or branch listing. 1.6: 2016-02-08:: Improved prs log parsing in SCCS back end allows blank lines in comments. SCCS regression tests now really work (previously a false positive). 1.5: 2016-02-07:: Bugfixes for SCCS support. It now has its own regression test. Documentation and FAQ update for the new back end. 1.4: 2016-02-05:: Basic SCCS support - no branches or tags, limited diffs. The diff command no longer leaks native commit IDs onto the screen. In fast-export, properly sanitize RCS branch names illegal for git. 1.3: 2016-02-04:: Make SRC able to drive RCS v5.7 (previously needed v5.8 or later). If you change nothing in the template commit during edit, commit is canceled. 1.2: 2016-01-29:: Documentation improvements based on user feedback. 1.1: 2016-01-27:: Avoid upchucking on status A files if we happen to go through a modify check. Add regression test for commit-comment editing. Force binary I/O - a step towards Python 3 porting. 1.0: 2016-01-26:: Now hosted on gitlab. Fix for Tom Willemse's multi-file commit bug. 0.19: 2015-04-02:: A pylint audit caught two unbound variables in odd cases. 0.18: 2014-12-23:: Reversed range expressons are now supported. In list and log, explicit ranges are no longer reversed. 0.17: 2014-12-19:: Undocumented 'add' command abolished; Emacs VC will use 'commit -a' instead. 0.16: 2014-12-18:: Allow -- as an argument ender in src diff. Changes to a workfile's x bits are propagated to its master on checkin. 0.15: 2014-12-08:: Deal gracefully with directories passed as arguments. 0.14: 2014-11-29:: Fixed bugs affecting argument parsing in the presence of numeric filenames. 0.13: 2014-11-24:: Fixed bug that caused spurious modified status after commit. 0.12: 2014-11-21:: Log command shows the branch in the header line for each revision. List and log command now have an -l option to play nice with Emacs VC. 0.11: 2014-11-19:: File-not-modified status character changed to '=' to match Mercurial. Fixed-width cutlines and list -f option support Emacs VC mode. 0.10: 2014-11-19:: Modified check is now done by content, not modification date. 0.9: 2014-11-16:: SRC is now feature-complete as planned. Branch deletion is implemented and tested. 'src rename' now renames tags and branches - no longer an alias for 'move'. In tag and branch, a 'create' or '-c' modifier is now required to make tags. 0.8: 2014-11-14:: A branch label names the tip revision of its branch. src log and src list skip ignored and unregistered files in arguments. The embedded help has been enriched and now features multiple topics. ! works to negate patterns in ignore files. src status -a forces status display of all files, including I and ?. 0.7: 2014-11-13:: Bugfix release: fix initial file commit. There was a bug in my tests... 0.6: 2014-11-12:: Useful boilerplate in commit and amend message buffers. Tag names for revisions work; so does tag renaming. Branch-sensitive traversal with .. is working. Fixed yet another fast-export bug. 0.5: 2014-11-11:: Removed src add. The first src commit to a file adds it. Branching is mostly working - branch delete isn't implemented, Tag and branch names to identify revisions don't work yet. 'U' (unmodified) becomes '.' in src status listings. src fast-export was broken in 0.4, it's fixed now. Added src version. 0.4: 2014-11-10:: Improvements to src fast-import. src commit now has an -e option to force editing after -m or -f. There is now a "src amend". 0.3: 2014-11-09:: There is now a "src status" command, and .srcignore affects it. src fast-import is implemented (by callout to rcs-fast-import). 0.2: 2014-11-08:: There is a public repository on Gitorious All the initially projected commands except branch are implemented. The bug that caused failures with vi has been fixed. ".." is a legal range separator as well as "-". There is a regression-test suite, and more documentation. 0.1: 2014-11-07:: Initial proof-of-concept release. src-1.33/README.adoc0000664000175000017500000000167314544356237012206 0ustar esresr= Simple Revision Control // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: BSD-2-Clause The venerable RCS (Revision Control System) has survived into the era of distributed version control because it fills a niche: sometimes you only *want* to track changes in single files at a time - for example, if you have a directory full of documents with separate histories. SRC (Simple Revision Control) is RCS, reloaded. It remains determinedly file-oriented and doesn't even track the committer of a change (because that's always you), but incorporates the design and user-interface lessons of modern version-control systems. It features sequential revision numbers, lockless operation, embedded command help, and a command set that will seem familiar to users of Subversion, Mercurial, and Git. See INSTALL.adoc for the (very simple) installation instructions. Run 'make check' for the regression test. src-1.33/src0000775000175000017500000042473214544571536011144 0ustar esresr#!/usr/bin/env python3 """ SRC - simple revision control. Things to know before hacking this: All the code outside the RCS and SCCS classes (and the RevisionMixin helper) is intended to be generic to any file-oriented VCS. SRC and RCS/SCCS have different goals in managing locks. RCS/SCCS 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/SCCS 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. With sufficient cleverness it would be possible to go in a different direction - leave the master unlocked at all times except during the commit sequence, intervening with a chmod to turn off write protection on the workfile when RCS/SCCS would normally turn it on. I had this as a to-do for a long time but have abandoned the concept; fighting RCS/SCCS's notion of when the workfile ought to be write-locked seems too likely to lead to weird bugs in unexpected situations. In an ideal world, we'd get rid of A status. The SCCS back end doesn't have it, because the only way to register new content is by "sccs add" on an already existing file and that creates a new SCCS master with the content checked in as the first commit. RCS ci works that way as well. On the other hand, if you use rcs -i foo it creates a master foo,v but does *not* stuff it with the content of any corresponding foo. This is what A status means. 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. """ # SPDX-FileCopyrightText: Copyright Eric S. Raymond # SPDX-License-Identifier: BSD-2-Clause # This code runs under both Python 2 and Python 3. # Preserve this property! from __future__ import print_function # Ugh. This is needed because pylint removed the no-self-use check in 2.14. # This is the only way to prevent spurious pylint failures on earlier versions. # pylint: disable=useless-option-value # pylint: disable=fixme,line-too-long,too-many-lines,invalid-name,no-value-for-parameter,no-self-use,no-else-break,no-else-return,no-else-continue,missing-function-docstring,comparison-with-callable,consider-using-f-string,too-many-public-methods,too-many-nested-blocks,consider-using-with,too-many-locals.too-many-branches,unnecessary-lambda-assignment # pylint: disable=multiple-imports import sys, os, subprocess, datetime, time, calendar, stat, glob import shutil, difflib, io, re, signal import tempfile, email.utils, pipes import struct, fcntl, termios, errno, inspect, pydoc try: import curses except ImportError: # pragma: no cover pass version = "1.33" # General notes on Python 2/3 compatibility: # # SRC uses the following strategy to allow it to run on both Python 2 # and Python 3: # # * Use binary I/O to read/write data from/to files and subprocesses; # where the exact bytes are important (such as in checking for # modified files), use the binary data directly. # # * Use latin-1 encoding to transform binary data to/from Unicode when # necessary for operations where Python 3 expects Unicode; this will # ensure that bytes 0x80..0xff are passed through and not clobbered. # The polystr and polybytes functions are used to do this so that when # running on Python 2, the byte string data is used unchanged. # # * Construct custom stdin, stdout, and stderr streams when running # on Python 3 that force ASCII encoding, and wrap them around the # underlying binary buffers (in Python 2, the streams are binary and # are used unchanged); this ensures that the same transformation is # done on data from/to the standard streams, as is done on binary data # from/to files and subprocesses; the make_std_wrapper function does # this. Without this change, 0x80..0xff written to stdout will be # garbled in unpredictable ways. master_encoding = "latin-1" if str is bytes: # Python 2 # pylint: disable=deprecated-module import cgi # pragma: no cover (false negative) # pylint: disable=no-member htmlescape = cgi.escape # pragma: no cover (false negative) polystr = str # pragma: no cover (false negative) polybytes = bytes # pragma: no cover (false negative) else: # Python 3 import html def htmlescape(s): # Python 2 compatibility. # Might be better to do this the other way around. return html.escape(s).replace("'", "'") def polystr(obj): "Polymorphic string factory function" # This is something of a hack: on Python 2, bytes is an alias # for str, so this ends up just giving a str back for all # inputs; but on Python 3, if fed a byte string, it decodes it # to Unicode using the specified master encoding, which should # be either 'ascii' if you're sure all data being handled will # be ASCII data, or 'latin-1' otherwise; this ensures that the # original bytes can be recovered by re-encoding. if isinstance(obj, str): return obj if not isinstance(obj, bytes): return str(obj) # pragma: no cover (interactive only) return str(obj, encoding=master_encoding) def polybytes(s): "Polymorphic string encoding function" # This is the reverse of the above hack; on Python 2 it returns # all strings unchanged, but on Python 3 it encodes Unicode # strings back to bytes using the specified master encoding. if isinstance(s, bytes): return s # if not isinstance(s, str): # return bytes(s) return bytes(s, encoding=master_encoding) def polystream(stream): "Standard input/output wrapper factory function" # This ensures that the encoding of standard output and standard # error on Python 3 matches the master encoding we use to turn # bytes to Unicode in polystr above. return io.TextIOWrapper(stream.buffer, encoding=master_encoding, newline="\n") sys.stdin = polystream(sys.stdin) sys.stdout = polystream(sys.stdout) sys.stderr = polystream(sys.stderr) # If we abandon Python 2 support, it might be best to # move from using pipes.quote to shlex.quote. See: # https://stackoverflow.com/questions/35817/how-to-escape-os-system-calls shellquote = pipes.quote # Note: Avoid using unbolded blue (poor luminance contrast with black # terminal-emulator background) or bolded yellow (poor contrast with # white background.) RESET = BOLD = "" CBLACK = CBLUE = CGREEN = CCYAN = CRED = CMAGENTA = CYELLOW = CWHITE = "" def init_colors(): # pragma: no cover curses.setupterm() # pylint: disable=global-statement global RESET, BOLD RESET = curses.tigetstr("sgr0") if RESET is not None: RESET = polystr(RESET) else: RESET = "" BOLD = curses.tigetstr("bold") if BOLD is not None: BOLD = polystr(BOLD) else: BOLD = "" colors = { "setaf": [0, 4, 2, 6, 1, 5, 3, 7], # ANSI colors "setf": [0, 1, 2, 3, 4, 5, 6, 7], } # legacy colors for (k, v) in colors.items(): x = curses.tigetstr(k) if x: for (i, c) in enumerate( ["black", "blue", "green", "cyan", "red", "magenta", "yellow", "white"] ): cap = curses.tparm(x, v[i]) if cap is not None: cap = polystr(cap) else: cap = "" globals()["C" + c.upper()] = cap break if "curses" in sys.modules and sys.stdout.isatty(): # pragma: no cover try: init_colors() except (curses.error, AttributeError): pass def rfc3339(t): "RFC3339 string from Unix time." return time.strftime("%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") raise SystemExit(1) debug = 0 DEBUG_COMMANDS = 1 # Show commands as they are executed DEBUG_TREESTATE = 2 # Dump directory state DEBUG_SEQUENCE = 3 # Sequence debugging DEBUG_PARSE = 4 # Debug logfile parse quiet = False # option -q: run more quietly pseudotime = False # option -T: artificial clock for regression testing logstream = sys.stderr def logit(msg): logstream.write(msg) class popen_or_die: "Read or write from a subordinate process." def __init__(self, command, legend="", mode="r"): assert mode in ("r", "w", "rb", "wb") self.command = command self.legend = legend self.mode = mode # Pipe to the correct streams depending on the chosen mode self.stdin = subprocess.PIPE if mode == "w" else None self.stdout = subprocess.PIPE if mode == "r" else None self.stderr = subprocess.STDOUT if mode == "r" else None if self.legend: self.legend = " " + self.legend self.fp = None def __enter__(self): if debug >= DEBUG_COMMANDS: if self.mode == "r": logit( "%s: reading from '%s'%s\n" % (rfc3339(time.time()), self.command, self.legend) ) else: logit( "%s: writing to '%s'%s\n" % (rfc3339(time.time()), self.command, self.legend) ) try: # The I/O streams for the subprocess are always bytes; this # is what we want for some operations, but we will need # to decode to Unicode for others to work in Python 3, as # explained in the general notes. self.fp = subprocess.Popen( self.command, shell=True, stdin=self.stdin, stdout=self.stdout, stderr=self.stderr, ) # The Python documentation recommends using communicate() to # avoid deadlocks, but this doesn't allow fine control over # reading the data; since we are not trying to both read # from and write to the same process, this should be OK. return self.fp.stdout if self.mode == "r" else self.fp.stdin except (OSError, IOError) as oe: # pragma: no cover croak("execution of %s%s failed: %s" % (self.command, self.legend, oe)) return None # pragma: no cover def __exit__(self, extype, value, traceback_unused): if extype: # pragma: no cover if debug > 0: raise extype(value) croak("fatal exception in popen_or_die.") if self.fp.stdout is not None: # This avoids a deadlock in wait() below if the OS pipe # buffer was filled because we didn't read all of the data # before exiting the context manager (shouldn't happen but # this makes sure). self.fp.stdout.read() self.fp.wait() if self.fp.returncode != 0: # pragma: no cover croak("%s%s returned error." % (self.command, self.legend)) return False def screenwidth(): # pragma: no cover "Return the current width of the terminal window." default_width = 73 if "COLUMNS" in os.environ: return int(os.environ["COLUMNS"]) try: return struct.unpack( "HH", fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack("HH", 0, 0)) )[1] except IOError as e: # ENOTTY isnormal for no terminal under Linux, but # Mac High Sierra can throw ENODEV. if e.errno in (errno.ENOTTY, errno.ENODEV): return default_width else: raise e WIDTH = screenwidth() - 1 def modified(workfile, history=None): "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. # # If no revisions, bail out if not backend.has_revisions(workfile): return False if history is None: history = History(workfile) with backend.manager(workfile) as xc: with backend.cat(xc.pathbase, history.current().native) as bstream: base_content = bstream.read() # this data will be binary if os.path.getsize(workfile) != len(base_content): return True with open(xc.pathbase, "rb") as fp: workfile_content = fp.read() # This comparison uses the binary data for maximum accuracy return base_content != workfile_content def relative(d=None): # Only used for debug/croak output return os.path.relpath(os.getcwd() if d is None else d, startdir) def treedump(legend): # Visibly dump the state of the directory we're in # Used for debugging instrumentation only. logit(legend + "\n") logit(polystr(capture_or_die("ls -laR " + startdir))) def rename(source, target, legend): if debug >= DEBUG_COMMANDS: logit("rename(%s, %a) %s\n" % (source, target, legend)) os.rename(source, target) def chdir(target, legend): if debug >= DEBUG_COMMANDS: logit("chdir(%a) %s\n" % (target, legend)) os.chdir(target) def caller(uplevel, legend=""): "Look up the stack for the callers of this function (for diagnostics)" if legend: legend = " " + legend return str(inspect.stack()[1 + uplevel][0].f_code.co_name) + legend def do_or_die(dcmd, legend="", mute=True, missing=None, fatal=True): "Either execute a command or die." if legend: legend = " " + legend if debug == 0 and mute: muteme = " >/dev/null 2>&1" else: muteme = "" say = croak if fatal else announce dcmd = "(" + dcmd + ")" + muteme if debug >= DEBUG_TREESTATE: treedump("Before command " + dcmd) if debug >= DEBUG_COMMANDS: logit("at %s executing '%s'%s\n" % (relative(), dcmd, legend)) try: retcode = subprocess.call(dcmd, shell=True) if retcode < 0: # pragma: no cover croak("%s was terminated by signal %d." % (repr(dcmd), -retcode)) elif retcode != 0: # pragma: no cover errmsg = "%s returned %d." % (repr(dcmd), retcode) if retcode == 127: if missing is None: missing = backend.__class__.__name__ errmsg += "\nYou probably need to install %s." % missing say(errmsg) except (OSError, IOError) as e: # pragma: no cover say("execution of %s%s failed: %s" % (repr(dcmd), legend, e)) if debug >= DEBUG_TREESTATE: treedump("After command") return retcode def capture_or_die(command): "Run a specified command, capturing the output." if debug >= DEBUG_COMMANDS: logit("%s: capturing %s\n" % (rfc3339(time.time()), command)) try: # This will return binary data content = subprocess.check_output(command, shell=True) except (subprocess.CalledProcessError, OSError) as oe: # pragma: no cover croak("execution of %s failed: %s" % (repr(command), oe)) if debug >= DEBUG_COMMANDS: # pragma: no cover logit(polystr(content)) return content # pylint: disable=too-many-instance-attributes class HistoryEntry: "Capture the state of a native revision item in the log." def __init__(self, history): "Initialize a history entry." self.history = history self.revno = None self.native = None # magic cookie only interpreted by back end self.headers = None self.log = "" self.date = None self.parent = None # Another HistoryEntry self.child = None # Another HistoryEntry self.branch = None def selected(self): "Is this the currently selected revision in the history list?" return self == self.history.current() def getdate(self, who): "Get the revision's commit date." if self.headers and not pseudotime: return self.headers.get(who + "-date") or self.date return self.date def unixtime(self, who): "Get the Unix timestamp of this revision." date = self.getdate(who) try: t = calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%SZ")) offset = 0 if self.headers and not pseudotime: offset = self.headers.get(who + "-date-offset") or 0 return t, offset except (TypeError, ValueError): # pragma: no cover croak("garbled date %s" % date) return None # pragma: no cover 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)) # pylint: disable=too-many-instance-attributes class History: "Encapsulate a revision list and some methods on it" def __init__(self, filename): "Intialize a history list." self.filename = filename self.revlist = [] self.symbols = {} self.tipbranch = "trunk" self.lockrevs = [] self.description = "" # Not currently used if not registered(self.filename): croak("%s is not registered" % self.filename) self.by_revno_d = {} self.by_native_d = {} if debug >= DEBUG_COMMANDS: logit("parsing %s\n" % self.filename) try: d = os.path.dirname(filename) if d: chdir(d, "before getting history") backend.parse(self, os.path.basename(filename)) finally: chdir(startdir, "after getting history") self.lift_headers() self.normalize_header_dates() def build_indices(self): 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 debug >= DEBUG_PARSE: logit("Symbols: %s\n" % self.symbols) for item in self.revlist: logit("Item %s\n" % item) logit("By revision: %s\n" % self.by_revno_d.keys()) if self.revlist: for (name, rev) in list(self.symbols.items()): if backend.isbranch(rev): base = backend.branch_to_base(rev) tip = backend.branch_to_tip(rev, self) while True: if base in self.by_native_d: self.by_native_d[base].branch = name if base == tip: break base = backend.succ(base) def lift_headers(self): valid = ( "author", "author-date", "committer", "committer-date", "mark", "parents", ) for item in self.revlist: headers = {} i = 0 while True: n = item.log.find("\n", i) if n < 0: break header = item.log[i:n].split(":", 1) if len(header) != 2: break key = header[0].lower() if key in valid: headers[key] = header[1].strip() i = n + 1 # eat blank line between headers and body while i < len(item.log) and item.log[i] == "\n": i += 1 item.log = item.log[i:] if headers: item.headers = headers def normalize_header_dates(self): for item in self.revlist: if item.headers: for k in tuple(item.headers): if k.endswith("-date"): d = email.utils.parsedate_tz(item.headers[k]) if d: u = email.utils.mktime_tz(d) u = datetime.datetime.utcfromtimestamp(u) item.headers[k] = u.isoformat() + "Z" item.headers[k + "-offset"] = d[9] if d[9] else 0 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]] except (IndexError, KeyError): try: return self.by_native_d[ backend.branch_to_tip(self.symbols[self.tipbranch], self) ] except (IndexError, KeyError): # pragma: no cover return None def current_branch(self, backwards=False): "Return a list of items that are descendants or ancestors of current." if debug >= DEBUG_SEQUENCE: logit(("current_branch(%s)\n" % 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 is 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: # pragma: no cover if revno == 0: # This case comes up if we try to select the tip # revision of a history without revisions. croak("{0} has no revisions".format(self.filename)) else: croak("{0} has no revno {1}".format(self.filename, revno)) return None # pragma: no cover 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. init -- the initialize command, which does nothing 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. srcify -- the srcify command: change management from SCCS/RCS to src. ignores -- .srcignore files and their uses. The 'help', 'rename', 'ls', 'move', 'copy', 'visualize', and 'version' commands are completely described in the command summary. """, "intro": """ SRC Introduction SRC (or src) is designed for version control on single-file projects. To start a single-file project, just create a file and commit it; this will creare a subdurectory called .src if one doews not already exist, and put your file history there. 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 explicitly 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. A filename can be a path. In that case SRC will behave as though it were running in the lowest-level directory on the path and called with the path basename. If you do not specify any files, SRC will operate sequentially on each individual file in the current directory with a history. A good help topic to read after this one would be 'revisions'. """, "revisions": """ SRC 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, srcify, 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 Commands Summary src help [command] Displays help for commands. src init This command is unecessary and does nothing. It is provided to reduce surprise for people who don't expect the first commit into a file in a new directory to initialize a repository there. src commit [-|-m 'string'|-f 'file'|-e|-b branch] ['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'. The -b option attaches the commit to the named branch, making it the default for future commits. 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. Sets the default branch for future checkins to that of whatever revision you check out. 'co' is a synonym for 'checkout'. src cat ['revision'] ['file'...] Send the specified revisions of the files to standard output. src status [-a] [-q] ['file'...] '=' = unmodified, 'M' = modified, '!' = missing, '?' = not tracked, 'I' = ignored, 'A' = added, '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. Create/delete takes a singleton revision, defaulting to the current branch tip. List defaults to all revisions. src branch [list|-l|create|-c|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'. Create/delete takes a singleton revision, defaulting to the current branch tip; pn create that branch becomes the default for future commits. List defaults to all revisions, including 0 (the trunk root phantom revision). 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 )] [-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 '-' or '-l ', where is a number, to limit the listing length. Default range is the current branch, reversed. src log [-v] [(-|-l )] [(-p|-u|-c) [-b|-w]] ['revision-range'] ['file'...] Sends log information about the specified commits to standard output. Use '-' or '-l ', where is a number, to limit the listing length. Default range is the current branch, reversed. Use '--patch', '-p' or '-u' to also send a unified format diff listing to standard output for each revision against its immediate ancestor revision; '-c' emits a context diff instead. When generating a diff, '-b' ignores changes in the amount of whitespace, and '-w' ignores all whitespace. Histories imported via 'fast-import' (when not using its '-p' option) have RFC-822-style headers inserted into the log comment to preserve metadata not otherwise representable in SRC, such as distinct author and committer identifications and dates. These headers are normally suppressed by 'log', however, '-v' shows a summarized view of important headers; '-v -v' shows all headers as-is. src diff [(-u|-c) [-b|-w]] ['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. 'di' is a synonym for 'diff'. src ls List all registered files. src visualize Emit a DOT visualization of repository structures. To use this, install the graphviz package and pipe the output to something like 'dot -Tpng | display -'. 'vis' is a synonym for 'visualize'. 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 for 'copy'. src fast-export ['revision-range'] ['file'...] Export one or more projects to standard output as a Git fast-import stream. For a history originally imported from elsewhere, author and committer identification is gleaned from the RFC-822-style headers inserted into the commit comment by 'fast-import' (if its '-p' option was not used). Otherwise, this information 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/unwritable) state. src srcify Move a directory from being RCS- or SCCS-managed to being SRC-managed. That is: if the current directory contains an RCS directory, rename it to .src (but leave any SCCS directory in place). Then check out all masters for editing that are not already checked out. src version Report the versions of SRC, the underlying Python, and the back end. The omission of 'src remove' is a deliberate speed bump. """, "status": """ src status [-a] [-q] ['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/writable. Modification status is by content rather than the filesystem's last-modified 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 a 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 commit' with the deliberately undocumented '-a' option meant for Emacs VC's use. 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. The -q option suppressed listing of untracked files. """, "init": """ src init This command is unnecessary and does nothing. It is provided by analogy with the init commands in cvs, git, hg and bzr/brz, as a placeholder in scripting and to reduce surprise for people who don't expect the first commit into a file in a new directory to initialize a repository there. """, "commit": """ src commit [-|-m 'string'|-f 'file'| -e] [-b branch] ['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. The -b option puts the commit on a new 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 several 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 will 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. The 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. 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 so may, as a side effect, change your current branch. 'co' is a synonym for 'checkout'. """, "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 [-v] [(-|-l )] [(-p|-u|-c) [-b|-w]] ['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 '--patch', '-p' or '-u' option additionally sends a unified format diff listing to standard output for each revision against its immediate ancestor revision; '-c' emits a context diff instead. When generating a diff, '-b' ignores changes in the amount of whitespace, and '-w' ignores all whitespace. The '-' or '-l ' option, where is a number, can be used to limit the listing length. Histories imported via 'fast-import' (when not using its '-p' option) have RFC-822-style headers inserted into the log comment to preserve metadata not otherwise representable in SRC, such as distinct author and committer identifications and dates. These headers are normally suppressed by 'log', however, '-v' shows a summarized view of important headers; '-v -v' shows all headers as-is. """, "list": """ src list [(-|-l )] [-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 format string. Available substitutions are: {0} - the file name {1} - the revision number {2} - the mark '*' if this is the currently checked out revision, else '-'. {3} - the date in RFC3339 format {4} - the summary line The '-' or '-l ' option, where is a number, can be used to limit the listing length. 'li' is a synonym for 'list'. """, "diff": """ src diff [(-u|-c) [-b|-w]] ['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. The actual difference generation is done with diff(1). The default diff format is '-u' (unified), but if you specify a '-c' option after the verb a context diff will be emitted. '-b' ignores changes in the amount of whitespace, and '-w' ignores all whitespace. 'di' is a synonym for 'diff'. """, "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 repository 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 produces a single stream with a joint history. If there is a .srcignore file, it is renamed to .gitignore in the stream. For a history originally imported from elsewhere, author and committer identification is gleaned from the RFC-822-style headers inserted into the commit comment by 'fast-import' (if its '-p' option was not used). Otherwise, this information is copied from your Git configuration. The default range is all commits. """, "srcify": """ src srcify Change the current directory with an RCS or SCCS subdirectory to be managed by src instead. Any RCS directory is renamed .src. Then all files with histories are checked out for editing. """, "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. """, "ignores": """ Making SRC Ignore Certain Files 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' itself 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 and is a superset of Unix glob(3) 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. [-] can be used to match ranges, e.g. [a-z] matches any lowercase letter. [^] brackets a negated character class; [^0123456789] would match any character not a decimal digit. [!] also brackets a negated character class """, } 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: if sys.stdout.isatty(): pydoc.pager(help_topics[arg]) else: 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: return True elif token.count("-") == 1 and "." not 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?" # pylint: disable=global-statement global ignorable if ignorable is None: ignorable = set() if os.path.exists(".srcignore"): with open(".srcignore", "rb") as fp: for line in fp: line = polystr(line) # Hack to make src a bit more compatible with # other systems and POSIX glob(3). line = line.replace("[^", "[!") 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) # pycheck: disable=too-many-branches class CommandContext: "Consume a revision specification or range from an argument list" # pylint: disable=too-many-arguments,too-many-branches,too-many-statements def __init__( self, cmd, args, require_empty=False, default_to=None, parse_revspec=True ): self.start = self.end = None self.seq = None self.branchwise = None if isinstance(args, tuple): args = list(args) self.args = list(args) self.default_to = default_to self.lo = self.start self.hi = self.end revspec = None if self.args: if self.args[0] == "--": parse_revspec = False 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: # pragma: no cover croak("internal error - argument parser is confused") try: self.start = int(self.start) except ValueError: # pragma: no cover pass try: self.end = int(self.end) except ValueError: # pragma: no cover pass else: try: self.end = self.start = int(revspec) except ValueError: self.end = self.start = revspec except ValueError: # pragma: no cover 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 backend.is_history(fn)] masters.sort() except OSError: croak("repo directory %s does not exist" % repodir) if masters: self.args += [backend.workfile(master) for master in masters] else: croak("%s requires at least one file argument" % cmd) if multidir and not quiet: announce("%s is selected." % repodir) 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.lo = 1 self.hi = len(metadata) self.seq = [metadata.by_revno(i) for i in range(self.lo, self.hi + 1)] def select_tip(self, metadata): "Set the range to the tip revision." self.lo = len(metadata) self.hi = None self.seq = [metadata.by_revno(self.lo)] def __contains__(self, i): "Does the spec contain the given revno?" if self.seq is None: croak( "revision spec hasn't been resolved" ) # pragma: no cover (should never happen) return i in self.seq # pylint: disable=too-many-branches def resolve(self, metadata): "Resolve a revision spec that may contain tags into revnos." if debug >= DEBUG_SEQUENCE: logit("Entering resolve with start=%s, end=%s\n" % (self.start, self.end)) if self.is_empty(): if debug >= DEBUG_SEQUENCE: logit("Revision spec is empty\n") 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 = [] if debug >= DEBUG_SEQUENCE: logit( "Empty revision spec returns %s\n" % ([x.revno for x in self.seq],) ) return self.seq def subresolve(token): part = token if isinstance(part, int): return part if token == "": # User specified @ current = metadata.current() if current is None: croak( "in {0}, no current revision".format(metadata.filename) ) # pragma: no cover (should never happen) return current.revno if part not in metadata.symbols: croak( "in {0}, can't resolve symbol {1}".format(metadata.filename, token) ) else: part = metadata.symbols[part] if backend.isbranch(part): part = backend.branch_to_tip(part, metadata) return metadata.native_to_revno(part) self.lo = subresolve(self.start) self.hi = subresolve(self.end) if debug >= DEBUG_SEQUENCE: logit("Subresolved range: lo=%s, hi=%s\n" % (self.lo, self.hi)) # pylint: disable=superfluous-parens mreversed = self.lo > self.hi if mreversed: swapme = self.hi self.hi = self.lo self.lo = swapme if self.hi > len(metadata): croak("{0} has no {1} revision".format(metadata.filename, self.hi)) if not self.branchwise: self.seq = [metadata.by_revno(i) for i in range(self.lo, self.hi + 1)] else: self.seq = [] e = metadata.by_revno(self.hi) while True: self.seq.append(e) if e.revno == self.lo: break if e.parent is None: croak("%s is not an ancestor of %s" % (self.lo, self.hi)) else: e = e.parent if debug >= DEBUG_SEQUENCE: logit( "selection: %s, branchwise is %s\n" % ([x.revno for x in self.seq], "on" if self.branchwise else "off") ) for item in metadata.revlist: logit("%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 mreversed: self.seq.reverse() return self.seq class CommentContext: "Encapsulate comment part of a revision." 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] + "\n" args.pop(0) except IndexError: # pragma: no cover croak("%s -m requires a following string" % legend) elif args[0].startswith("-m"): self.leader = args[2:] + "\n" args.pop(0) elif args[0] == "-f": args.pop(0) try: # Read filesystem data as binary for robustness, but # decode to Unicode for internal use with open(args[0], "rb") as fp: self.leader = polystr(fp.read()) args.pop(0) except IndexError: # pragma: no cover croak("%s -f requires a following filename argument" % legend) except OSError: # pragma: no cover croak("couldn't open %s." % args[1]) elif args[0].startswith("-"): croak("unexpected %s option" % args[0]) # pragma: no cover def edit(self, content="", trailer="", diff=None): "Interactively edit a comment if required, then prepare for handoff." if self.leader and not self.force_edit: self.comment = self.leader else: orig_content = content if self.leader: content = self.leader + content if trailer or diff: content += ( "\n" + CommentContext.COMMENT_CUTLINE + CommentContext.COMMENT_EXPLANATION + trailer ) editor = os.getenv("EDITOR") if editor is None: # pragma: no cover for editor in ( "emacsclient", "emacs", "vim", "vi", "nano", "joe", "jed", ): try: if shutil.which(editor): break except AttributeError: croak( "fallback editor discovery is not available under Python 2." ) else: croak("can't find a text editor to launch") try: with tempfile.NamedTemporaryFile( prefix="src", suffix="tmp", delete=False ) as fp: commentfile = fp.name fp.write(polybytes(content)) if diff: fp.write(b"\nChanges to be committed:\n") for s in diff: fp.write(polybytes(s)) fp.write(b"\n") do_or_die(editor + " " + commentfile, "edit", mute=False) with open(commentfile, "rb") as fp: self.comment = polystr(fp.read()) os.unlink(commentfile) except IOError: # pragma: no cover croak("edit aborted.") where = self.comment.find(CommentContext.COMMENT_CUTLINE) if where != -1: self.comment = self.comment[:where] self.comment = self.comment.strip() if self.comment == orig_content.strip() or not self.comment: return False # Can be removed if we ever parse RCS/SCCS files directly for badnews in backend.delimiters: if badnews in self.comment: croak("malformed comment") # pragma: no cover if not self.comment.endswith("\n"): self.comment += "\n" return True def content(self): "Return the edited comment." return self.comment # pylint: disable=too-many-arguments def external_diff(file0, s0, file1, s1, unified=True, ignore_ws=None): "Compute diff using external program." def writetmp(s): with tempfile.NamedTemporaryFile( prefix="src", suffix="tmp", delete=False ) as fp: fp.write(polybytes(s)) return fp.name if unified: opts, tok0, tok1 = "-u", "-", "+" else: opts, tok0, tok1 = "-c", "*", "-" if ignore_ws: opts += " " + ignore_ws tmp0 = writetmp(s0) tmp1 = writetmp(s1) with popen_or_die( 'diff %s "%s" "%s" || :' % (opts, tmp0, tmp1), "external diff" ) as fp: diff = polystr(fp.read()) os.unlink(tmp0) os.unlink(tmp1) diff = re.sub(r"(?m)^([%s]{3} ).+$" % tok0, r"\1" + file0, diff, 1) diff = re.sub(r"(?m)^([%s]{3} ).+$" % tok1, r"\1" + file1, diff, 1) return diff.split("\n") def compute_diff(metadata, lo, hi, differ, ignore_ws=None): """Compute diff between two revs of a file. If 'lo' is None, then this is a "creation event" in which 'hi' materializes fully formed from nothing. If 'hi' is None, then diff 'lo' against the working file. File must already have been "lifted".""" name = metadata.filename if lo is None: file0 = "/dev/null" old_content = "" else: file0 = name + " (r" + str(lo) + ")" with backend.cat(name, metadata.revno_to_native(lo)) as fp: old_content = fp.read() # this data will be binary if hi is None: file1 = name + " (workfile)" with open(name, "rb") as fp: new_content = fp.read() else: file1 = name + " (r" + str(hi) + ")" with backend.cat(name, metadata.revno_to_native(hi)) as fp: new_content = fp.read() # this data will be binary # Don't list identical files (comparison uses binary data # for maximum accuracy). if old_content == new_content: return () if ignore_ws: return external_diff( file0, old_content, file1, new_content, differ == difflib.unified_diff, ignore_ws, ) lines0 = polystr(old_content).split("\n") lines1 = polystr(new_content).split("\n") return differ(lines0, lines1, fromfile=file0, tofile=file1, lineterm="") def colorize_unified(s): for x in colorize_unified.colors: if s.startswith(x[0]): return x[1] + s + RESET return s colorize_unified.colors = ( ("+++ ", BOLD), ("--- ", BOLD), ("@@ ", CCYAN), ("+", CGREEN), ("-", CRED), ) def print_diff(metadata, lo, hi, differ, ignore_ws=None): "Dump diff between revisions to standard output." if differ == difflib.unified_diff: colorizer = colorize_unified else: colorizer = lambda x: x with backend.manager(metadata.filename): for line in compute_diff(metadata, lo, hi, differ, ignore_ws): sys.stdout.write(colorizer(line) + "\n") def exec_copy(source, target): if os.path.exists(target): oldtargetmode = newtargetmode = os.stat(target).st_mode sourcemode = os.stat(source).st_mode for bitmask in (stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH): if bitmask & sourcemode: newtargetmode |= bitmask else: newtargetmode &= ~bitmask if newtargetmode != oldtargetmode: os.chmod(target, newtargetmode) 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 = ctx.seq[0].native elif ctx.lo > len(metadata): croak("%s has only %d revisions" % (arg, len(metadata))) else: revision = metadata.revno_to_native(ctx.lo) with backend.manager(arg) as xc: backend.checkout(xc.pathbase, revision) backend.set_branch(backend.revision_to_branch(revision), xc.pathbase) if not quiet and len(args) > 1: announce("%s <- %d" % (arg, ctx.lo)) # pylint: disable=unused-argument def init_method(*args): "Initialize a repository directory." # pylint: disable=unnecessary-pass pass # pylint: disable=too-many-branches,too-many-statements def commit_method(*args): "Commit changes to files." args = list(args) register_only = False parse_revspec = True branch = None differ = difflib.unified_diff while args: if args[0] == "--": args.pop(0) parse_revspec = False break elif args[0] == "-a": # Perform error check, but don't actually do a commit. # The Emacs VC-mode support for SRC was written early, # before 1.0, when I hadn't quite figured out what the # most efficient method for file registration would be. # VC-mode wants to have a registration as well as a # checkin method. This is no longer needed for normal SRC # operation, but it's better to leave this in place than # risk causing hassles for people running old Emacs versions. register_only = True parse_revspec = False args.pop(0) elif args[0] == "-b": args.pop(0) branch = args.pop(0) else: break if not register_only: 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}.\n".format(arg) revcount = 0 metadata = None diff = compute_diff(type("", (), {"filename": arg}), None, None, differ) elif register_only: croak("attempt to re-add a registered file failed") else: metadata = History(arg) ctx.resolve(metadata) if metadata and ctx.is_empty(): ctx.select_tip(metadata) revcount = len(metadata) trailer = "Committing {0} revision {1}.\n".format(arg, revcount + 1) with backend.manager(arg): diff = compute_diff(metadata, ctx.lo, None, differ) if not register_only and not diff: announce("in %s, no changes to commit" % arg) continue if not register_only and not comment.edit("", trailer, diff): announce("in %s, commit cancelled" % arg) else: has_history = registered(arg) if not has_history: if debug >= DEBUG_COMMANDS: logit("registration phase:\n") # We can't use the manager here, it wants to go clear down # to a repository directory. try: d = os.path.dirname(arg) if d: chdir(d, "before registering") backend.register(os.path.basename(arg)) finally: if d: chdir(startdir, "after registering") if debug >= DEBUG_COMMANDS: logit("commit phase:\n") if not register_only: with backend.manager(arg) as xc: # 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 # the VCS doesn't propagate the changed executable # bit to the master, leading to misbehavior on the # next checkout. exec_copy(xc.pathbase, backend.history(xc.pathbase)) if branch is not None: if not has_history: croak("can't set branch on unregistered file.") if branch not in metadata.symbols: croak("can't switch to nonexistent branch %s." % branch) elif not backend.isbranch(metadata.symbols[branch]): croak("%s is not a branch." % branch) backend.set_branch(metadata.symbols[branch], metadata.filename) backend.checkin(xc.pathbase, comment.content()) if metadata is None: metadata = History(arg) if not quiet and len(args) > 1: announce("%s -> %d" % (arg, revcount)) def add_method(*args): "For Emacs VC compatibility." commit_method("-a", *args) 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) differ = difflib.unified_diff 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.lo = metadata.tip().revno trailer = "Amending {0} revision {1}.\n".format(arg, ctx.lo) item = metadata.by_revno(ctx.lo) parent = item.parent.revno if item.parent else None with backend.manager(arg): diff = compute_diff(metadata, parent, ctx.lo, differ) if not comment.edit(metadata.by_revno(ctx.lo).log, trailer, diff): announce("in %s, amend cancelled" % arg) else: with backend.manager(arg) as xc: backend.amend( xc.pathbase, metadata.revno_to_native(ctx.lo), comment.content() ) if not quiet and len(args) > 1: announce("%s : %d" % (arg, ctx.lo)) def list_method(*args): "Generate a summary listing of commits, one line per commit." args = list(args) custom = None limit = None parse_revspec = True while args and args[0].startswith("-"): if args[0] == "--": parse_revspec = False args.pop(0) break elif args[0] == "-f": args.pop(0) try: custom = args[0] args.pop(0) except IndexError: # pragma: no cover croak("list -f requires a following string") elif args[0] == "-l": args.pop(0) try: limit = args[0] args.pop(0) limit = int(limit) except IndexError: # pragma: no cover croak("list -l requires a following integer") except ValueError: # pragma: no cover croak("%s is not an integer" % limit) elif args[0][1:].isdigit(): limit = int(args.pop(0)[1:]) # it's all digits, so no ValueError else: croak("unexpected %s option" % args[0]) 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.getdate("author"), summary) ) else: sys.stdout.write( custom.format( arg, item.revno, mark, item.getdate("author"), summary ) + "\n" ) 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 differ = None ignore_ws = None verbose = 0 while args and args[0].startswith("-"): if args[0] == "--": parse_revspec = False args.pop(0) break elif args[0] == "-l": args.pop(0) try: limit = args[0] args.pop(0) limit = int(limit) except IndexError: # pragma: no cover croak("list -l requires a following integer") except ValueError: # pragma: no cover croak("%s is not an integer" % limit) elif args[0][1:].isdigit(): limit = int(args.pop(0)[1:]) # it's all digits, so no ValueError elif args[0] in ("--patch", "-p", "-u"): differ = difflib.unified_diff args.pop(0) elif args[0] == "-c": differ = difflib.context_diff args.pop(0) elif args[0] in ("-b", "-w"): ignore_ws = args.pop(0) elif args[0] == "-v": verbose += 1 args.pop(0) else: croak("unexpected %s option" % args[0]) ctx = CommandContext( "log", args, default_to="branch_reversed", parse_revspec=parse_revspec ) # pylint: disable=too-many-nested-blocks 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) * "="))) metadata = History(arg) for item in ctx.resolve(metadata): sys.stdout.write( "%s%-4d%s | %s%s%s | %s%s%s\n" % ( BOLD + CCYAN, item.revno, RESET, CYELLOW, item.getdate("author"), RESET, BOLD + CGREEN, item.branch, RESET, ) ) if verbose and item.headers: headers = item.headers if verbose == 1: headers = {} for k in ("author", "committer"): if k in item.headers: v = item.headers[k] if k + "-date" in item.headers: v += " " + item.headers[k + "-date"] headers[k] = v for k in sorted(headers.keys()): sys.stdout.write( "%s%s%s: %s\n" % (BOLD, k.title(), RESET, headers[k]) ) sys.stdout.write("\n") sys.stdout.write("%s" % item.log) if differ: if item.parent: parent = item.parent.revno pdesc = "r%d/%s" % (parent, arg) else: parent = None pdesc = "/dev/null" sys.stdout.write( "\n%sdiff %s r%s/%s%s\n" % (BOLD, pdesc, item.revno, arg, RESET) ) print_diff(metadata, parent, item.revno, differ, ignore_ws) sys.stdout.write(("-" * WIDTH) + "\n") if limit is not None: limit -= 1 if limit <= 0: break def status_method(*args): "Get status of some or all files." args = list(args) allflag = False qflag = False if args: if args[0] == "--": args.pop(0) elif args[0] == "-a": allflag = True args.pop(0) elif args[0] == "-q": qflag = True args.pop(0) # No command context is created, so we do this explicitly if multidir and not quiet: announce("%s is selected." % repodir) if args: candidates = args else: candidates = [] for dirpath, _, fnames in os.walk("./"): for f in fnames: candidates.append(os.path.join(dirpath, f)[2:]) pairs = [] for fn in candidates: if backend.is_history(fn): if not os.path.isfile(backend.workfile(fn)): pairs.append((fn, "!")) elif ignore(fn): if allflag or fn in args: pairs.append((fn, "I")) elif not os.path.isfile(backend.history(fn)): if not qflag: 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, "=")) pairs.sort() for (fn, status) in pairs: sys.stdout.write(status + " " + 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.manager(arg) as xc: for item in ctx.seq: with backend.cat(xc.pathbase, item.native) as fp: sys.stdout.write(polystr(fp.read())) def diff_method(*args): "Dump diffs between revisions to standard output." if isinstance(args, tuple): args = list(args) differ = difflib.unified_diff ignore_ws = None while args and args[0] != "--" and args[0].startswith("-"): if args[0] == "-u": differ = difflib.unified_diff args.pop(0) elif args[0] == "-c": differ = difflib.context_diff args.pop(0) elif args[0] in ("-b", "-w"): ignore_ws = args.pop(0) else: croak("unexpected %s option" % args[0]) ctx = CommandContext("diff", args) for arg in ctx.args: metadata = History(arg) ctx.resolve(metadata) if ctx.is_empty(): ctx.select_tip(metadata) print_diff(metadata, ctx.lo, ctx.hi, differ, ignore_ws) # pylint: disable=too-many-locals,too-many-nested-blocks 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 ) # pragma: no cover (should never happen) 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: if legend == "branch": current_branch = metadata.symbols[name] for lock in metadata.lockrevs: if backend.revision_to_branch(lock) == current_branch: croak("can't delete the current branch") status = 0 with backend.manager(arg) as xc: status = delete_method(name, metadata) if status != 0: croak("%s deletion failed." % legend) if not quiet and len(args) > 1: announce("in %s, %s %s removed" % (xc.pathbase, 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) ctx.resolve(metadata) if ctx.is_empty(): prepend = [0] ctx.select_all(metadata) else: prepend = [] revisions = prepend + [item.revno for item in ctx.seq] sys.stdout.write("= %s %s\n" % (arg, ((WIDTH - len(arg) - 5) * "="))) keys = list(metadata.symbols.keys()) if metadata.tipbranch in keys: keys.remove(metadata.tipbranch) keys.sort() keys = [metadata.tipbranch] + keys for key in keys: value = metadata.symbols[key] selected = "" if legend == "branch": # Note! This code relies on # backend.branch_to_parent() returning an empty # string when called on a trunk revision. displaystr = backend.branch_to_parent(value) if not displaystr: display = 0 else: display = metadata.native_to_revno(displaystr) selected = "* " if key == metadata.tipbranch else "- " else: display = metadata.native_to_revno(value) if display in revisions and backend.isbranch(value) == ( legend == "branch" ): sys.stdout.write("%4s\t%s%s\n" % (display, selected, 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.manager(arg) as xc: set_method(name, revision, metadata) if not quiet and len(args) > 1: announce( "in %s, %s %s = %s" % (xc.pathbase, legend, name, ctx.start) ) return 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.lo) 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.make_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.manager(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 os.sep in target and not os.path.exists(os.path.dirname(target)): croak("directory '%s' does not exist." % target) elif not registered(source): croak("%s is not registered" % 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 ) # pragma: no cover 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): # pragma: no cover "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.manager(arg) as xc: backend.release(xc.pathbase) def srcify_method(*args): "Move an RCS or SCCS directory into SRC management." if os.path.exists(".src"): croak("A %s directory already exists." % repodir) if args: croak("lift cannot accept arguments") if not os.path.isdir("RCS") and not os.path.isdir("SCCS"): croak("no RCS or SCCS directory") candidates = [ f for f in os.listdir(".") if os.path.isfile(f) and not os.path.islink(f) ] for fn in candidates: if registered(fn) and (not os.path.exists(fn) or not modified(fn)): with backend.manager(fn) as xc: backend.checkout(xc.pathbase, "") if os.path.isdir("RCS"): rename("RCS", ".src", "in srcify") def ls_method(*args): "List registered files." if args: croak("ls cannot accept arguments") try: masters = [fn for fn in os.listdir(repodir) if backend.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 visualize_method(*args): "Generate (and possibly display) a DOT visualization of repo structure." if not os.path.exists(repodir): croak("repository subdirectory %s does not exist" % repodir) args = list(args) comment = CommentContext("visualize", args) ctx = CommandContext("visualize", args, parse_revspec=comment.parse_revspec) for arg in ctx.args: # if not os.path.exists(arg): # croak("I see no '%s' here." % arg) if 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.select_all(metadata) sys.stdout.write("digraph {\n") if len(ctx.args) > 1: pref = arg + ":" else: pref = "" for item in ctx.seq: if item.parent: sys.stdout.write( "\t%s%d -> %s%d;\n" % (pref, item.parent.revno, pref, item.revno) ) summary = htmlescape(item.log.split("\n")[0][:42]) sys.stdout.write( '\t%s%s [shape=box,width=5,label=<
%s%s%s
>];\n' % (pref, item.revno, pref, item.revno, summary) ) if metadata.tip(item.native) == item: sys.stdout.write( '\t"%s%s" [shape=oval,width=2];\n' % (pref, item.branch) ) sys.stdout.write( '\t"%s%s" -> "%s%s" [style=dotted];\n' % (pref, item.revno, pref, item.branch) ) keys = sorted(metadata.symbols.keys()) for name in keys: native = metadata.symbols[name] branch_label = backend.isbranch(native) if branch_label: native = backend.branch_to_tip(native, metadata) revno = metadata.native_to_revno(native) if not branch_label: sys.stdout.write( '\t{rank=same; "%s%s"; "%s%s"}\n' % (pref, name, pref, revno) ) sys.stdout.write( '\t"%s%s" -> "%s%s" [style=dotted];\n' % (pref, name, pref, revno) ) sys.stdout.write("}\n") # pylint: disable=too-many-locals def fast_export_method(*args): "Dump revision content to standard output." def attribute(item, who, fallback): s = fallback if item.headers and who in item.headers: s = item.headers[who] t, o = item.unixtime(who) return "%s %s %d %s%02d%02d\n" % ( (who, s, t, "-" if o < 0 else "+") + divmod(abs(o), 3600) ) ctx = CommandContext("fast-export", args) mark = 0 if pseudotime: username = "J. Random Hacker" useremail = "jrh@nowhere.man" else: username = polystr(capture_or_die("git config --get user.name")).strip() useremail = polystr(capture_or_die("git config --get user.email")).strip() attribution = "%s <%s>" % (username, useremail) markmap = {} tips = {} last_commit_mark = 0 # This is meant to be consumed by reposurgeon's importer sys.stdout.write( "#sourcetype %s\n" % {"RCS": "rcs", "SCCS": "sccs"}.get(repodir, "src") ) for arg in ctx.args: if not registered(arg): croak("%s is not registered" % arg) executable = os.stat(backend.history(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.manager(arg) as xc: for i in range(ctx.lo, ctx.hi + 1): item = metadata.by_revno(i) with backend.cat(xc.pathbase, item.native) as fp: content = fp.read() # this data will be binary size = len(content) # size will be # of bytes, as desired mark += 1 markmap[item.revno] = mark sys.stdout.write("blob\nmark :%d\ndata %d\n" % (mark, size)) sys.stdout.write(polystr(content) + "\n") # Ideally this would be in Git canonical even with tags. # This is tricky; see reposurgeon's rules for branch coloring. # It's not really worth the extra complexity as long at these # streams round-trip properly. branch = item.branch if branch == "trunk": branch = "master" oldbranch = branch for c in "~^\\*?": branch = branch.replace(c, "") if not branch: croak("branch name %s is ill-formed" % oldbranch) elif branch != oldbranch: announce("branch name %s sanitized to %s" % (oldbranch, branch)) if branch not in tips: sys.stdout.write("reset refs/heads/" + branch + "\n") sys.stdout.write("commit refs/heads/%s\n" % branch) # Hidden magic for cluing in reposurgeon if "--reposurgeon" in args: oid = item.revno if repodir != ".src": oid = item.native sys.stdout.write("#legacy-id %s\n" % oid) sys.stdout.write("mark :%d\n" % (mark + 1)) sys.stdout.write(attribute(item, "author", attribution)) sys.stdout.write(attribute(item, "committer", attribution)) 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) arg = xc.pathbase if arg == ".srcignore": arg = ".gitignore" 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 tips[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]) ) # At some point git-fast-export stopped issuing branch-tip resets. # for branch in tips: # sys.stdout.write("reset refs/heads/%s\nfrom :%d\n\n" % (branch, tips[branch])) def fast_import_method(*args): "Accept a git fast-import stream on stdin, turn it into file histories." if not isinstance(backend, RCS): croak("fast-import is only supported with the RCS backend") 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), "fast_import_method", missing="rcs-fast-import", ) try: os.makedirs(repodir) except OSError: pass for fn in os.listdir("RCS"): corresponding = os.path.join("RCS", os.path.basename(fn)) fn = os.path.join(repodir, os.path.basename(fn)) if os.path.exists(fn): croak("%s exists, aborting leaving RCS in place!" % corresponding) rename(corresponding, fn, "fast-import") shutil.rmtree("RCS") # pylint: disable=unused-argument def version_method(*args): "Report SRC's version" sys.stdout.write("src: %s\n" % version) (major, minor, micro, _releaselevel, _serial) = sys.version_info sys.stdout.write("python: %s.%s.%s\n" % (major, minor, micro)) sys.stdout.write("%s: %s\n" % (backend.__class__.__name__, backend.version())) sys.stdout.write("platform: %s\n" % sys.platform) if os.path.exists(".git"): # pragma: no cover sys.stdout.write("revision: %s\n" % capture_or_die("git rev-parse HEAD")) dispatch = { "help": help_method, "commit": commit_method, "ci": commit_method, "add": add_method, "amend": amend_method, "am": amend_method, "init": init_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, "visualize": visualize_method, "vis": visualize_method, "fast-export": fast_export_method, "fast-import": fast_import_method, "release": release_method, "srcify": srcify_method, "version": version_method, } # Interpreting branch and revision numbers # # SCCS and RCS were originally designed on the assumption that a revision # within a branch is named by a major and minor release number. The # terminology used for these parts has varied. When you check in a change # without specifing a revision, the minor number is incremented from the one # on the tip of the current branch and the major number is left unchanged. # # RCS conventions are better documented. Examples from # the GNU RCS manual follow; see # https://www.gnu.org/software/rcs/manual/rcs.html # sections 1.2.3 and 3.1.2 for details. # # 1.1 -- revision number for initial checkin (typically); # branch number: 1 # next higher branch number: 2 # next higher revision number: 1.2 # # 9.4.1.42 -- more complicated (perhaps after much gnarly hacking); # branch number: 9.4.1 # next higher branch number: 9.4.2 # next higher revision number: 9.4.1.43 # # 33.333.333 -- not a valid revision number; # however, a perfectly valid branch number # next higher branch number: 333.333.334 # next higher revision number: 333.333.333.1 # # A revision ID may have any (even) number of components. Branches are designated # by IDs with an odd number of components. Revision and branch numbers never # contain zero (the manual says "All integers are positive."). # # The manual says: "The branch point of a non-trunk branch is the # revision number formed by removing the branch’s trailing integer. To # compute the next higher branch or revision number, add one to the # trailing integer. The highest-numbered revision on a branch is # called the tip of the branch (or branch tip)." # # SCCS numbering (not supported yet) works differently from RCS # numbering. Details at http://osr507doc.sco.com/en/tools/SCCS_delta_numbering.html # Unfortunately, he official GNU SCCS documentation at # https://www.gnu.org/software/cssc/manual/index.html # has almost nothing useful to say about it. # # SCCS node IDs have at most 4 parts in the form R.B.L.S (release, branch, # level, sequence - slightly different terminology than RCS would later use). # Branch IDs are distinguished by an explicit trailing zero. # # 1.0 - Trunk banch ID # 1.1 - First checkin on trunk # 1.1.1.0 - ID of first branch from trunk v1.1 # 1.1.1.1 - Next checkin on that branch # 1.1.2.0 - Second branch from v1.1 # 1.2 - Next checkin on trunk. # # The main difference is that in original AT&T SCCS you could not # branch from a branch, only from trunk. This restriction was removed # in at least some later versions, including CSSC and the Schilling # fork. In section 3.5.3 the CSSC manual says # # "When a branch is created from an existing sid, the release and level # numbers are copied, the branch number is set to the lowest unused # value for that release and level, and the sequence number is set to # one. Hence the first branch from version 1.1 will be version 1.1.1.1, # and if a branch is made from that, its sid will be 1.1.2.1." # # Jorg Schilling writes, 2018-11-29: "I cannot speak for RCS, but the # naming conventions used for branches in SCCS are not engraved into # the sources but rather a convention that is encouraged by the way # "get -e -b" works with or without -rSID option. SCCS internally uses # serial numbers and for this reason it is currently limited to 2G # deltas even though the R.B.L.S scheme could allow more. You could # even edit the p.file and control the SID that is used for the next # delget(1) as long as you don't violate basic rules." # # In both SCCS and RCS, you normally construct branch numbers to pass them # to the checkin command to make the checkin happen on a new branch. # The actual ID generated for that revision will be different; # in RCS it will have a 1 appended, in RCS the trailing 0 will be # replaced with a 1. # # In SCCS, it is documented in one SCO version that passing a branch # number to a retrieval command will retrieve the branch tip revision. # This is not documented in Solaris or GNU SCCS. Nor is it explictly # documented in GNU RCS, though there are hints in various parts related # to revision numbers and it actually works there. # # Interpreting symbol values # # SCCS doesn't have symbols (name-to-revision or name-to-branch # associations) at all. RCS has them and stores them in a header # section of the master file. # # A weird curveball that RCS tosses is that the values of branch symbols are # sometimes (always?) stored in masters with a zero inserted as the second # to last component. That is, for example, "1.3.1" is stored as "1.3.0.1" # and even displayed that way in rlog output. I have seen, but cannot find, # an RCS document that muttered this was an "efficiency hack". SRC never # had to notice this quirk, as it always refers to branches by name. # # The release-numbering problem # # In all of the above examples except two deliberately odd ones from the GNU # manual, the major part of a revision ID is always 1. It is possible to # change the major part by specifying a revision when you check in, but this # has seldom actually been done. SRC itself never does this, but it's a # possibility (if a remote one) in CVS, RCS, and SCCS collections. # # This possibility matters when we are trying to find the branch tip # or base associated with a particular revision. Breaks introduced # by major-number changes will screw up the traversal. # # Note that SRC uses the empty string as the predecessor of the first # (1.1) revision. class RevisionMixin: "Express common operations on RCS and SCCS revisions." @staticmethod def splitrev(rev): "Native revision to numeric tuple." return [int(d) for d in rev.split(".")] @staticmethod def joinrev(rev): "Numeric tuple to native revision." return ".".join([str(d) for d in rev]) def pred(self, rev): "Our predecessor. Walks up parent branch." # Assumes the release number has never beem bumped. 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 node, in any back end." # Assumes the release number is never bumped. if rev: n = self.splitrev(rev) n[-1] += 1 return self.joinrev(n) else: return "1.1" def branch_to_base(self, revid): "Go from a branch ID 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 tag to the tip revision of its branch." rev = self.branch_to_base(revid) 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 branch_child(self, name, revision, metadata): "Compute a base revision for a named branch." if name in metadata.symbols: return metadata.symbols[name] else: def branchfrom(c, p): "Is c a branch child (not direct descendant) of parent p?" c = self.splitrev(c) p = str(p) 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.revno) ] ) newsib += 1 base = baserev.native + "." + str(newsib) return base class RCS(RevisionMixin): "Encapsulate RCS back end methods." delimiters = ( "----------------------------", "=============================================================================", ) RCS_SAVE = "RCS-save" class RCSManager: "Execution context for backend methods." def __init__(self, path): self.path = path self.pathbase = os.path.basename(path) self.__where = os.getcwd() self.__deferred = [] self.__previous_handlers = {} def defer_signal( self, sig_num, stack_frame ): # pragma: no cover (passed as hook) self.__deferred.append(sig_num) def __enter__(self): # Replace existing signal handlers with deferred handler for sig_num in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM): # signal.signal returns None when no handler has been # set in Python, which is the same as the default # handler (SIG_DFL) being set self.__previous_handlers[sig_num] = ( signal.signal(sig_num, self.defer_signal) or signal.SIG_DFL ) if os.path.dirname(self.path): dirname = os.path.dirname(self.path) chdir(dirname, "enter from %s" % (caller(2) if debug else None)) if not os.path.exists(repodir): croak("repository subdirectory %s does not exist" % relative(repodir)) elif repodir != "RCS" and os.path.exists(repodir): if os.path.exists("RCS"): rename("RCS", RCS.RCS_SAVE, "stashing") rename(repodir, "RCS", "setting up for RCS") return self def __exit__(self, extype, value, traceback_unused): if repodir != "RCS" and not os.path.exists(repodir): rename("RCS", repodir, "restoring") if os.path.exists(RCS.RCS_SAVE): rename(RCS.RCS_SAVE, "RCS", "unstashing") chdir(self.__where, "within %s exit" % (caller(2) if debug else None)) if extype and debug > 0: raise extype(value) # Restore handlers for sig_num, handler in self.__previous_handlers.items(): signal.signal(sig_num, handler) # Send deferred signals while self.__deferred: sig_num = self.__deferred.pop(0) os.kill(os.getpid(), sig_num) return True @staticmethod def manager(path): return RCS.RCSManager(path) @staticmethod def history(arg): "History file corresponding to an RCS workfile." # The reason this is required is that we might not be within the # manager context when this function is called. Thus we have to # check both possible locations for the master. for d in (backend.__class__.__name__, repodir): p = os.path.join(os.path.dirname(arg), d, os.path.basename(arg) + ",v") if os.path.exists(p): return p return p # Use repodir as a default for nonexistent targets @staticmethod def workfile(arg): "Workfile corresponding to an RCS master" arg = arg[:-2] parts = arg.split(os.path.sep) if len(parts) > 1 and repodir in parts: parts.remove(repodir) arg = os.path.sep.join(parts) return arg @staticmethod def isbranch(revid): "Is this a branch symbol?" return (revid.count(".")) % 2 == 0 def revision_to_branch(self, revid): "Go from a revision to its branch." return self.joinrev(self.splitrev(revid)[:-1]) def branch_to_parent(self, revid): "Go from a revision or branch ID tag to the revision it was based on." remove = 1 if self.isbranch(revid) else 2 return self.joinrev(self.splitrev(revid)[:-remove]) @staticmethod def is_history(path): return path.endswith(",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 @staticmethod def register(arg): "Register a file. *Not* called from a manager context." rcs_master = os.path.join("RCS", arg + ",v") master = os.path.join(repodir, arg + ",v") if repodir != "RCS" and os.path.exists(rcs_master): croak("name collision with a pre-existing RCS directory.") # repodir could be .src or RCS or something random; cope if not os.path.isdir(repodir): if debug >= DEBUG_COMMANDS: logit("mkdir(%s)\n" % repodir) os.mkdir(repodir) # Key choices here: -b suppresses all keyword expansion, -U sets # non-strict locking (which makes branch appends less painful). do_or_die( "rcs -q -U -kb -i {0} /dev/null") m = re.search(r"[0-9]+\.[0-9]+\.[0-9]+".encode("ascii"), rawversion) return m and polystr(m.group(0)) def parse(self, metadata, basename): "Get and parse the RCS log output for this file." def sortkey(rev): return rev.date + ".".join("%010d" % int(n) for n in rev.native.split(".")) def degrottify(rev): # Undo RCS's "efficiency hack" (that's what the manual called it). parts = rev.split(".") if len(parts) > 3 and parts[-2] == "0": parts = parts[:-2] + parts[-1:] return self.joinrev(parts) metadata.symbols["trunk"] = "1" metadata.tipbranch = "trunk" with popen_or_die( "cd %s >/dev/null; rlog '%s' 2>/dev/null; cd ..>/dev/null" % (shellquote(repodir), shellquote(basename)), caller(1, "metadata parse") if debug else None, ) as fp: if debug >= DEBUG_PARSE: logit("\t-> init\n") state = "init" for line in fp: line = polystr(line) if debug >= DEBUG_PARSE: logit("in: %s\n" % repr(line)) if state == "init": if line.startswith("locks:"): if debug >= DEBUG_PARSE: logit("\t-> locks\n") state = "locks" elif line.startswith("symbolic names:"): if debug >= DEBUG_PARSE: logit("\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 rcs -b, that resets to the dynamically # highest branch. if not branch or branch == "1": metadata.tipbranch = "trunk" else: metadata.tipbranch = degrottify(branch) elif line.startswith("description:"): state = "description" elif state == "description": if line.startswith("============================"): break elif line.startswith("----------------------------"): if debug >= DEBUG_PARSE: logit("\t-> logheader\n") state = "logheader" metadata.revlist.append(HistoryEntry(metadata)) metadata.description = metadata.description[:-1] else: metadata.description += line elif state == "locks": if not line[0].isspace(): if debug >= DEBUG_PARSE: logit("\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: logit("\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] = degrottify(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("======================="): # This deals with RCS v5.7 issuing a log header # divider just before the terminator, something # v5.8 does not do. if not metadata.revlist[-1].native: metadata.revlist.pop() elif 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, set the tip branch by name. if metadata.tipbranch != "trunk": for (k, v) in list(metadata.symbols.items()): if v == metadata.tipbranch: metadata.tipbranch = k break else: croak("unrecognized branch ID '%s'" % metadata.tipbranch) metadata.revlist.sort(key=sortkey) 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: # sys.stdout.write("\t%d revisions\n" % len(metadata.revlist) logit("\tlockrevs: %s\n" % metadata.lockrevs) logit("\tsymbols: %s\n" % metadata.symbols) metadata.build_indices() class SCCS(RevisionMixin): "Encapsulate SCCS back end methods." delimiters = ("-X-X-X-X-X--X-X-X-X-X--X-X-X-X-X-",) class SCCSManager: "Execution context for backend methods." def __init__(self, path): self.path = path self.pathbase = os.path.basename(path) self.__where = os.getcwd() if not os.path.isdir("SCCS"): croak("no SCCS directory.") self.__deferred = [] self.__previous_handlers = {} def defer_signal( self, sig_num, stack_frame ): # pragma: no cover (passed as hook) self.__deferred.append(sig_num) def __enter__(self): # Replace existing signal handlers with deferred handler for sig_num in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM): # signal.signal returns None when no handler has been # set in Python, which is the same as the default # handler (SIG_DFL) being set self.__previous_handlers[sig_num] = ( signal.signal(sig_num, self.defer_signal) or signal.SIG_DFL ) if os.path.dirname(self.path): dirname = os.path.dirname(self.path) chdir(dirname, "within %s enter" % (caller(2) if debug else None)) if not os.path.exists(repodir): croak("repository subdirectory %s does not exist" % relative(repodir)) return self def __exit__(self, extype, value, traceback_unused): chdir(self.__where, "within %s exit" % (caller(2) if debug else None)) # Restore handlers for sig_num, handler in self.__previous_handlers.items(): signal.signal(sig_num, handler) # Send deferred signals while self.__deferred: sig_num = self.__deferred.pop(0) os.kill(os.getpid(), sig_num) return True @staticmethod def manager(path): return SCCS.SCCSManager(path) @staticmethod def __sccsfile(arg, pref): return os.path.join( os.path.dirname(arg), "SCCS", pref + "." + os.path.basename(arg) ) @staticmethod def history(arg): "History file corresponding to an SCCS workfile." return SCCS.__sccsfile(arg, "s") @staticmethod def workfile(arg): "Workfile corresponding to an SCCS master" if "SCCS" in arg: arg = arg.replace("SCCS/s.", "") elif arg.startswith("s."): arg = arg[2:] return arg @staticmethod def isbranch(revid): "Is this a branch symbol?" return revid.endswith(".0") def revision_to_branch(self, revid): "Go from a revision to its branch." return self.joinrev(self.splitrev(revid)[:-1]) + ".0" def branch_to_parent(self, revid): "Go from a revisiob or branch ID tag to the revision it was based on." return self.joinrev(self.splitrev(revid)[:-2]) @staticmethod def is_history(path): return os.path.basename(path).startswith("s.") @staticmethod def has_revisions(arg): "Does the master for this file have any revisions" # It's not possible to create an SCCS file without at least one # revision. return True @staticmethod def register(arg): "Register a file" if not os.path.isdir("SCCS"): os.mkdir("SCCS") def checkin(self, arg, comment): "Check in a commit, with comment." if os.path.exists(self.history(arg)): cmd = "delta -s -y{1} {0}".format(shellquote(arg), shellquote(comment)) else: # Yuck - 2>/dev/null is required to banish the message # admin: warning: SCCS/XXXXX: No id keywords. cmd = "admin -fb -i {0} -y{1} <{0} 2>/dev/null".format( shellquote(arg), shellquote(comment) ) do_or_die("TZ=UTC sccs " + cmd, caller(1, "checkin") if debug else None) # After checkin, make it writeable (and locked) again. do_or_die( "rm -f {0} && sccs get -e -s {0} >/dev/null".format(shellquote(arg)), caller(1, "get after checkin") if debug else None, ) def checkout(self, arg, revision): "Check out a revision. Leaves it writeable." do_or_die("rm -f 'SCCS/p.{0}'".format(arg), caller(1) if debug else None) if revision: do_or_die( "rm -f {0} && sccs get -s -e -r{1} {0} >/dev/null".format( shellquote(arg), revision ), caller(1, "checkout (revision)") if debug else None, ) else: do_or_die( "rm -f '{0}' && sccs get -s -e {0} >/dev/null".format(shellquote(arg)), caller(1, "checkout (no revision)") if debug else None, ) def amend(self, arg, rev, comment): "Amend a commit comment." comment = "'" + comment.replace("'", r"'\''") + "'" do_or_die( "sccs cdc -r{1} -y{2} {0}".format( shellquote(arg), rev, shellquote(comment) ), caller(1, "amend") if debug else None, ) def cat(self, arg, revision): "Ship the contents of a revision to stdout or a named file." if revision: return popen_or_die( "sccs get -s -p -r{1} {0} 2>/dev/null".format( shellquote(arg), revision ), caller(1, "metadata parse (revision)") if debug else None, ) else: return popen_or_die( "sccs get -p {0}".format(shellquote(arg)), caller(1, "metadata parse (no revision)") if debug else None, ) def delete_tag(self, tagname, metadata): "Delete a specified tag." croak("tags are not supported in the SCCS back end") # pragma: no cover def set_tag(self, tagname, revision, metadata): "Set a specified tag." croak("tags are not supported in the SCCS back end") # pragma: no cover def delete_branch(self, _branchname, _metadata): "Delete a specified branch." croak("branches are not supported in the SCCS back end") # pragma: no cover def set_branch(self, _revision, _filename): "Set the specified branch to be default, creating it if required." croak("branches are not supported in the SCCS back end") # pragma: no cover def make_branch(self, name, revision, metadata): "Set the specified branch to be default, creating it if required." croak("branches are not supported in the SCCS back end") # pragma: no cover def move(self, source, target): "Move a file and its history." do_or_die( "mv {0} {1} && mv {2} {3}".format( shellquote(source), shellquote(target), shellquote(self.history(source)), shellquote(self.history(target)), ), caller(1, "move") if debug else None, ) def copy(self, source, target): "Copy a file and its history." do_or_die( "cp {0} {1} && cp {2} {3}".format( shellquote(source), shellquote(target), shellquote(self.history(source)), shellquote(self.history(target)), ), caller(1, "copy") if debug else None, ) @staticmethod def release(arg): "Release locks." do_or_die( "sccs admin -dla {0}".format(shellquote(arg)), caller(1, "release") if debug else None, ) @staticmethod def version(): rawversion = capture_or_die("sccs --version 2>&1") m = re.search(r"[0-9]+\.[0-9]+\.[0-9]+".encode("ascii"), rawversion) return m and polystr(m.group(0)) def parse(self, metadata, basename): "Get and parse the SCCS log output for this file." metadata.symbols["trunk"] = "1.0" with popen_or_die( "sccs prs -e -d':FD::Dt:\n:C:{1}' {0} 2>/dev/null".format( shellquote(basename), SCCS.delimiters[0] ), caller(1, "metadata parse") if debug else None, ) as fp: if debug >= DEBUG_PARSE: logit("\t-> init\n") state = "init" for line in fp: line = polystr(line) if debug >= DEBUG_PARSE: logit("in %s: %s\n" % (state, repr(line))) if state == "init": if line == "none\n": line = "" metadata.description = line state = "header" elif state == "header": comment = "" if line.startswith("D "): try: (_, rev, yymmdd, hhmmss) = line.split()[:4] metadata.revlist.append(HistoryEntry(metadata)) metadata.revlist[-1].native = rev yymmdd = yymmdd.replace("/", "-") # In Schilling's SCCS the year has a century part, # in CSSC it does not (yet, as of 2023). Sun says: # # 'The X/Open standard states that old dates held in # ("yy/mm/dd") format does not change in "s." files, but # the values "yy" which range from 69 - 99 are to be # interpreted as 1969 - 1999 respectively. Values of "yy" # which range from 00 - 68 are to be interpreted as 2000 # - 2068 respectively.' # # This disambiguates out to 2068. Note that on 32-bit # platforms there will be a year-2038 problem sooner # than that. year = yymmdd.split("-")[0] if len(year) < 4: if year <= "68": yymmdd = str(20) + yymmdd else: yymmdd = str(19) + yymmdd # pragma: no cover metadata.revlist[-1].date = yymmdd + "T" + hhmmss + "Z" except ValueError: # pragma: no cover croak( "ill-formed delta line" ) # pragma: no cover (should never happen) if debug >= DEBUG_PARSE: logit("\t-> header\n") state = "comment" elif state == "comment": if line == SCCS.delimiters[0] + "\n": metadata.revlist[-1].log = comment.rstrip() + "\n" if debug >= DEBUG_PARSE: logit("\t-> init\n") state = "header" else: comment += line 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() try: with open(self.__sccsfile(metadata.filename, "p"), "rb") as fp: for line in fp: metadata.lockrevs.append(polystr(line).split()[0]) except IOError: pass metadata.build_indices() backends = (RCS, SCCS) if __name__ == "__main__": try: commandline = list(sys.argv[1:]) repodir = ".src" backend = RCS multidir = os.path.exists(".src") and os.path.exists("RCS") startdir = os.getcwd() # If there's no .src directory, use the history # directory of whichever back end is active. if not os.path.exists(".src"): for vcs in backends: if os.path.exists(vcs.__name__): repodir = vcs.__name__ backend = vcs break 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] commandline.pop(0) elif commandline[0] == "-L": logstream = open(commandline[1], "a", encoding=master_encoding) commandline.pop(0) else: croak( "unknown option %s before command verb" % commandline[0] ) # pragma: no cover commandline.pop(0) if debug >= DEBUG_COMMANDS: logit("Starting at %s\n" % startdir) time.sleep(0.1) # Prevents some kind of weird buffering screwup. # User might want to force the back end for vcs in backends: if commandline and commandline[0] == vcs.__name__.lower(): backend = vcs commandline.pop(0) break if not commandline: help_method() raise SystemExit(0) # pragma: no cover # Ugly constraint... if backend.__name__ == "SCCS": multidir = False repodir = "SCCS" elif backend.__name__ == "RCS": # In theory we could do this check only when .src exists. In practice, # we prefer making the program's behavior safer and easier for a human # to reason about - in doubtful cases it should just bail out rather than # trying to be overly clever. if os.path.exists(RCS.RCS_SAVE): croak( "%s exists: a previous SRC must have crashed hard." % RCS.RCS_SAVE ) backend = backend() if commandline[0] in dispatch: dispatch[commandline[0]](*commandline[1:]) else: croak("no such command as '%s'. Try 'src help'" % commandline[0]) except KeyboardInterrupt: # pragma: no cover pass # The following sets edit modes for GNU EMACS # Local Variables: # mode:python # End: src-1.33/src.10000664000175000017500000004577114544571352011276 0ustar esresr'\" t .\" Title: src .\" Author: [FIXME: author] [see http://www.docbook.org/tdg5/en/html/author] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 01/01/2024 .\" Manual: \ \& .\" Source: \ \& .\" Language: English .\" .TH "SRC" "1" "01/01/2024" "\ \&" "\ \&" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" src \- simple revision control .SH "SYNOPSIS" .sp \fBsrc\fR [command] [revision\-spec] [\fIfile\fR\&...] .SH "DESCRIPTION" .sp SRC (or src) is simple revision control, a version\-control system for single\-file projects by solo developers and authors\&. It modernizes the venerable RCS, hence the anagrammatic acronym\&. The design is tuned for use cases like all those little scripts in your \fI~/bin\fR directory, or a directory full of single\-file HOWTOs\&. .sp SRC revision histories are single, human\-readable files beneath a hidden \fI\&.src\fR subdirectory in the directory where they live\&. There may be multiple histories under one directory; SRC treats them as separate projects, and history files can be moved elsewhere at any time\&. .sp SRC gives you simple, consecutive integer revision numbers\&. It supports tags and branching\&. It records commit timestamps, but does not show committer information, because the committer is always you\&. The command set is intended to look familiar if you have ever used Subversion, Mercurial, or Git\&. .sp SRC is lightweight and fast\&. It uses two small self\-contained executables, with no libraries and no complications\&. .sp SRC interprets the EDITOR variable in the usual way, using it to spawn an editor instance when you perform a commit or amend\&. If EDITOR is not set it has a fallback list of editors it looks for, beginning with various ways to invoke Emacs and vi\&. .sp SRC is fully supported in Emacs VC mode\&. .SH "COMMAND SUMMARY" .sp 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\&. Revision numbers always increase in commit\-date order\&. .sp 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)\&. .sp If SRC complains that your revision spec looks like a nonexistent filename, you can prefix it with "@" (this is always allowed)\&. "@" by itself means the current (checked\-out) revision\&. .sp A filename can be a path\&. In that case SRC will behave as though it were running in the lowest\-level directory on the path and called with the path basename\&. .sp Unless otherwise noted under individual commands, the default revision is the tip revision on the current branch and the default range is all revisions on the current branch\&. .sp 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\&. .PP src help [\fIcommand\fR] .RS 4 Displays help for commands\&. .RE .PP src commit [\-|\-m \fIstring\fR|\-f \fIfile\fR|\-e|\-b branch] [\fIfile\fR\&...] .RS 4 Enters a commit for specified files\&. Separately to each one\&. A history is created for the file if it does not already exist\&. With \fI\-\fR, take comment text from stdin; with \fI\-m\fR use the following string as the comment; with \fI\-f\fR take from a file\&. With \fI\-e\fR, edit even after \fI\-\fR, \fI\-f\fR or \fI\-m\fR\&. "ci" is a synonym for "commit"\&. With \fI\-b\fR, set ther named branch to check in to (it must exist); that branch becomes the default for commits\&. .RE .PP src amend [\-|\-m \fIstring\fR|\-f \fIfile\fR|\-e] [\fIrevision\fR] [\fIfile\fR\&...] .RS 4 Amends the stored comment for a specified revision, defaulting to the latest revision on the current branch\&. Flags are as for commit\&. "am" is a synonym for "amend"\&. .RE .PP src checkout [\fIrevision\fR] [\fIfile\fR\&...] .RS 4 Refresh the working copy of the file(s) from their history files\&. "co" is a synonym for "checkout"\&. .RE .PP src cat [\fIrevision\fR] [\fIfile\fR\&...] .RS 4 Send the specified revision of the files to standard output\&. .RE .PP src status [\-a] [\fIfile\fR\&...] .RS 4 "A" = added, "=" = unmodified, "M" = modified, "!" = missing, "?" = not tracked, "I" = ignored, "L" = locked (recover with "src checkout")\&. The "A" and "L" statuses should only occur if you have used RCS directly on a file\&. Normally "?" and "I" files are not listed; this changes if you either give the \fI\-a\fR switch or specify which files to look at\&. "st" is a synonym for "status"\&. .RE .PP src tag [list|\-l|create|\-c|delete|del|\-d] [\fIname\fR] [\fIrevision\fR] [\fIfile\fR\&...] .RS 4 List tags, create tags, or delete tags\&. Create/delete takes a revision, defaulting to the current branch tip\&. List defaults to all revisions\&. .RE .PP src branch [list|\-l|create|\-c|delete|del|\-d] [\fIname\fR] [\fIfile\fR\&...] .RS 4 List, create, or delete branches\&. When listing, the active branch is first in the list\&. The default branch is "trunk"\&. Create/delete takes a singleton revision, defaulting to the current branch tip; on create, the branch becomes default for future commits\&. List defaults to all revisions, including 0 (the trunk root phantom revision)\&. .RE .PP src rename [\fItag\fR|\fIbranch\fR] [\fIoldname\fR] [\fInewname\fR] [\fIfile\fR\&...] .RS 4 Rename a tag or branch\&. Refuses to step on an existing symbol or rename a nonexistent one\&. "rn" is a synonym for "rename"\&. .RE .PP src list [(\-|\-l )] [\-f \fIfmt\fR] [\fIrevision\-range\fR] [\fIfile\fR\&...] .RS 4 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 \fIhelp list\fR for information about custom formats\&. Use \fI\-\fR or \fI\-l \fR, where is a number, to limit the listing length\&. Default range is the current branch, reversed\&. "li" is a synonym for "list"\&. .RE .PP src log [\-v] [(\-|\-l )] [(\-p|\-u|\-c) [\-b|\-w]] [\fIrevision\-range\fR] [\fIfile\fR\&...] .RS 4 Sends log information about the specified commits to standard output\&. Use \fI\-\fR or \fI\-l \fR, where is a number, to limit the listing length\&. Default range is the current branch, reversed\&. The \fI\-\-patch\fR, \fI\-p\fR or \fI\-u\fR option additionally sends a unified\-format diff listing to standard output for each revision against its immediate ancestor revision; \fI\-c\fR emits a context diff instead\&. When generating a diff, \fI\-b\fR ignores changes in whitespace, and \fI\-w\fR ignores all whitespace\&. Histories imported via \fIfast\-import\fR (when not using its \fI\-p\fR option) have RFC\-822\-style headers inserted into the log comment to preserve metadata not otherwise representable in SRC, such as distinct author and committer identifications and dates\&. These headers are normally suppressed by \fIlog\fR, however, \fI\-v\fR shows a summarized view of important headers; \fI\-v \-v\fR shows all headers as\-is\&. .RE .PP src diff [(\-u|\-c) [\-b|\-w]] [\fIrevision\-range\fR] [\fIfile\fR\&...] .RS 4 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\&. The actual difference generation is done with diff(1)\&. The default diff format is \fI\-u\fR (unified), but if you specify a \fI\-c\fR option after the verb a context diff will be emitted\&. \fI\-b\fR ignores changes in the amount of whitespace, and \fI\-w\fR ignores all whitespace\&. "di" is a synonym for "diff"\&. .RE .PP src ls .RS 4 List all registered files\&. .RE .PP src visualize .RS 4 Emit a DOT visualization of repository structures\&. To use this, install the graphviz package and pipe the output to something like "dot \-Tpng | display \-"\&. "vis" is a synonym for "visualize"\&. .RE .PP src move \fIold\fR \fInew\fR .RS 4 Rename a workfile and its history\&. Refuses to step on existing workfiles or histories\&. "mv" is a synonym for "move"\&. .RE .PP src copy \fIold\fR \fInew\fR .RS 4 Copy a file and its master\&. Refuses to step on existing files or masters\&. "cp" is a synonym for "copy"\&. .RE .PP src fast\-export [\fIrevision\-range\fR] [\fIfile\fR\&...] .RS 4 Export one or more projects as a Git fast\-import stream\&. For a history originally imported from elsewhere, author and committer identification is gleaned from the RFC\-822\-style headers inserted into the commit comment by \fIfast\-import\fR (if its \fI\-p\fR option was not used)\&. Otherwise, this information is copied from your Git configuration\&. .RE .PP src fast\-import [\-p] [\fIfiles\fR\&...] .RS 4 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 \fI\-p\fR (plain) option is given, in which case this metadata is discarded\&. Give arguments to restrict the files imported\&. .RE .PP src release [\fIfile\fR\&...] .RS 4 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) state\&. .RE .PP src srcify .RS 4 Move a directory from being RCS\- or SCCS\-managed to being SRC\-managed\&. That is: if the current directory contains an RCS directory, rename it to \&.src (but leave any SCCS directory in place)\&. Then check out all masters for editing that are not already checked out\&. .RE .PP src version .RS 4 Report the versions of SRC, the underlying Python, and the RCS or SCCS back end\&. .RE .sp The omission of "src remove" is a deliberate speed bump\&. .sp If no files are specified, all eligible files are operated on in sequence\&. .SH "NOISE CONTROL" .sp Silence is golden\&. When you have selected only one file to operate on, and the command is not a report generator (\fIstatus\fR, \fIcat\fR, \fIlog\fR, \fIlist\fR, \fIfast\-export\fR, the listing modes of \fItag\fR and \fIbranch\fR, \fIls\fR) you will see a reply only if the operation failed\&. .sp Other commands (\fIcommit\fR, \fIcheckout\fR, tag creation and deletion) give you a success message per file when operating on multiple files, so you will not be in doubt about which operation succeeded\&. This behavior can be suppressed with the \fI\-q\fR option, placed \fIbefore\fR the subcommand word\&. .sp If your directory contains a file named "\&.srcignore", each line that is neither blank nor begins with a "#" is interpreted as an ignore pattern\&. It is expanded with glob(3), and files in the expansion are omitted from \fIsrc status\fR \- unless the file is named as an argument, of the status command, in which case its status is "I"\&. Thus, for example, a line reading "*\&.html" will cause all files with an HTML extension to be omitted from the output of "src status", but the output of \fIsrc status *\fR will list them with status "I"\&. .SH "BACKWARD COMPATIBILITY" .sp SRC history files are (normally) RCS master files\&. SRC maintains no permanent state other than these files\&. .sp In order to maintain complete backwards compatibility, one other compromise was made: any commit comment containing a string exactly matching an RCS log delimiter (a long string of "\-" characters) will be rejected as malformed\&. .sp The RCS back end will be automatically selected when there is an \fI\&.src\fR or \fIRCS\fR subdirectory\&. If both these directories exist, SRC will operate on \fI\&.src\fR and preserve the RCS directory; in this case it will be a little extra verbose to leave no doubt about what it is doing\&. .sp You can explicitly select the RCS back end by making the first command keyword on the src command line be \fIrcs\fR\&. This should only be necessary when your working directory contains two or more of the subdirectories \fI\&.src\fR, \fIRCS\fR, and \fISCCS\fR\&. .sp If your directory has both a \fI\&.src\fR and an unrelated \fIRCS\fR directory you can force SRC to work on the RCS directory and ignore \fI\&.src\fR by giving it the option "\-S RCS"\&. .sp By default, history files are kept in a hidden subdirectory named \fI\&.src\fR\&. But if you have an \fIRCS\fR subdirectory and no \fI\&.src\fR, SRC will quietly operate on the files in the \fIRCS\fR directory in a completely backward\-compatible way\&. .SH "WORKING WITH SCCS" .sp Using SCCS as a back end is also supported, with some limits due to missing features in SCCS implementations: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} SCCS tags are an SRC\-only extension that won\(cqt be visible from SCCS running natively\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} All commands relating to tags and branches throw an error in the SCCS back end\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} In CSSC SCCS, src cat does not necessarily pipe out binary data correctly\&. This has been fixed in the SunOS and Schilling versions\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} The CSSC SCCS, the exec bit is not propagated between master and workfile\&. This has been fixed in the SunOS and Schilling versions\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} The CSSC and SunOS SCCS backends have a Y2\&.1K problem that SRC cannot effectively work around and will probably not be fixed\&. The Schilling version has repaired this\&. To be on the safe side, do not use the SCCS backend after the year 2067\&. .RE .sp The SCCS back end will be automatically selected when there is an \fISCCS\fR subdirectory and no \fI\&.src\fR or \fIRCS\fR subdirectory\&. .sp You can explicitly select the SCCS back end by making the first command keyword on the src command line be \fIsccs\fR\&. This should only be necessary when your working directory contains none or two or more of the subdirectories \fI\&.src\fR, \fIRCS\fR, and \fISCCS\fR\&. .sp Working with SCCS requires an \fISCCS\fR subdirectory; SRC will quietly create one, if required, then operate on the files in the \fISCCS\fR directory in a completely backward\-compatible way\&. .sp Fast\-import to SCCS is not supported\&. .sp The SCCS mode is not recommended unless you have a specific need to work with legacy SCCS repositories\&. Up\-converting them to something less Paleolithic (e\&.g\&. with sccs2rcs(1) or reposurgeon(1)) would be a better idea; in truth, the SCCS support exists mainly because it\(cqs hilarious (for obscure hacker values of \fIhilarious\fR)\&. .SH "DEBUGGING OPTIONS" .sp These will be of interest mainly to developers\&. They must go before the subcommand\&. .sp A \fI\-d\fR (debug) option before the main command word turns on debugging messages\&. Just one "\-d" gives you complete visibility about what commands the back end is running\&. It can be repeated for higher debugging levels that expose more of src\(cqs internal computation\&. .sp A \fI\-L\fR option sets a log file to which debug output dould be written Without this option it is written to standard error\&. .sp A \fI\-S\fR (sandbox) option can be used to set the repository directory to something other than its default of \fI\&.src\fR\&. Use "\-S RCS" to make src operate on an \fIRCS\fR directory even if there is alraady a \fI\&.src\fR directory\&. .sp A \fI\-T\fR option sets up an artificial clock that ticks once on each revision and fixes the user information to be used in \fIfast\-export\fR; It also attributes all commits to "J\&. Random Hacker"\&. It is for regression testing\&. .SH "REQUIREMENTS" .sp SRC is written in Python and requires 2\&.7 or later; it will run under Python 3\&.x for x > 2\&. .sp If you wish to use the RCS support (recommended), the RCS tools at version 5\&.7 or later must be installed and accessible in your $PATH\&. .sp If you wish to use the SCCS support, some implementation of SCCS must be accessible\&. GNU\(cqs CSSC (Compatibly Stupid Source Control) will work; so will the SunOS and Schilling forks of AT&T SCCS\&. .sp The rcs\-fast\-import(1) tool at version 1\&.3 or later is required to support the \fIsrc fast\-import\fR command\&. .sp SRC will die gracefully with a useful error message when it fails due to a missing back end\&. .SH "LIMITATIONS" .sp SRC will unconditionally bail out if a directory named \fIRCS\-save\fR exists\&. This is because in order to be able to use \fI\&.src\fR when an unrelated \fIRCS\fR subdirectory is also present, SRC has to play a game of three\-directory monte\&. Before doing its work it moves \fIRCS\fR to \fIRCS\-save\fR, then moves \fI\&.src\fR to \fIRCS\fR; after doing its work it moves \fIRCS\fR to \fI\&.src\fR and \fIRCS\-save\fR to \fIRCS\fR\&. If there is a pre\-existing \fIRCS\-save\fR this maneuver can\(cqt be done\&. If you trip over such a pre\-exiting \fIRCS\-save\fR, this probanly means SRC previously underwent a hard crash and you will have to resuffle these directories by hand\&. No bug that can produce duch a crash has yet been reported\&. .sp The directory shuffle also means that running more than one SRC edit session on the same directory at the same time may produce mysterious failures\&. Don\(cqt do this \- it is way outside the tool\(cqs intended performance envelope\&. .sp Branch deletions change the revision numbers of revisions downstream of the branch join\&. .sp In src fast\-export dumps of repositories with tags, branch labels may not exactly match what git fast\-export would emit\&. .sp In both RCS and SCCS revision numbers normally looked like "1\&.n" for n starting at 1 and monotonically increasing\&. It was possible to check in a change with a higher release number (for example, "2\&.1"), though this was seldom done\&. If you use SRC to view or edit an ancient master that used this feature, commands using ranges and named branches will not always work as exoected\&. .SH "REPORTING BUGS" .sp Report bugs to Eric S\&. Raymond \&. The project page is at http://catb\&.org/~esr/src .SH "SEE ALSO" .sp rcs(1), rcs\-fast\-import(1), sccs(1), svn(1), hg(1), git(1), dot(1), sccs2rcs\&. src-1.33/src.adoc0000664000175000017500000004110014544356237012025 0ustar esresr= src(1) = :doctype: manpage // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: CC-BY-4.0 == NAME == src - simple revision control == SYNOPSIS == *src* [command] [revision-spec] ['file'...] == DESCRIPTION == SRC (or src) is simple revision control, a version-control system for single-file projects by solo developers and authors. It modernizes the venerable RCS, hence the anagrammatic acronym. The design is tuned for use cases like all those little scripts in your _~/bin_ directory, or a directory full of single-file HOWTOs. SRC revision histories are single, human-readable files beneath a hidden _.src_ subdirectory in the directory where they live. There may be multiple histories under one directory; SRC treats them as separate projects, and history files can be moved elsewhere at any time. SRC gives you simple, consecutive integer revision numbers. It supports tags and branching. It records commit timestamps, but does not show committer information, because the committer is always you. The command set is intended to look familiar if you have ever used Subversion, Mercurial, or Git. SRC is lightweight and fast. It uses two small self-contained executables, with no libraries and no complications. SRC interprets the EDITOR variable in the usual way, using it to spawn an editor instance when you perform a commit or amend. If EDITOR is not set it has a fallback list of editors it looks for, beginning with various ways to invoke Emacs and vi. SRC is fully supported in Emacs VC mode. == COMMAND SUMMARY == 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. 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 SRC complains that your revision spec looks like a nonexistent filename, you can prefix it with "@" (this is always allowed). "@" by itself means the current (checked-out) revision. A filename can be a path. In that case SRC will behave as though it were running in the lowest-level directory on the path and called with the path basename. Unless otherwise noted under individual commands, the default revision is the tip revision on the current branch and the default range is all revisions on the current branch. 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. src help ['command']:: Displays help for commands. src commit [-|-m 'string'|-f 'file'|-e|-b branch] ['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". With '-b', set ther named branch to check in to (it must exist); that branch becomes the default for commits. 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. "am" is a synonym for "amend". src checkout ['revision'] ['file'...]:: Refresh the working copy of the file(s) from their history files. "co" is a synonym for "checkout". src cat ['revision'] ['file'...]:: Send the specified revision 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"). The "A" and "L" statuses should only occur if you have used RCS directly on a file. Normally "?" and "I" files are not listed; this changes if you either give the '-a' switch or specify which files to look at. "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. Create/delete takes a revision, defaulting to the current branch tip. List defaults to all revisions. src branch [list|-l|create|-c|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". Create/delete takes a singleton revision, defaulting to the current branch tip; on create, the branch becomes default for future commits. List defaults to all revisions, including 0 (the trunk root phantom revision). 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 )] [-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 '-' or '-l ', where is a number, to limit the listing length. Default range is the current branch, reversed. "li" is a synonym for "list". src log [-v] [(-|-l )] [(-p|-u|-c) [-b|-w]] ['revision-range'] ['file'...]:: Sends log information about the specified commits to standard output. Use '-' or '-l ', where is a number, to limit the listing length. Default range is the current branch, reversed. The '--patch', '-p' or '-u' option additionally sends a unified-format diff listing to standard output for each revision against its immediate ancestor revision; '-c' emits a context diff instead. When generating a diff, '-b' ignores changes in whitespace, and '-w' ignores all whitespace. Histories imported via 'fast-import' (when not using its '-p' option) have RFC-822-style headers inserted into the log comment to preserve metadata not otherwise representable in SRC, such as distinct author and committer identifications and dates. These headers are normally suppressed by 'log', however, '-v' shows a summarized view of important headers; '-v -v' shows all headers as-is. src diff [(-u|-c) [-b|-w]] ['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. The actual difference generation is done with diff(1). The default diff format is '-u' (unified), but if you specify a '-c' option after the verb a context diff will be emitted. '-b' ignores changes in the amount of whitespace, and '-w' ignores all whitespace. "di" is a synonym for "diff". src ls:: List all registered files. src visualize:: Emit a DOT visualization of repository structures. To use this, install the graphviz package and pipe the output to something like "dot -Tpng | display -". "vis" is a synonym for "visualize". 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 file and its master. Refuses to step on existing files or masters. "cp" is a synonym for "copy". src fast-export ['revision-range'] ['file'...]:: Export one or more projects as a Git fast-import stream. For a history originally imported from elsewhere, author and committer identification is gleaned from the RFC-822-style headers inserted into the commit comment by 'fast-import' (if its '-p' option was not used). Otherwise, this information is copied from your Git configuration. src fast-import [-p] ['files'...]:: 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) state. src srcify:: Move a directory from being RCS- or SCCS-managed to being SRC-managed. That is: if the current directory contains an RCS directory, rename it to .src (but leave any SCCS directory in place). Then check out all masters for editing that are not already checked out. src version:: Report the versions of SRC, the underlying Python, and the RCS or SCCS back end. The omission of "src remove" is a deliberate speed bump. If no files are specified, all eligible files are operated on in sequence. == NOISE CONTROL == Silence is golden. When you have selected only one file to operate on, and the command is not a report generator ('status', 'cat', 'log', 'list', 'fast-export', the listing modes of 'tag' and 'branch', 'ls') you will see a reply only if the operation failed. Other commands ('commit', 'checkout', tag creation and deletion) give you a success message per file when operating on multiple files, so you will not be in doubt about which operation succeeded. This behavior can be suppressed with the '-q' option, placed 'before' the subcommand word. If your directory contains a file named ".srcignore", each line that is neither blank nor begins with a "#" is interpreted as an ignore pattern. It is expanded with glob(3), and files in the expansion are omitted from 'src status' - unless the file is named as an argument, of the status command, in which case its status is "I". Thus, for example, a line reading "*.html" will cause all files with an HTML extension to be omitted from the output of "src status", but the output of 'src status *' will list them with status "I". == BACKWARD COMPATIBILITY == SRC history files are (normally) RCS master files. SRC maintains no permanent state other than these files. In order to maintain complete backwards compatibility, one other compromise was made: any commit comment containing a string exactly matching an RCS log delimiter (a long string of "-" characters) will be rejected as malformed. The RCS back end will be automatically selected when there is an _.src_ or _RCS_ subdirectory. If both these directories exist, SRC will operate on _.src_ and preserve the RCS directory; in this case it will be a little extra verbose to leave no doubt about what it is doing. You can explicitly select the RCS back end by making the first command keyword on the src command line be 'rcs'. This should only be necessary when your working directory contains two or more of the subdirectories _.src_, _RCS_, and _SCCS_. If your directory has both a _.src_ and an unrelated _RCS_ directory you can force SRC to work on the RCS directory and ignore _.src_ by giving it the option "-S RCS". By default, history files are kept in a hidden subdirectory named _.src_. But if you have an _RCS_ subdirectory and no _.src_, SRC will quietly operate on the files in the _RCS_ directory in a completely backward-compatible way. == WORKING WITH SCCS == Using SCCS as a back end is also supported, with some limits due to missing features in SCCS implementations: * SCCS tags are an SRC-only extension that won't be visible from SCCS running natively. * All commands relating to tags and branches throw an error in the SCCS back end. * In CSSC SCCS, src cat does not necessarily pipe out binary data correctly. This has been fixed in the SunOS and Schilling versions. * The CSSC SCCS, the exec bit is not propagated between master and workfile. This has been fixed in the SunOS and Schilling versions. * The CSSC and SunOS SCCS backends have a Y2.1K problem that SRC cannot effectively work around and will probably not be fixed. The Schilling version has repaired this. To be on the safe side, do not use the SCCS backend after the year 2067. The SCCS back end will be automatically selected when there is an _SCCS_ subdirectory and no _.src_ or _RCS_ subdirectory. You can explicitly select the SCCS back end by making the first command keyword on the src command line be 'sccs'. This should only be necessary when your working directory contains none or two or more of the subdirectories _.src_, _RCS_, and _SCCS_. Working with SCCS requires an _SCCS_ subdirectory; SRC will quietly create one, if required, then operate on the files in the _SCCS_ directory in a completely backward-compatible way. Fast-import to SCCS is not supported. The SCCS mode is not recommended unless you have a specific need to work with legacy SCCS repositories. Up-converting them to something less Paleolithic (e.g. with sccs2rcs(1) or reposurgeon(1)) would be a better idea; in truth, the SCCS support exists mainly because it's hilarious (for obscure hacker values of 'hilarious'). == DEBUGGING OPTIONS == These will be of interest mainly to developers. They must go before the subcommand. A '-d' (debug) option before the main command word turns on debugging messages. Just one "-d" gives you complete visibility about what commands the back end is running. It can be repeated for higher debugging levels that expose more of src's internal computation. A '-L' option sets a log file to which debug output dould be written Without this option it is written to standard error. A '-S' (sandbox) option can be used to set the repository directory to something other than its default of _.src_. Use "-S RCS" to make src operate on an _RCS_ directory even if there is alraady a _.src_ directory. A '-T' option sets up an artificial clock that ticks once on each revision and fixes the user information to be used in 'fast-export'; It also attributes all commits to "J. Random Hacker". It is for regression testing. == REQUIREMENTS == SRC is written in Python and requires 2.7 or later; it will run under Python 3.x for x > 2. If you wish to use the RCS support (recommended), the RCS tools at version 5.7 or later must be installed and accessible in your $PATH. If you wish to use the SCCS support, some implementation of SCCS must be accessible. GNU's CSSC (Compatibly Stupid Source Control) will work; so will the SunOS and Schilling forks of AT&T SCCS. The rcs-fast-import(1) tool at version 1.3 or later is required to support the 'src fast-import' command. SRC will die gracefully with a useful error message when it fails due to a missing back end. == LIMITATIONS == SRC will unconditionally bail out if a directory named _RCS-save_ exists. This is because in order to be able to use _.src_ when an unrelated _RCS_ subdirectory is also present, SRC has to play a game of three-directory monte. Before doing its work it moves _RCS_ to _RCS-save_, then moves _.src_ to __RCS__; after doing its work it moves _RCS_ to _.src_ and _RCS-save_ to __RCS__. If there is a pre-existing _RCS-save_ this maneuver can't be done. If you trip over such a pre-exiting __RCS-save__, this probanly means SRC previously underwent a hard crash and you will have to resuffle these directories by hand. No bug that can produce duch a crash has yet been reported. The directory shuffle also means that running more than one SRC edit session on the same directory at the same time may produce mysterious failures. Don't do this - it is way outside the tool's intended performance envelope. Branch deletions change the revision numbers of revisions downstream of the branch join. In src fast-export dumps of repositories with tags, branch labels may not exactly match what git fast-export would emit. In both RCS and SCCS revision numbers normally looked like "1.n" for n starting at 1 and monotonically increasing. It was possible to check in a change with a higher release number (for example, "2.1"), though this was seldom done. If you use SRC to view or edit an ancient master that used this feature, commands using ranges and named branches will not always work as exoected. == REPORTING BUGS == Report bugs to Eric S. Raymond . The project page is at http://catb.org/~esr/src == SEE ALSO == rcs(1), rcs-fast-import(1), sccs(1), svn(1), hg(1), git(1), dot(1), sccs2rcs. // end src-1.33/srctest0000775000175000017500000017343014544356441012034 0ustar esresr#!/bin/sh # SPDX-FileCopyrightText: Copyright Eric S. Raymond # SPDX-License-Identifier: BSD-2-Clause # # Regression tester for SRC. # # Emits messages in TAP (Test Anything Protocol). # # Use -b to test with a specified back end, rcs or sccs # Use -e to test with an alternate src version # Use -l to set a log-redirect option on src while tests are running # Use -p to test with a specified Python interpreter, python2 or python3 # Use -t to put test files and masters at a fixed location, not removing on exit # Use -c to do coverage analysis; the argument is the coverage data filename # # If the -b and -n options are not forced, all combinations # are tested sequentially. historify () { case $backend in rcs) history=.src/$1,v ;; sccs) history=SCCS/s.$1 ;; *) echo "srctest: unsupported backend $backend" esac } nuke() { rm -f "$1" ".src/$1,v" "RCS/$1,v" "SCCS/s.$1" } fresh_start() { rm -f .src/* RCS/* SCCS/* } # No dependencies on master name formats after this like # Set the umask for a bit of defensiveness umask 0077 # Set the PATH to include the current directory, so the repository # head version of src can always be tested. PATH="$(pwd)":$PATH backend="" python="" testmode=no testcount=1 passed="" logfile="" expect_empty="-e" while getopts :b:c:e:l:p:t opt do case $opt in b) backend=$OPTARG;; c) coverage erase; src="coverage run -a --data-file=$(pwd)/$OPTARG $(pwd)/src" logfile=/dev/null passed="-L /dev/null -d -d -d -d" expect_empty="" ;; e) src=$OPTARG;; l) logfile="$(pwd)/$OPTARG"; echo "# Start $(date):" >"${logfile}";; p) python=$OPTARG;; t) testmode=yes;; *) echo "srctest: unknown option"; exit 1;; esac done # shellcheck disable=SC2004 shift $(($OPTIND - 1)) $backend >/dev/null 2>&1 if [ "$?" = 127 ] then echo "not ok ${testcount} - backend ${backend} is missing." testcount=$((testcount + 1)) exit 1 fi if [ -z "$src" ] then src="${python} ${PWD}/src" fi # Generic TAP functions begin here # The tap* functions are a mini-framework for controlled execution of # CLI tests. They ship reports in TAP format to stdout. If the # variable $logfile is set, they will also append stanza headers to # the specified logfile. # # The point of these functions is twfold: to give us TAP logging of # test outcomes to standard output, and so that any debug logging # produced by the tool running under taptest/tapdiff control appears # *after* a stanza header identifying the test. # # They are intended to be used in a particular pattern so they will # produce useful stanzas in the logfile. First, call one of the # primary functions that generates a new section - taplog, taptest, or # tapdiff. Then call tapgrep and tapcheck to run as many auxiliary # tests as you would like. # # The test group labels aren't used yet (except for being reported in # the test log if $logfile is set). In the future they may be used to # allow running only subspans of an entire test sequence. Don't # assume that the existence of generated test files soans the # boundaries defined by a change in group label. # If you want to change where command captures and diffs live, modifying # this variable will do it. tap_capture="/tmp/tap$$" # Set this to add a fixed preamble to every TAP message tap_preamble="" # Options to pass diff. tap_diffopts="--label Expected --label Actual -u" # Start a new log stanza. First argument is the group label, second is the # legend that later functions should use to report success or failure. taplog() { label="$1" legend="$2" if [ "${logfile}" ] then echo "# ${label} ${tap_preamble}${legend}" >>"${logfile}" fi } # Produce a TAP line from the return status of the last command # executed. Does not start a new log stanza. First argument is the # group label. Second is the command return status to dispatch on, 0 # for success and any other value for failure. Third is the legend # that later functions should use to report success or failure. # Fourth, if given, is the name of a capture of the command's stdout # and stderr. # # If the command return is nonzero, the captured output has been # passed, and the size of the capture is nonzero, the diff is dumped # as a YAML attachment conforming to TAP. Beginning the command with "!" # allows an expected failure status to be processed returning success. # # The -d option forces the capture to be dumped even on command success. # The -e option reports failure if the capture is nonempty. tapcheck() { debug="no" need_empty="" while getopts :de opt do case $opt in d) debug=yes;; e) need_empty="-e";; *) echo "not ok ${testcount} - unknown option in tapcheck"; exit 1;; esac done # shellcheck disable=SC2004 shift $(($OPTIND - 1)) label="$1" status="$2" legend="$3" outfile="$4" case "${status}" in 0) ;; *) echo "not ok ${testcount} - ${tap_preamble}${legend} failed"; if [ -n "${outfile}" ] then echo " --- |" echo " Return status ${status}" sed <"${outfile}" -e 's/^/ /' echo " ..." fi exit 1 ;; esac if [ "${need_empty}" = "-e" ] && [ -n "${outfile}" ] && [ -s "${outfile}" ] then echo "not ok ${testcount} - ${tap_preamble}${legend} had unexpected nonempty output."; echo " --- |" echo " Return status ${status}" sed <"${outfile}" -e 's/^/ /' echo " ..." exit 1 fi echo "ok ${testcount} - ${tap_preamble}${legend} succeeded" if [ "${debug}" = "yes" ] && [ -n "${outfile}" ] && [ -s "${outfile}" ] then echo " --- |" echo " Return status ${status}" sed <"${outfile}" -e 's/^/ /' echo " ..." fi testcount=$((testcount + 1)) } # Run a command with stdout and stderr capture. Starts a new log # stanza. First argument is the group label. Second is the legend that # later functions should use to report success or failure. # # All later arguments are treated as a shell command to be executed, # with standard output and standard error captured as # ${tap_capture}out. The command is deemed to succeed if its return status # is 0 and to fail otherwise; if it fails, the capture is dumped as a # YAML attachment conforming to TAP. Beginning the command with "!" # allows an expected failure status to be processed returning success. # # WARNING: Strings in taptest command lines have to be quoted twice; # one layer is stripped off by normal shell expansion, the second # removed by the eval this function uses internally. # # The -d option forces that capture to be dumped even on command success. # The -e option reports failure if the capture is nonempty. taptest() { debug="" need_empty="" while getopts :de opt do case $opt in d) debug="-d";; e) need_empty="-e";; *) echo "not ok ${testcount} - unknown option in taptest"; exit 1;; esac done # shellcheck disable=SC2004 shift $(($OPTIND - 1)) label="$1" legend="$2" shift shift taplog "${label}" "${legend}" # shellcheck disable=SC2086,SC2048 eval $* >${tap_capture}out 2>&1 # shellcheck disable=SC2086 tapcheck ${debug} ${need_empty} internal $? "${legend}" "${tap_capture}out" } # Run a command, diffing the output against a specified checkfile. # Starts a new log stanza. First argument is the group label. # Second argument is the checkfile of expected output; if # the actual output differs, the difference is dumped as a YAML # attachment conforming to TAP. Third argument is the legend to be # used in reporting success or failure. # # All later arguments are treated as a shell command to be executed, # with standard output and standard error captured as # ${tap_capture}out. The command is deemed to succeed the diff bwtween the # capture and the checkfile is empty and to fail otherwise; if it # fails, the diff is dumped as a YAML attachment conforming to TAP. # # WARNING: Strings in tapdiff command lines have to be quoted twice; # one layer is stripped off by normal shell expansion, the second # removed by the eval this functions uses internally. # # With the -f option, pass the command output through the specified # filter before diffing. tapdiff () { filter="cat" if [ "$1" = "-f" ] then filter="$2" shift shift fi label="$1" checkfile="$2" legend="$3" shift shift shift taplog "${label}" "${legend}" # shellcheck disable=SC2086,SC2048 eval $* >${tap_capture}out 2>&1 case $? in 0) ;; *) echo "not ok ${testcount} - ${tap_preamble}${legend} command failed"; echo " --- |" sed <"${tap_capture}out" -e 's/^/ /' echo " ..." exit 1 ;; esac # shellcheck disable=SC2086 diff ${tap_diffopts} "${checkfile}" ${tap_capture}out | ${filter} >${tap_capture}diff if [ ! -s ${tap_capture}diff ] then echo "ok ${testcount} - ${tap_preamble}${legend} diff succeeded" else echo "not ok ${testcount} - ${tap_preamble}${legend} diff failed" echo " --- |" sed <"${tap_capture}diff" -e 's/^/ /' echo " ..." exit 1 fi testcount=$((testcount + 1)) } # Given a test file and a checkfile, verify that they compare binary equal. # Relies on cmp(1) to always ship a textual non-zero-length complain if they # do not. This is a separate function because doing the obvious way would # clobber ${tap_capture}out just before it's needed for the check. tapcmp () { label="$1" testfile="$2" checkfile="$3" legend="$4" taplog "${label}" "${legend}" # shellcheck disable=SC2086 cmp "${testfile}" "${checkfile}" >${tap_capture}diff 2>&1 tapcheck internal "$?" "${legend}" } # Grep for a pattern in the stashed output of the last taptest command. # First argument is group label, second is the string to grep for, third # is the legend to be used in reporting success or failure. tapgrep() { if [ "$#" != 3 ] then echo "Bail out! # tapgrep requires exactly three arguments." exit 1; fi label="$1" lookfor="$2" legend="$3" grep "$lookfor" ${tap_capture}out >/dev/null 2>&1 tapcheck internal "$?" "${legend}" } # Wmit a TAP comment. We don't sihp an OK line here because it # doesn't count as a passed test. tapcomment() { shift # Skip the label argument echo "# $*" if [ -n "${logfile}" ] then echo "# $*" >>"${logfile}" fi } # Clean up tempfiles created by the tap functions. tapclean() { if [ -z "${tap_capture}" ] then echo "not ok ${testcount} - ${tap_preamble}cleanup deletion suppressed." exit 1 else rm -f ${tap_capture}* fi testcount=$((testcount + 1)) } # Generic TAP functions end here if [ $testmode = yes ] then SANDBOX=/tmp/srctest echo "# Test files and masters will not be removed on exit." rm -fr $SANDBOX else # Needs to not be a subdirectory of here, or git gets confused. Use # -u so that src's initialization will be tested. SANDBOX=$(mktemp -u /tmp/src_XXXXXXXX) trap 'rm -fr $SANDBOX; tapclean' EXIT HUP INT QUIT TERM fi if [ ! -d "$SANDBOX" ] then mkdir "$SANDBOX" || { echo "Bail out! # scratch directory creation of $SANDBOX failed"; exit 1; } fi if [ "$SANDBOX" = "" ] then testcount=$((testcount + 1)) echo "Bail out! srctest refuses to destroy the world." fi cd "$SANDBOX" || (echo "srctest: sandbox it missing"; exit 1) rm -fr -- * COLUMNS=73 export COLUMNS # Set an editor that does nothing, noy modifimg its argument file. We # do this to avoid making the eecution path through the edit-function # code dependent on what well-known editors are in the user's $PATH. EDITOR=: export EDITOR # Test sequence begins here # shellcheck disable=SC2120 test_backend() { TESTOPTS="$passed $backend" tap_preamble="($python $backend): " # shellcheck disable=SC2086 mkdir ${python}-${backend} # shellcheck disable=SC2086 cd ${python}-${backend} >/dev/null || ( echo "Bail out! Sandbox subdirectory creation failed"; exit 1 ) # No repo directory yet. Test those error cases first # shellcheck disable=SC2086 taptest repoless "reject list with missing repo directory" ! $src -T ${TESTOPTS} list tapgrep repoless "does not exist" "list with missing repo message check" # shellcheck disable=SC2086 taptest repoless "reject srcify with repo directory." ! $src -q -T ${TESTOPTS} srcify # shellcheck disable=SC2086 taptest repoless "version" $src -T ${TESTOPTS} version tapgrep repoless "python" "sane version output" # shellcheck disable=SC2086 taptest repoless "reject ls without repo directory" ! $src -T ${TESTOPTS} ls # shellcheck disable=SC2086 taptest repoless "reject visualize without repo directory" ! $src -T ${TESTOPTS} visualize # shellcheck disable=SC2086 taptest repoless "empty command line not blowing up" $src -T ${TESTOPTS} # shellcheck disable=SC2086 taptest repoless "commit help lookup" $src -T ${TESTOPTS} help commit # shellcheck disable=SC2086 taptest repoless "error exit on unknown command" ! $src -T ${TESTOPTS} foozle # shellcheck disable=SC2086 taptest repoless "error exit on help for unknown command" ! $src -T ${TESTOPTS} help foozle # shellcheck disable=SC2086 taptest repoless "init unexpectedly" $src -T ${TESTOPTS} init # No-directory tests end here cat >testfile1 <testfile1 <testfile4 </tmp/tap$$in # shellcheck disable=SC2086 taptest ${expect_empty} workflow "commit with -" $src -T ${TESTOPTS} commit - testfile1 testfile2 <testfile2 <testfile2 <testfile1 <testfile4 <testfile4 <testfile14 <testfile15 <testfile6 <testfile8 <testfile10 <testfile12 <"$srcfi" # Side effect - file is used later # shellcheck disable=SC2002 cat "$srcfi" | (cd foo >/dev/null || ("echo missing foo directory" ;exit 1); git init --quiet; git fast-import --quiet) (cd foo >/dev/null || ("echo missing foo directory"; exit 1); git fast-export --all) | grep -v '^#' >"$gitfi" tapdiff workfile "$srcfi" "fast-export roundtrip: $testname" cat "$gitfi" rm -fr foo } # Without this copy, the rcs-fast-import test would modify testf1le1 under # the RCS nackend but not the SCCS one. # shellcheck disable=SC2086 taptest ${expect_empty} workflow "copying testfile1" $src -T ${TESTOPTS} copy testfile1 exportme test_export filename exportme # Test multiple-file fast-export. echo flower power >testfile14 # shellcheck disable=SC2086 taptest workflow "it's a Mad world" $src -T ${TESTOPTS} commit -m "'Alfred E. Newman'" testfile14 test_export filenames exportme testfile14 historify testfile14 rm -f "$history" test_export revspec-filename -- exportme taplog workfile "fast-export revspec/filename distinction" grep refs/heads/master revspec-filename-src.fi >/dev/null && ! grep refs/heads/exportme/master revspec-filename-src.fi >/dev/null tapcheck workfile "$?" "${legend}" rm -f exportme test_export not-checked-out exportme tapcheck workfile "$?" "fast-export consults history only" # shellcheck disable=SC2086 taptest workfklow "checkout after fast-export" $src -T ${TESTOPTS} checkout exportme if [ "$backend" = "sccs" ] then tapcomment workflow "($python $backend): skipping fast-import checks: RCS-only" elif ! command -v rcs-fast-import >/dev/null 2>&1 then tapcomment workflow "($python $backend): skipping fast-import checks: rcs-fast-import missing" else mkdir RCS # shellcheck disable=SC2086 taptest workflow "fast-import don't clobber RCS" ! $src -T ${TESTOPTS} fast-import -p reheadered # shellcheck disable=SC2086 tapdiff workflow reheadered "fast-import roundtrip (export)" $src -T ${TESTOPTS} fast-export exportme fi nuke exportme # shellcheck disable=SC2086 taptest badmove "rejection of move with bad source" ! $src -T ${TESTOPTS} move foo bar tapgrep badmove "I see no" "move rejection message check" # shellcheck disable=SC2086 taptest workflow "move command" $src -T ${TESTOPTS} move testfile1 newname1 historify newname1 # shellcheck disable=SC2086 taptest workflow "move target location check" [ -e newname1 ] && [ -e "$history" ] newname1_master="${history}" historify newname2 newname2_master="${history}" # shellcheck disable=SC2086 taptest workflow "copy command" $src -T ${TESTOPTS} copy newname1 newname2 taptest workflow "copy source and target location check" [ -e newname1 ] && [ -e newname2 ] && [ -e "${newname1_master}" ] && [ -e "${newname2_master}" ] cat >manifest <statuslog <.srcignore echo "newname1" >>.srcignore cat >statuslog <diffall.expect <>newname1 echo "and even more" >>newname2 # shellcheck disable=SC2086 tapdiff workflow diffall.expect "expected diff after modify" $src -T ${TESTOPTS} diff # shellcheck disable=SC2086 taptest workflow "checkout after modification" $src -T ${TESTOPTS} checkout newname1 newname2 cat >limit.list <limit.log <statdummy <>statdummy # shellcheck disable=SC2086 taptest teststatus "status fetch expecting M" $src -T ${TESTOPTS} status statdummy tapgrep teststatus "^M" "M status check after modification" rm statdummy # shellcheck disable=SC2086 taptest teststatus "status fetch expecting !" $src -T ${TESTOPTS} status statdummy tapgrep teststatus "^!" "! status check after deletion" # shellcheck disable=SC2086 taptest teststatus "reversion" $src -T ${TESTOPTS} checkout statdummy # shellcheck disable=SC2086 taptest teststatus "status fetch expecting = (reversiom)" $src -T ${TESTOPTS} status statdummy tapgrep teststatus "^=" "= status check after restoration" historify statdummy rm -f "$history" # shellcheck disable=SC2086 taptest teststatus "status fetch expecting ?" $src -T ${TESTOPTS} status statdummy tapgrep teststatus "^?" "? status check after master deletion" # Get a fresh start - enforcing bounday between test groups fresh_start if [ "$backend" = "sccs" ] then tapcomment branchy "($python $backend): skipping branch tests" else # Test branch creation echo "Base content" >branchfoo # shellcheck disable=SC2086 taptest branchy "branch test start commit " $src -T ${TESTOPTS} ci -m "'Start a file with branches'" branchfoo cat >testfile18 <testfile19 <branchfoo # shellcheck disable=SC2086 taptest branchy "branch checkin" $src -T ${TESTOPTS} ci -m "'checkin on the branch'" branchfoo cat >testfile20 <branchfoo # shellcheck disable=SC2086 taptest branchy "reject checkin on nonexistent branch" ! $src -d -T ${TESTOPTS} ci -b boggle -m "'Alter content on trunk'" branchfoo # shellcheck disable=SC2086 tapgrep branchy "can't switch to nonexistent branch" "nonexistent-branch message check" # shellcheck disable=SC2086 taptest branchy "altering content on trunk" $src -T ${TESTOPTS} ci -b trunk -m "'Alter content on trunk'" branchfoo cat >testfile21 <.src/sample,v <sampledot <1First comment.>]; 1 -> 2; 2 [shape=box,width=5,label=<
2Second comment.
>]; 2 -> 3; 3 [shape=box,width=5,label=<
3Third comment.
>]; 3 -> 4; 4 [shape=box,width=5,label=<
4On a branch?
>]; "trunk" [shape=oval,width=2]; "4" -> "trunk" [style=dotted]; 3 -> 5; 5 [shape=box,width=5,label=<
5Totally unfubared.
>]; 5 -> 6; 6 [shape=box,width=5,label=<
6Still utterly fubar
>]; 6 -> 7; 7 [shape=box,width=5,label=<
7Totally chenille.
>]; 7 -> 8; 8 [shape=box,width=5,label=<
8Utterly fubar
>]; "muggle" [shape=oval,width=2]; "8" -> "muggle" [style=dotted]; 8 -> 9; 9 [shape=box,width=5,label=<
9All fixed up.
>]; 9 -> 10; 10 [shape=box,width=5,label=<
10It' all good.
>]; 10 -> 11; 11 [shape=box,width=5,label=<
11No good.
>]; 11 -> 12; 12 [shape=box,width=5,label=<
12That's good.
>]; 12 -> 13; 13 [shape=box,width=5,label=<
13I see you
>]; "wibble" [shape=oval,width=2]; "13" -> "wibble" [style=dotted]; {rank=same; "GLARB"; "4"} "GLARB" -> "4" [style=dotted]; {rank=same; "GORP"; "8"} "GORP" -> "8" [style=dotted]; } EOF # shellcheck disable=SC2086 tapdiff branchy sampledot "dot visualization" $src -T ${TESTOPTS} visualize sample cat >sample.seqlog <sample.branchlog <sample.branchlog-p <sample.taglog <changes <branchlist <branchlog <newlist <newlog <newlist <newlist <newlist <23 # shellcheck disable=SC2086 taptest numeric "commit of file with numeric name" $src -T ${TESTOPTS} commit -m "'I do not know why you say goodbye'" -- 23 cat >randomcontent <exectest # shellcheck disable=SC2086 taptest exec "first commit of exectest" $src -T ${TESTOPTS} commit -m "'First comment on exectest'" exectest chmod a+x exectest echo "Should be executable" >exectest # shellcheck disable=SC2086 taptest exec "second commit of exectest" $src -T ${TESTOPTS} commit -m "'Second comment on exectest'" exectest # shellcheck disable=SC2010 taptest exec "propagation of exec bit" test -x exectest fi # Get a fresh start - enforcing bounday between test groups fresh_start # Test for Tom Willemse's multi-commit bug. echo "test 1" > file1 echo "test 2" > file2 # shellcheck disable=SC2086 taptest multifile "multi-file registration" $src -T ${TESTOPTS} commit -m "'Initial commit'" file1 file2 echo "test 1 line 2" >> file1 echo "test 2 line 2" >> file2 # shellcheck disable=SC2086 taptest multifile "multi-file commit" $src -T ${TESTOPTS} commit -m "'Second commit'" file1 file2 # Test the edit logic cat >modify <<'EOF' echo "Different first line" >modified$$ cat $1 >>modified$$ mv modified$$ $1 EOF chmod a+x modify echo "test 1 line 3" >> file1 # shellcheck disable=SC2086 EDITOR="./modify" taptest edit "edit logic" $src -T ${TESTOPTS} commit file1 # Get a fresh start - enforcing bounday between test groups fresh_start cat >binary <binary.chk <>binary # shellcheck disable=SC2086 taptest binary "binary file modification" $src -T ${TESTOPTS} commit -m "'Binary file after modification.'" binary tapcmp binary binary binary.chk "binary content in checkouts and commits" if [ "$backend" = "sccs" ] then tapcomment binary "($python $backend): skipping binary cat test" else # shellcheck disable=SC2086 taptest binary "binary cat" $src -T ${TESTOPTS} cat binary tapcmp binary binary ${tap_capture}out "binary content in cat" fi cat >newline <newline.chk <>newline # shellcheck disable=SC2086 taptest newline "modify newline file" $src -T ${TESTOPTS} commit -m "'DOS newline file after modification.'" newline tapcmp newline newline newline.chk "newline preservation in checkouts and commits" if [ "$backend" = "sccs" ] then tapcomment newline "($python $backend): skipping newline cat test" else # shellcheck disable=SC2086 taptest newline "newline file checkin" $src -T ${TESTOPTS} cat newline tapcmp newline ${tap_capture}out newline "newline content in cat" fi # Get a fresh start - enforcing bounday between test groups fresh_start cat >padcomment <<'EOF' printf "\n\n\n\n" >modified$$ cat $1 >>modified$$ mv modified$$ $1 EOF chmod a+x padcomment echo gommelgor >padfile # shellcheck disable=SC2086 taptest padfile "padfile commit" $src -T ${TESTOPTS} commit -m pingle padfile for i in commit amend do echo "more stuff" >>padfile # shellcheck disable=SC2086 EDITOR="./padcomment" taptest padfile "edit padfile" $src -T ${TESTOPTS} $i padfile tapgrep padfile cancelled "whitespace-only $i cancel" # shellcheck disable=SC2086 taptest padfile "padfile $i" $src -T ${TESTOPTS} checkout padfile done # Get a fresh start - enforcing bounday between test groups fresh_start cat >clonemsg <<'EOF' echo "I think I'm a clone now" >modified$$ cat $1 >>modified$$ mv modified$$ $1 cp $1 clonedmsg EOF chmod a+x clonemsg echo gommelgor >diffledore # shellcheck disable=SC2086 taptest amend "initial diffledore commit" $src -T ${TESTOPTS} commit -m pingle diffledore for i in commit amend do test $i = commit && echo "more stuff" >>diffledore # shellcheck disable=SC2086 EDITOR="./clonemsg" taptest ignore "diffledore modification" $src -T ${TESTOPTS} $i diffledore grep -F -e 'Changes to be committed' clonedmsg >/dev/null && grep -F -e '@@ ' clonedmsg >/dev/null && grep -F -e '+++ ' clonedmsg >/dev/null && grep -F -e '--- ' clonedmsg >/dev/null tapcheck amend "$?" "$i diff in boilerplate" done # Get a fresh start - enforcing bounday between test groups fresh_start cat >dontinvoke <<'EOF' echo "panic!" >>nochanges EOF chmod a+x dontinvoke echo "bingleby" >canttouchthis # shellcheck disable=SC2086 taptest nochanges "canttouchthis commit" $src -T ${TESTOPTS} commit -m pingle canttouchthis # shellcheck disable=SC2086 EDITOR="./dontinvoke" taptest ignore "canttouchtos second commit" $src -T ${TESTOPTS} commit canttouchthis grep 'no changes to commit' ${tap_capture}out >/dev/null && ! grep panic ${tap_capture}out >/dev/null tapcheck nochanges "$?" "nothing to commit" cat >ignore.ws <ignore.ws <ignore.expect-b <ignore.expect-w <.src/tiebreak,v < Author-Date: Mon 20 Nov 2017 21:37:42 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :22 Parents: :20 eleventh @ text @eleventh @ 1.10 log @Author: Eric Sunshine Author-Date: Mon 20 Nov 2017 21:30:40 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :20 Parents: :18 tenth @ text @d1 1 a1 1 tenth @ 1.9 log @Author: Eric Sunshine Author-Date: Mon 20 Nov 2017 21:27:29 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :18 Parents: :16 ninth @ text @d1 1 a1 1 ninth @ 1.8 log @Author: Eric Sunshine Author-Date: Mon 20 Nov 2017 21:25:22 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :16 Parents: :14 eighth @ text @d1 1 a1 1 eighth @ 1.7 log @Author: Eric Sunshine Author-Date: Mon 20 Nov 2017 23:02:46 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :14 Parents: :12 seventh @ text @d1 1 a1 1 seventh @ 1.6 log @Author: Eric Sunshine Author-Date: Mon 20 Nov 2017 22:56:46 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :12 Parents: :10 sixth @ text @d1 1 a1 1 sixth @ 1.5 log @Author: Eric Sunshine Author-Date: Fri 03 Nov 2017 13:30:17 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :10 Parents: :8 fifth @ text @d1 1 a1 1 fifth @ 1.4 log @Author: Eric Sunshine Author-Date: Fri 03 Nov 2017 13:28:35 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :8 Parents: :6 fourth @ text @d1 1 a1 1 fourth @ 1.3 log @Author: Eric Sunshine Author-Date: Fri 03 Nov 2017 13:26:41 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :6 Parents: :4 third @ text @d1 1 a1 1 third @ 1.2 log @Author: Eric Sunshine Author-Date: Fri 03 Nov 2017 13:25:01 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :4 Parents: :2 second @ text @d1 1 a1 1 second @ 1.1 log @Author: Eric Sunshine Author-Date: Fri 03 Nov 2017 13:12:48 -0500 Committer: Roy G. Biv Committer-Date: Tue 21 Nov 2017 01:45:15 +0000 Mark: :2 first @ text @d1 1 a1 1 first @ EOF cat >tiebreak.expect <noheaders.expect <logheaders.expect < Author-Date: 2017-11-21T02:37:42Z Author-Date-Offset: -18000 Committer: Roy G. Biv Committer-Date: 2017-11-21T01:45:15Z Committer-Date-Offset: 0 Mark: :22 Parents: :20 eleventh ------------------------------------------------------------------------ 10 | 1970-01-02T00:09:00Z | trunk Author: Eric Sunshine Author-Date: 2017-11-21T02:30:40Z Author-Date-Offset: -18000 Committer: Roy G. Biv Committer-Date: 2017-11-21T01:45:15Z Committer-Date-Offset: 0 Mark: :20 Parents: :18 tenth ------------------------------------------------------------------------ EOF # shellcheck disable=SC2086 tapdiff tiebreak logheaders.expect "log -v -v shows all headers" $src -T ${TESTOPTS} log -v -v -2 tiebreak cat >summaryheaders.expect < 2017-11-21T02:37:42Z Committer: Roy G. Biv 2017-11-21T01:45:15Z eleventh ------------------------------------------------------------------------ 10 | 1970-01-02T00:09:00Z | trunk Author: Eric Sunshine 2017-11-21T02:30:40Z Committer: Roy G. Biv 2017-11-21T01:45:15Z tenth ------------------------------------------------------------------------ EOF # shellcheck disable=SC2086 tapdiff tiebreak summaryheaders.expect "log -v shows summarized headers" $src -T ${TESTOPTS} log -v -2 tiebreak cat >authordate1.expect <authordate2.expect < 1509732768 -0500" "fast-export: consult RFC 822 headers (author)" tapgrep tiebreak "committer Roy G. Biv 1511228715 +0000" "fast-export: consult RFC 822 headers (committer)" fi fi # Now for the srcify test rm -fr .src RCS SCCS cat >srcifyfile </dev/null fi historify srcifyfile # shellcheck disable=SC2086 taptest srcify "srcify command" $src -T ${TESTOPTS} srcify test -f "$history" tapcheck srcify "$?" "srcify created master" test -f srcifyfile tapcheck srcify "$?" "srcify left the workfile in place" # Check a parsing case brought up by GitLab issue #21: Filenames including '-' are interpreted as revision ranges touch a-b # shellcheck disable=SC2086 taptest dashparse "checkin of file named with embedded dash" $src -T ${TESTOPTS} ci -m "Initial" -- a-b historify a-b test -f "$history" tapcheck dashparse "$?" "commit of filename resembling a revision renge" # Test deep operations mkdir inner echo one >inner/sample # shellcheck disable=SC2086 taptest deep "commit of deep file" $src -T ${TESTOPTS} commit -m "'Early trunk content'" inner/sample # shellcheck disable=SC2086 taptest deep "cat of deep file" $src -T ${TESTOPTS} cat inner/sample tapcmp deep inner/sample "${tap_capture}out" "binary cat returned correct data" # Test multidirectory operation if [ "$backend" = "rcs" ] then mkdir RCS-save # shellcheck disable=SC2086 taptest multidir "correctly bailing out on existing RCS-save" ! $src -T ${TESTOPTS} log rmdir RCS-save mkdir RCS echo "RCS mark" >RCS/rcsmark echo "tweedledum" >tweedledum echo "tweedledee" >tweedledee # shellcheck disable=SC2086 taptest multidir "multidirectory checkin to .src" $src -q -T ${TESTOPTS} ci -m "helter" tweedledum test -f .src/tweedledum,v tapcheck multidir "$?" "master location check after multidirectory checkin" ! test -f .src/tweedledum tapcheck multidir "$?" "content location check after multidirectory checkin" test -f RCS/rcsmark tapcheck multidir "$?" "RCS restoration check after multidirectory shuffle" ! test -f RCS-save tapcheck multidir "$?" "no exiguous save directory after shuffle" # shellcheck disable=SC2086 taptest multidir "multidir checkin with -S RCS" $src -S RCS -T ${TESTOPTS} ci -m "skelter" tweedledee # shellcheck disable=SC2086 taptest multidir "multidir tag creation" $src -T ${TESTOPTS} tag -c fimbulwinter tweedledum # shellcheck disable=SC2086 taptest multidir "multidir tag rename" $src -T ${TESTOPTS} rename tag fimbulwinter niflheim -- tweedledum cat >tweedledee.expected <tweedledee.expected < # # This code is intended to be embedded in your project. The author # grants permission for it to be distributed under the prevailing # license of your project if you choose, provided that license is # OSD-compliant; otherwise the following SPDX tag applies. # # SPDX-License-Identifier: BSD-2-Clause # # This is version 1.0 # A newer version may be available at https://gitlab.com/esr/tapview # # POSIX allows but does not mandate that -n suppresses emission of a # trailing newline in echo. Thus, some shell builtin echos don't do # that. Cope gracefully. # shellcheck disable=SC2039 if [ "$(echo -n "a"; echo "b")" != "ab" ] then ECHO="echo" elif [ "$(/bin/echo -n "a"; /bin/echo "b")" = "ab" ] then ECHO="/bin/echo" else echo "tapview: bailing out, your echo lacks -n support." exit 3 fi OK="." FAIL="F" SKIP="s" TODO_NOT_OK="x" TODO_OK="u" ship_char() { # shellcheck disable=SC2039 "${ECHO}" -n "$1" } ship_line() { report="${report}${1}\n" } testcount=0 failcount=0 skipcount=0 todocount=0 test_before_plan=no test_after_plan=no expect="" status=0 report="" IFS="" state=start while read -r line do if expr "$line" : "Bail out!" >/dev/null then ship_line "$line" status=2 break fi if expr "$line" : '1\.\.[0-9][0-9]*' >/dev/null >/dev/null then if [ "$expect" != "" ] then if [ "${testcount}" -gt 0 ] then echo "" fi ship_line "Cannot have more than one plan line." echo "${report}" exit 1 fi if expr "$line" : ".* *SKIP" >/dev/null || expr "$line" : ".* *skip" >/dev/null then ship_line "$line" echo "${report}" exit 1 # Not specified in the standard whether this should exit 1 or 0 fi expect=$(expr "$line" : '1\.\.\([0-9][0-9]*\)') continue fi if expr "$line" : "ok" >/dev/null then testcount=$((testcount + 1)) if [ "$expect" = "" ] then test_before_plan=yes else test_after_plan=yes fi if expr "$line" : ".*# *TODO" >/dev/null || expr "$line" : ".*# *todo" >/dev/null then ship_char ${TODO_OK} ship_line "$line" todocount=$((todocount + 1)) elif expr "$line" : ".*# *SKIP" >/dev/null || expr "$line" : ".*# *skip" >/dev/null then ship_char ${SKIP} ship_line "$line" skipcount=$((skipcount + 1)) else ship_char ${OK} fi state=ok continue fi if expr "$line" : "not ok" >/dev/null then testcount=$((testcount + 1)) if [ "$expect" = "" ] then test_before_plan=yes else test_after_plan=yes fi if expr "$line" : ".*# *SKIP" >/dev/null || expr "$line" : ".*# *skip" >/dev/null then ship_char "${SKIP}" state=ok skipcount=$((skipcount + 1)) continue fi if expr "$line" : ".*# *TODO" >/dev/null || expr "$line" : ".*# *todo" >/dev/null then ship_char ${TODO_NOT_OK} state=ok todocount=$((todocount + 1)) continue fi ship_char "${FAIL}" ship_line "$line" state=not_ok failcount=$((failcount + 1)) status=1 continue fi # shellcheck disable=SC2166 if [ "${state}" = "yaml" ] then ship_line "$line" if expr "$line" : '[ ]*\.\.\.' >/dev/null then state=ok fi elif expr "$line" : "[ ]*---" >/dev/null then ship_line "$line" state=yaml fi done /bin/echo "" if [ -z "$expect" ] then ship_line "Missing a plan." status=1 elif [ "$test_before_plan" = "yes" ] && [ "$test_after_plan" = "yes" ] then ship_line "A plan line may only be placed before or after all tests." status=1 elif [ "${expect}" -gt "${testcount}" ] then ship_line "Expected ${expect} tests but only ${testcount} ran." status=1 elif [ "${expect}" -lt "${testcount}" ] then ship_line "Expected ${expect} tests but ${testcount} ran." status=1 fi report="${report}${testcount} tests, ${failcount} failures" if [ "$todocount" != 0 ] then report="${report}, ${todocount} TODOs" fi if [ "$skipcount" != 0 ] then report="${report}, ${skipcount} SKIPs" fi echo "${report}." exit "${status}" # end src-1.33/TODO.adoc0000664000175000017500000000066714544356237012020 0ustar esresr= SRC TODO list // SPDX-FileCopyrightText: Copyright Eric S. Raymond // SPDX-License-Identifier: CC-BY-4.0 * Eliminate 'L' status, turning it to '=' and automatically checking out the file when required. * Full branch support in the SCCS back end, now that we know it's possible. * Uncommit operation using sccs rmdel and rcs -o; leave the workfile unaltered but delete the latest revision on the current branch.