2 * Copyright (C) 1986-2005 The Free Software Foundation, Inc.
4 * Portions Copyright (C) 1998-2005 Derek Price, Ximbiot <http://ximbiot.com>,
7 * Portions Copyright (C) 1992, Brian Berliner and Jeff Polk
8 * Portions Copyright (C) 1989-1992, Brian Berliner
10 * You may distribute under the terms of the GNU General Public License as
11 * specified in the README file that comes with the CVS source distribution.
13 * The routines contained in this file do all the rcs file parsing and
21 /* These need to be source after cvs.h or HAVE_MMAP won't be set... */
23 # include "getpagesize.h"
24 # include <sys/mman.h>
26 /* Define MAP_FILE when it isn't otherwise. */
30 /* Define MAP_FAILED for old systems which neglect to. */
32 # define MAP_FAILED ((void *)-1)
36 /* The RCS -k options, and a set of enums that must match the array.
37 These come first so that we can use enum kflag in function
39 static const char *const kflags[] =
40 {"kv", "kvl", "k", "v", "o", "b", NULL};
41 enum kflag { KFLAG_KV = 0, KFLAG_KVL, KFLAG_K, KFLAG_V, KFLAG_O, KFLAG_B };
43 /* A structure we use to buffer the contents of an RCS file. The
44 various fields are only referenced directly by the rcsbuf_*
45 functions. We declare the struct here so that we can allocate it
46 on the stack, rather than in memory. */
50 /* Points to the current position in the buffer. */
52 /* Points just after the last valid character in the buffer. */
56 /* The name of the file, used for error messages. */
58 /* The starting file position of the data in the buffer. */
60 /* The length of the value. */
62 /* Whether the value contains an '@' string. If so, we can not
63 compress whitespace characters. */
65 /* The number of embedded '@' characters in an '@' string. If
66 this is non-zero, we must search the string for pairs of '@'
67 and convert them to a single '@'. */
71 static RCSNode *RCS_parsercsfile_i (FILE * fp, const char *rcsfile);
72 static char *RCS_getdatebranch (RCSNode * rcs, const char *date,
74 static void rcsbuf_open (struct rcsbuffer *, FILE *fp,
75 const char *filename, unsigned long pos);
76 static void rcsbuf_close (struct rcsbuffer *);
77 static int rcsbuf_getkey (struct rcsbuffer *, char **keyp, char **valp);
78 static int rcsbuf_getrevnum (struct rcsbuffer *, char **revp);
79 static char *rcsbuf_fill (struct rcsbuffer *, char *ptr, char **keyp,
81 static int rcsbuf_valcmp (struct rcsbuffer *);
82 static char *rcsbuf_valcopy (struct rcsbuffer *, char *val, int polish,
84 static void rcsbuf_valpolish (struct rcsbuffer *, char *val, int polish,
86 static void rcsbuf_valpolish_internal (struct rcsbuffer *, char *to,
87 const char *from, size_t *lenp);
88 static off_t rcsbuf_ftello (struct rcsbuffer *);
89 static void rcsbuf_get_buffered (struct rcsbuffer *, char **datap,
91 static void rcsbuf_cache (RCSNode *, struct rcsbuffer *);
92 static void rcsbuf_cache_close (void);
93 static void rcsbuf_cache_open (RCSNode *, off_t, FILE **, struct rcsbuffer *);
94 static int checkmagic_proc (Node *p, void *closure);
95 static void do_branches (List * list, char *val);
96 static void do_symbols (List * list, char *val);
97 static void do_locks (List * list, char *val);
98 static void free_rcsnode_contents (RCSNode *);
99 static void free_rcsvers_contents (RCSVers *);
100 static void rcsvers_delproc (Node * p);
101 static char *translate_symtag (RCSNode *, const char *);
102 static char *RCS_addbranch (RCSNode *, const char *);
103 static char *truncate_revnum_in_place (char *);
104 static char *truncate_revnum (const char *);
105 static char *printable_date (const char *);
106 static char *escape_keyword_value (const char *, int *);
107 static void expand_keywords (RCSNode *, RCSVers *, const char *,
108 const char *, size_t, enum kflag, char *,
109 size_t, char **, size_t *);
110 static void cmp_file_buffer (void *, const char *, size_t);
112 /* Routines for reading, parsing and writing RCS files. */
113 static RCSVers *getdelta (struct rcsbuffer *, char *, char **, char **);
114 static Deltatext *RCS_getdeltatext (RCSNode *, FILE *, struct rcsbuffer *);
115 static void freedeltatext (Deltatext *);
117 static void RCS_putadmin (RCSNode *, FILE *);
118 static void RCS_putdtree (RCSNode *, char *, FILE *);
119 static void RCS_putdesc (RCSNode *, FILE *);
120 static void putdelta (RCSVers *, FILE *);
121 static int putrcsfield_proc (Node *, void *);
122 static int putsymbol_proc (Node *, void *);
123 static void RCS_copydeltas (RCSNode *, FILE *, struct rcsbuffer *, FILE *,
124 Deltatext *, char *);
125 static int count_delta_actions (Node *, void *);
126 static void putdeltatext (FILE *, Deltatext *);
128 static FILE *rcs_internal_lockfile (char *);
129 static void rcs_internal_unlockfile (FILE *, char *);
130 static char *rcs_lockfilename (const char *);
132 /* The RCS file reading functions are called a lot, and they do some
133 string comparisons. This macro speeds things up a bit by skipping
134 the function call when the first characters are different. It
135 evaluates its arguments multiple times. */
136 #define STREQ(a, b) (*(char *)(a) == *(char *)(b) && strcmp ((a), (b)) == 0)
138 static char * getfullCVSname (char *, char **);
141 * We don't want to use isspace() from the C library because:
143 * 1. The definition of "whitespace" in RCS files includes ASCII
144 * backspace, but the C locale doesn't.
145 * 2. isspace is an very expensive function call in some implementations
146 * due to the addition of wide character support.
148 static const char spacetab[] = {
149 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, /* 0x00 - 0x0f */
150 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 - 0x1f */
151 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 - 0x2f */
152 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x30 - 0x3f */
153 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x40 - 0x4f */
154 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x50 - 0x5f */
155 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x60 - 0x8f */
156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x70 - 0x7f */
157 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x80 - 0x8f */
158 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x90 - 0x9f */
159 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xa0 - 0xaf */
160 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xb0 - 0xbf */
161 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xc0 - 0xcf */
162 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xd0 - 0xdf */
163 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0xe0 - 0xef */
164 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 0xf0 - 0xff */
167 #define whitespace(c) (spacetab[(unsigned char)c] != 0)
169 static char *rcs_lockfile = NULL;
170 static int rcs_lockfd = -1;
176 * locate_rcs ( const char* file, const char *repository , int *inattic )
178 * Find an RCS file in the repository, case insensitively when the cased name
179 * doesn't exist, we are running as the server, and a client has asked us to
182 * Most parts of CVS will want to rely instead on RCS_parse which calls this
183 * function and is called by recurse.c which then puts the result in useful
184 * places like the rcs field of struct file_info.
188 * repository the repository (including the directory)
189 * file the filename within that directory (without RCSEXT).
190 * inattic NULL or a pointer to the output boolean
194 * inattic If this input was non-null, the destination will be
195 * set to true if the file was found in the attic or
196 * false if not. If no RCS file is found, this value
201 * a newly-malloc'd array containing the absolute pathname of the RCS
202 * file that was found or NULL when none was found.
206 * errno can be set by the return value of the final call to
207 * locate_file_in_dir(). This should resolve to the system's existence error
208 * value (sometime ENOENT) if the Attic directory did not exist and ENOENT if
209 * the Attic was found but no matching files were found in the Attic or its
213 locate_rcs (const char *repository, const char *file, int *inattic)
217 /* First, try to find the file as cased. */
218 retval = xmalloc (strlen (repository)
223 sprintf (retval, "%s/%s%s", repository, file, RCSEXT);
224 if (isreadable (retval))
230 sprintf (retval, "%s/%s/%s%s", repository, CVSATTIC, file, RCSEXT);
231 if (isreadable (retval))
244 /* A few generic thoughts on error handling, in particular the
245 printing of unexpected characters that we find in the RCS file
246 (that is, why we use '\x%x' rather than %c or some such).
248 * Avoiding %c means we don't have to worry about what is printable
249 and other such stuff. In error handling, often better to keep it
252 * Hex rather than decimal or octal because character set standards
255 * Saying "character 0x%x" might make it sound like we are printing
256 a file offset. So we use '\x%x'.
258 * Would be nice to print the offset within the file, but I can
259 imagine various portability hassles (in particular, whether
260 unsigned long is always big enough to hold file offsets). */
262 /* Parse an rcsfile given a user file name and a repository. If there is
263 an error, we print an error message and return NULL. If the file
264 does not exist, we return NULL without printing anything (I'm not
265 sure this allows the caller to do anything reasonable, but it is
266 the current behavior). */
268 RCS_parse (const char *file, const char *repos)
272 RCSNode *retval = NULL;
276 /* We're creating a new RCSNode, so there is no hope of finding it
278 rcsbuf_cache_close ();
280 if (!(rcsfile = locate_rcs (repos, file, &inattic)))
282 /* Handle the error cases */
284 else if ((fp = CVS_FOPEN (rcsfile, FOPEN_BINARY_READ)))
286 rcs = RCS_parsercsfile_i (fp, rcsfile);
291 rcs->flags |= INATTIC;
297 else if (!existence_error (errno))
299 error (0, errno, "cannot open `%s'", rcsfile);
309 * Parse a specific rcsfile.
312 RCS_parsercsfile (const char *rcsfile)
317 /* We're creating a new RCSNode, so there is no hope of finding it
319 rcsbuf_cache_close ();
321 /* open the rcsfile */
322 if ((fp = CVS_FOPEN (rcsfile, FOPEN_BINARY_READ)) == NULL)
324 error (0, errno, "Couldn't open rcs file `%s'", rcsfile);
328 rcs = RCS_parsercsfile_i (fp, rcsfile);
338 RCS_parsercsfile_i (FILE *fp, const char *rcsfile)
341 struct rcsbuffer rcsbuf;
345 rdata = xmalloc (sizeof (RCSNode));
346 memset (rdata, 0, sizeof (RCSNode));
348 rdata->path = xstrdup (rcsfile);
349 rdata->print_path = xstrdup (primary_root_inverse_translate (rcsfile));
351 /* Process HEAD, BRANCH, and EXPAND keywords from the RCS header.
353 Most cvs operations on the main branch don't need any more
354 information. Those that do call RCS_reparsercsfile to parse
355 the rest of the header and the deltas. */
357 rcsbuf_open (&rcsbuf, fp, rcsfile, 0);
359 if (! rcsbuf_getkey (&rcsbuf, &key, &value))
361 if (STREQ (key, RCSDESC))
364 if (STREQ (RCSHEAD, key) && value != NULL)
365 rdata->head = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
367 if (! rcsbuf_getkey (&rcsbuf, &key, &value))
369 if (STREQ (key, RCSDESC))
372 if (STREQ (RCSBRANCH, key) && value != NULL)
376 rdata->branch = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
377 if ((numdots (rdata->branch) & 1) != 0)
379 /* turn it into a branch if it's a revision */
380 cp = strrchr (rdata->branch, '.');
385 /* Look ahead for expand, stopping when we see desc or a revision
391 if (STREQ (RCSEXPAND, key))
393 rdata->expand = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
398 (isdigit ((unsigned char)*cp) || *cp == '.') && *cp != '\0';
404 if (STREQ (RCSDESC, key))
407 if (! rcsbuf_getkey (&rcsbuf, &key, &value))
411 rdata->flags |= PARTIAL;
413 rcsbuf_cache (rdata, &rcsbuf);
418 error (0, 0, "`%s' does not appear to be a valid rcs file",
420 rcsbuf_close (&rcsbuf);
421 freercsnode (&rdata);
428 /* Do the real work of parsing an RCS file.
430 On error, die with a fatal error; if it returns at all it was successful.
432 If PFP is NULL, close the file when done. Otherwise, leave it open
433 and store the FILE * in *PFP. */
435 RCS_reparsercsfile (RCSNode *rdata, FILE **pfp, struct rcsbuffer *rcsbufp)
439 struct rcsbuffer rcsbuf;
446 assert (rdata != NULL);
447 rcsfile = rdata->path;
449 rcsbuf_cache_open (rdata, 0, &fp, &rcsbuf);
452 /* This probably shouldn't be done until later: if a file has an
453 empty revision tree (which is permissible), rdata->versions
454 should be NULL. -twp */
455 rdata->versions = getlist ();
458 * process all the special header information, break out when we get to
459 * the first revision delta
464 /* get the next key/value pair */
467 if (! rcsbuf_getkey (&rcsbuf, &key, &value))
469 error (1, 0, "`%s' does not appear to be a valid rcs file",
476 /* Skip head, branch and expand tags; we already have them. */
477 if (STREQ (key, RCSHEAD)
478 || STREQ (key, RCSBRANCH)
479 || STREQ (key, RCSEXPAND))
484 if (STREQ (key, "access"))
488 /* We pass the POLISH parameter as 1 because
489 RCS_addaccess expects nothing but spaces. FIXME:
490 It would be easy and more efficient to change
495 "Duplicate `access' keyword found in RCS file.");
496 free (rdata->access);
498 rdata->access = rcsbuf_valcopy (&rcsbuf, value, 1, NULL);
503 /* We always save lock information, so that we can handle
504 -kkvl correctly when checking out a file. */
505 if (STREQ (key, "locks"))
509 if (rdata->locks_data)
512 "Duplicate `locks' keyword found in RCS file.");
513 free (rdata->locks_data);
515 rdata->locks_data = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
517 if (! rcsbuf_getkey (&rcsbuf, &key, &value))
519 error (1, 0, "premature end of file reading %s", rcsfile);
521 if (STREQ (key, "strict") && value == NULL)
523 rdata->strict_locks = 1;
530 if (STREQ (RCSSYMBOLS, key))
534 if (rdata->symbols_data)
537 "Duplicate `%s' keyword found in RCS file.",
539 free (rdata->symbols_data);
541 rdata->symbols_data = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
547 * check key for '.''s and digits (probably a rev) if it is a
548 * revision or `desc', we are done with the headers and are down to the
549 * revision deltas, so we break out of the loop
552 (isdigit ((unsigned char) *cp) || *cp == '.') && *cp != '\0';
555 /* Note that when comparing with RCSDATE, we are not massaging
556 VALUE from the string found in the RCS file. This is OK
557 since we know exactly what to expect. */
558 if (*cp == '\0' && strncmp (RCSDATE, value, (sizeof RCSDATE) - 1) == 0)
561 if (STREQ (key, RCSDESC))
564 if (STREQ (key, "comment"))
569 "warning: duplicate key `%s' in RCS file `%s'",
571 free (rdata->comment);
573 rdata->comment = rcsbuf_valcopy (&rcsbuf, value, 0, NULL);
576 if (rdata->other == NULL)
577 rdata->other = getlist ();
579 kv->type = rcsbuf_valcmp (&rcsbuf) ? RCSCMPFLD : RCSFIELD;
580 kv->key = xstrdup (key);
581 kv->data = rcsbuf_valcopy (&rcsbuf, value, kv->type == RCSFIELD, NULL);
582 if (addnode (rdata->other, kv) != 0)
584 error (0, 0, "warning: duplicate key `%s' in RCS file `%s'",
589 /* if we haven't grabbed it yet, we didn't want it */
592 /* We got out of the loop, so we have the first part of the first
593 revision delta in KEY (the revision) and VALUE (the date key
594 and its value). This is what getdelta expects to receive. */
596 while ((vnode = getdelta (&rcsbuf, rcsfile, &key, &value)) != NULL)
601 q->delproc = rcsvers_delproc;
603 q->key = vnode->version;
605 /* add the nodes to the list */
606 if (addnode (rdata->versions, q) != 0)
609 purify_printf("WARNING: Adding duplicate version: %s (%s)\n",
616 /* Here KEY and VALUE are whatever caused getdelta to return NULL. */
618 if (STREQ (key, RCSDESC))
620 if (rdata->desc != NULL)
623 "warning: duplicate key `%s' in RCS file `%s'",
627 rdata->desc = rcsbuf_valcopy (&rcsbuf, value, 1, NULL);
630 rdata->delta_pos = rcsbuf_ftello (&rcsbuf);
633 rcsbuf_cache (rdata, &rcsbuf);
639 rdata->flags &= ~PARTIAL;
644 /* Move RCS into or out of the Attic, depending on TOATTIC. If the
645 file is already in the desired place, return without doing
646 anything. At some point may want to think about how this relates
647 to RCS_rewrite but that is a bit hairy (if one wants renames to be
648 atomic, or that kind of thing). If there is an error, print a message
649 and return 1. On success, return 0. */
651 RCS_setattic (RCSNode *rcs, int toattic)
657 /* Some systems aren't going to let us rename an open file. */
658 rcsbuf_cache_close ();
660 /* Could make the pathname computations in this file, and probably
661 in other parts of rcs.c too, easier if the REPOS and FILE
662 arguments to RCS_parse got stashed in the RCSNode. */
668 if (rcs->flags & INATTIC)
671 /* Example: rcs->path is "/foo/bar/baz,v". */
672 newpath = xmalloc (strlen (rcs->path) + sizeof CVSATTIC + 5);
673 p = last_component (rcs->path);
674 strncpy (newpath, rcs->path, p - rcs->path);
675 strcpy (newpath + (p - rcs->path), CVSATTIC);
677 /* Create the Attic directory if it doesn't exist. */
678 omask = umask (cvsumask);
679 if (CVS_MKDIR (newpath, 0777) < 0 && errno != EEXIST)
680 error (0, errno, "cannot make directory %s", newpath);
681 (void) umask (omask);
683 strcat (newpath, "/");
686 if (CVS_RENAME (rcs->path, newpath) < 0)
688 int save_errno = errno;
690 /* The checks for isreadable look awfully fishy, but
691 I'm going to leave them here for now until I
692 can think harder about whether they take care of
693 some cases which should be handled somehow. */
695 if (isreadable (rcs->path) || !isreadable (newpath))
697 error (0, save_errno, "cannot rename %s to %s",
706 if (!(rcs->flags & INATTIC))
709 newpath = xmalloc (strlen (rcs->path));
711 /* Example: rcs->path is "/foo/bar/Attic/baz,v". */
712 p = last_component (rcs->path);
713 strncpy (newpath, rcs->path, p - rcs->path - 1);
714 newpath[p - rcs->path - 1] = '\0';
715 q = newpath + (p - rcs->path - 1) - (sizeof CVSATTIC - 1);
716 assert (strncmp (q, CVSATTIC, sizeof CVSATTIC - 1) == 0);
719 if (CVS_RENAME (rcs->path, newpath) < 0)
721 error (0, errno, "failed to move `%s' out of the attic",
737 * Fully parse the RCS file. Store all keyword/value pairs, fetch the
738 * log messages for each revision, and fetch add and delete counts for
739 * each revision (we could fetch the entire text for each revision,
740 * but the only caller, log_fileproc, doesn't need that information,
741 * so we don't waste the memory required to store it). The add and
742 * delete counts are stored on the OTHER field of the RCSVERSNODE
743 * structure, under the names ";add" and ";delete", so that we don't
744 * waste the memory space of extra fields in RCSVERSNODE for code
745 * which doesn't need this information.
748 RCS_fully_parse (RCSNode *rcs)
751 struct rcsbuffer rcsbuf;
753 RCS_reparsercsfile (rcs, &fp, &rcsbuf);
761 /* Rather than try to keep track of how much information we
762 have read, just read to the end of the file. */
763 if (!rcsbuf_getrevnum (&rcsbuf, &key))
766 vers = findnode (rcs->versions, key);
769 "mismatch in rcs file %s between deltas and deltatexts (%s)",
770 rcs->print_path, key);
774 while (rcsbuf_getkey (&rcsbuf, &key, &value))
776 if (!STREQ (key, "text"))
780 if (vnode->other == NULL)
781 vnode->other = getlist ();
783 kv->type = rcsbuf_valcmp (&rcsbuf) ? RCSCMPFLD : RCSFIELD;
784 kv->key = xstrdup (key);
785 kv->data = rcsbuf_valcopy (&rcsbuf, value, kv->type == RCSFIELD,
787 if (addnode (vnode->other, kv) != 0)
791 warning: duplicate key `%s' in version `%s' of RCS file `%s'",
792 key, vnode->version, rcs->print_path);
799 if (!STREQ (vnode->version, rcs->head))
801 unsigned long add, del;
805 /* This is a change text. Store the add and delete
814 rcsbuf_valpolish (&rcsbuf, value, 0, &vallen);
816 while (cp < value + vallen)
822 if (op != 'a' && op != 'd')
824 unrecognized operation '\\x%x' in %s",
825 op, rcs->print_path);
826 (void) strtoul (cp, (char **) &cp, 10);
828 error (1, 0, "space expected in %s revision %s",
829 rcs->print_path, vnode->version);
830 count = strtoul (cp, (char **) &cp, 10);
832 error (1, 0, "linefeed expected in %s revision %s",
833 rcs->print_path, vnode->version);
844 else if (cp == value + vallen)
848 premature end of value in %s revision %s",
849 rcs->print_path, vnode->version);
859 sprintf (buf, "%lu", add);
862 kv->key = xstrdup (";add");
863 kv->data = xstrdup (buf);
864 if (addnode (vnode->other, kv) != 0)
868 warning: duplicate key `%s' in version `%s' of RCS file `%s'",
869 key, vnode->version, rcs->print_path);
873 sprintf (buf, "%lu", del);
876 kv->key = xstrdup (";delete");
877 kv->data = xstrdup (buf);
878 if (addnode (vnode->other, kv) != 0)
882 warning: duplicate key `%s' in version `%s' of RCS file `%s'",
883 key, vnode->version, rcs->print_path);
888 /* We have found the "text" key which ends the data for
889 this revision. Break out of the loop and go on to the
895 rcsbuf_cache (rcs, &rcsbuf);
901 * freercsnode - free up the info for an RCSNode
904 freercsnode (RCSNode **rnodep)
906 if (rnodep == NULL || *rnodep == NULL)
909 ((*rnodep)->refcount)--;
910 if ((*rnodep)->refcount != 0)
915 free ((*rnodep)->path);
916 free ((*rnodep)->print_path);
917 if ((*rnodep)->head != NULL)
918 free ((*rnodep)->head);
919 if ((*rnodep)->branch != NULL)
920 free ((*rnodep)->branch);
921 free_rcsnode_contents (*rnodep);
929 * free_rcsnode_contents - free up the contents of an RCSNode without
930 * freeing the node itself, or the file name, or the head, or the
931 * path. This returns the RCSNode to the state it is in immediately
932 * after a call to RCS_parse.
935 free_rcsnode_contents (RCSNode *rnode)
937 dellist (&rnode->versions);
938 if (rnode->symbols != NULL)
939 dellist (&rnode->symbols);
940 if (rnode->symbols_data != NULL)
941 free (rnode->symbols_data);
942 if (rnode->expand != NULL)
943 free (rnode->expand);
944 if (rnode->other != NULL)
945 dellist (&rnode->other);
946 if (rnode->access != NULL)
947 free (rnode->access);
948 if (rnode->locks_data != NULL)
949 free (rnode->locks_data);
950 if (rnode->locks != NULL)
951 dellist (&rnode->locks);
952 if (rnode->comment != NULL)
953 free (rnode->comment);
954 if (rnode->desc != NULL)
960 /* free_rcsvers_contents -- free up the contents of an RCSVers node,
961 but also free the pointer to the node itself. */
962 /* Note: The `hardlinks' list is *not* freed, since it is merely a
963 pointer into the `hardlist' structure (defined in hardlink.c), and
964 that structure is freed elsewhere in the program. */
966 free_rcsvers_contents (RCSVers *rnode)
968 if (rnode->branches != NULL)
969 dellist (&rnode->branches);
970 if (rnode->date != NULL)
972 if (rnode->next != NULL)
974 if (rnode->author != NULL)
975 free (rnode->author);
976 if (rnode->state != NULL)
978 if (rnode->other != NULL)
979 dellist (&rnode->other);
980 if (rnode->other_delta != NULL)
981 dellist (&rnode->other_delta);
982 if (rnode->text != NULL)
983 freedeltatext (rnode->text);
990 * rcsvers_delproc - free up an RCSVers type node
993 rcsvers_delproc (Node *p)
995 free_rcsvers_contents (p->data);
1000 /* These functions retrieve keys and values from an RCS file using a
1001 buffer. We use this somewhat complex approach because it turns out
1002 that for many common operations, CVS spends most of its time
1003 reading keys, so it's worth doing some fairly hairy optimization. */
1005 /* The number of bytes we try to read each time we need more data. */
1007 #define RCSBUF_BUFSIZE (8192)
1009 /* The buffer we use to store data. This grows as needed. */
1011 static char *rcsbuf_buffer = NULL;
1012 static size_t rcsbuf_buffer_size = 0;
1014 /* Whether rcsbuf_buffer is in use. This is used as a sanity check. */
1016 static int rcsbuf_inuse;
1018 /* Set up to start gathering keys and values from an RCS file. This
1019 initializes RCSBUF. */
1022 rcsbuf_open (struct rcsbuffer *rcsbuf, FILE *fp, const char *filename,
1023 long unsigned int pos)
1026 error (1, 0, "rcsbuf_open: internal error");
1031 /* When we have mmap, it is much more efficient to let the system do the
1032 * buffering and caching for us
1035 size_t mmap_off = 0;
1037 if ( fstat (fileno(fp), &fs) < 0 )
1038 error ( 1, errno, "Could not stat RCS archive %s for mapping", filename );
1042 size_t ps = getpagesize ();
1043 mmap_off = ( pos / ps ) * ps;
1046 /* Map private here since this particular buffer is read only */
1047 rcsbuf_buffer = mmap ( NULL, fs.st_size - mmap_off,
1048 PROT_READ | PROT_WRITE,
1049 MAP_PRIVATE, fileno(fp), mmap_off );
1050 if ( rcsbuf_buffer == NULL || rcsbuf_buffer == MAP_FAILED )
1051 error ( 1, errno, "Could not map memory to RCS archive %s", filename );
1053 rcsbuf_buffer_size = fs.st_size - mmap_off;
1054 rcsbuf->ptr = rcsbuf_buffer + pos - mmap_off;
1055 rcsbuf->ptrend = rcsbuf_buffer + fs.st_size - mmap_off;
1056 rcsbuf->pos = mmap_off;
1058 #else /* !HAVE_MMAP */
1059 if (rcsbuf_buffer_size < RCSBUF_BUFSIZE)
1060 expand_string (&rcsbuf_buffer, &rcsbuf_buffer_size, RCSBUF_BUFSIZE);
1062 rcsbuf->ptr = rcsbuf_buffer;
1063 rcsbuf->ptrend = rcsbuf_buffer;
1065 #endif /* HAVE_MMAP */
1067 rcsbuf->filename = filename;
1069 rcsbuf->at_string = 0;
1070 rcsbuf->embedded_at = 0;
1075 /* Stop gathering keys from an RCS file. */
1077 rcsbuf_close (struct rcsbuffer *rcsbuf)
1080 error (1, 0, "rcsbuf_close: internal error");
1082 munmap ( rcsbuf_buffer, rcsbuf_buffer_size );
1089 /* Read a key/value pair from an RCS file. This sets *KEYP to point
1090 to the key, and *VALUEP to point to the value. A missing or empty
1091 value is indicated by setting *VALUEP to NULL.
1093 This function returns 1 on success, or 0 on EOF. If there is an
1094 error reading the file, or an EOF in an unexpected location, it
1095 gives a fatal error.
1097 This sets *KEYP and *VALUEP to point to storage managed by
1098 rcsbuf_getkey. Moreover, *VALUEP has not been massaged from the
1099 RCS format: it may contain embedded whitespace and embedded '@'
1100 characters. Call rcsbuf_valcopy or rcsbuf_valpolish to do
1101 appropriate massaging. */
1103 /* Note that the extreme hair in rcsbuf_getkey is because profiling
1104 statistics show that it was worth it. */
1106 rcsbuf_getkey (struct rcsbuffer *rcsbuf, char **keyp, char **valp)
1108 register const char * const my_spacetab = spacetab;
1109 register char *ptr, *ptrend;
1112 #define my_whitespace(c) (my_spacetab[(unsigned char)c] != 0)
1115 rcsbuf->at_string = 0;
1116 rcsbuf->embedded_at = 0;
1119 ptrend = rcsbuf->ptrend;
1122 assert (ptr >= rcsbuf_buffer && ptr <= rcsbuf_buffer + rcsbuf_buffer_size);
1123 assert (ptrend >= rcsbuf_buffer && ptrend <= rcsbuf_buffer + rcsbuf_buffer_size);
1126 /* If the pointer is more than RCSBUF_BUFSIZE bytes into the
1127 buffer, move back to the start of the buffer. This keeps the
1128 buffer from growing indefinitely. */
1129 if (ptr - rcsbuf_buffer >= RCSBUF_BUFSIZE)
1135 /* Sanity check: we don't read more than RCSBUF_BUFSIZE bytes
1136 at a time, so we can't have more bytes than that past PTR. */
1137 assert (len <= RCSBUF_BUFSIZE);
1139 /* Update the POS field, which holds the file offset of the
1140 first byte in the RCSBUF_BUFFER buffer. */
1141 rcsbuf->pos += ptr - rcsbuf_buffer;
1143 memcpy (rcsbuf_buffer, ptr, len);
1144 ptr = rcsbuf_buffer;
1146 rcsbuf->ptrend = ptrend;
1148 #endif /* HAVE_MMAP */
1150 /* Skip leading whitespace. */
1156 ptr = rcsbuf_fill (rcsbuf, ptr, NULL, NULL);
1159 ptrend = rcsbuf->ptrend;
1163 if (! my_whitespace (c))
1169 /* We've found the start of the key. */
1180 ptr = rcsbuf_fill (rcsbuf, ptr, keyp, NULL);
1182 error (1, 0, "EOF in key in RCS file %s",
1183 primary_root_inverse_translate (rcsbuf->filename));
1184 ptrend = rcsbuf->ptrend;
1187 if (c == ';' || my_whitespace (c))
1192 /* Here *KEYP points to the key in the buffer, C is the character
1193 we found at the of the key, and PTR points to the location in
1194 the buffer where we found C. We must set *PTR to \0 in order
1195 to terminate the key. If the key ended with ';', then there is
1208 /* C must be whitespace. Skip whitespace between the key and the
1209 value. If we find ';' now, there is no value. */
1215 ptr = rcsbuf_fill (rcsbuf, ptr, keyp, NULL);
1217 error (1, 0, "EOF while looking for value in RCS file %s",
1218 primary_root_inverse_translate (rcsbuf->filename));
1219 ptrend = rcsbuf->ptrend;
1225 rcsbuf->ptr = ptr + 1;
1228 if (! my_whitespace (c))
1233 /* Now PTR points to the start of the value, and C is the first
1234 character of the value. */
1243 /* Optimize the common case of a value composed of a single
1246 rcsbuf->at_string = 1;
1254 while ((pat = memchr (ptr, '@', ptrend - ptr)) == NULL)
1256 /* Note that we pass PTREND as the PTR value to
1257 rcsbuf_fill, so that we will wind up setting PTR to
1258 the location corresponding to the old PTREND, so
1259 that we don't search the same bytes again. */
1260 ptr = rcsbuf_fill (rcsbuf, ptrend, keyp, valp);
1263 "EOF while looking for end of string in RCS file %s",
1264 primary_root_inverse_translate (rcsbuf->filename));
1265 ptrend = rcsbuf->ptrend;
1268 /* Handle the special case of an '@' right at the end of
1270 if (pat + 1 >= ptrend)
1272 /* Note that we pass PAT, not PTR, here. */
1273 pat = rcsbuf_fill (rcsbuf, pat, keyp, valp);
1276 /* EOF here is OK; it just means that the last
1277 character of the file was an '@' terminating a
1278 value for a key type which does not require a
1280 pat = rcsbuf->ptrend - 1;
1283 ptrend = rcsbuf->ptrend;
1285 /* Note that the value of PTR is bogus here. This is
1286 OK, because we don't use it. */
1289 if (pat + 1 >= ptrend || pat[1] != '@')
1292 /* We found an '@' pair in the string. Keep looking. */
1293 ++rcsbuf->embedded_at;
1297 /* Here PAT points to the final '@' in the string. */
1304 rcsbuf->vlen = vlen;
1309 /* Certain keywords only have a '@' string. If there is no '@'
1310 string, then the old getrcskey function assumed that they had
1311 no value, and we do the same. */
1317 if (STREQ (k, RCSDESC)
1318 || STREQ (k, "text")
1319 || STREQ (k, "log"))
1328 /* If we've already gathered a '@' string, try to skip whitespace
1338 ptr = rcsbuf_fill (rcsbuf, ptr, keyp, valp);
1340 error (1, 0, "EOF in value in RCS file %s",
1341 primary_root_inverse_translate (rcsbuf->filename));
1342 ptrend = rcsbuf->ptrend;
1347 /* We're done. We already set everything up for this
1349 rcsbuf->ptr = ptr + 1;
1352 if (! my_whitespace (n))
1357 /* The value extends past the '@' string. We need to undo the
1358 '@' stripping done in the default case above. This
1359 case never happens in a plain RCS file, but it can happen
1360 if user defined phrases are used. */
1361 ((*valp)--)[rcsbuf->vlen++] = '@';
1364 /* Here we have a value which is not a simple '@' string. We need
1365 to gather up everything until the next ';', including any '@'
1366 strings. *VALP points to the start of the value. If
1367 RCSBUF->VLEN is not zero, then we have already read an '@'
1368 string, and PTR points to the data following the '@' string.
1369 Otherwise, PTR points to the start of the value. */
1373 char *start, *psemi, *pat;
1375 /* Find the ';' which must end the value. */
1377 while ((psemi = memchr (ptr, ';', ptrend - ptr)) == NULL)
1381 /* Note that we pass PTREND as the PTR value to
1382 rcsbuf_fill, so that we will wind up setting PTR to the
1383 location corresponding to the old PTREND, so that we
1384 don't search the same bytes again. */
1385 slen = start - *valp;
1386 ptr = rcsbuf_fill (rcsbuf, ptrend, keyp, valp);
1388 error (1, 0, "EOF in value in RCS file %s",
1389 primary_root_inverse_translate (rcsbuf->filename));
1390 start = *valp + slen;
1391 ptrend = rcsbuf->ptrend;
1394 /* See if there are any '@' strings in the value. */
1395 pat = memchr (start, '@', psemi - start);
1401 /* We're done with the value. Trim any trailing
1404 rcsbuf->ptr = psemi + 1;
1407 while (psemi > start && my_whitespace (psemi[-1]))
1411 vlen = psemi - start;
1414 rcsbuf->vlen = vlen;
1419 /* We found an '@' string in the value. We set RCSBUF->AT_STRING
1420 and RCSBUF->EMBEDDED_AT to indicate that we won't be able to
1421 compress whitespace correctly for this type of value.
1422 Since this type of value never arises in a normal RCS file,
1423 this should not be a big deal. It means that if anybody
1424 adds a phrase which can have both an '@' string and regular
1425 text, they will have to handle whitespace compression
1428 rcsbuf->at_string = 1;
1429 rcsbuf->embedded_at = -1;
1435 while ((pat = memchr (ptr, '@', ptrend - ptr)) == NULL)
1437 /* Note that we pass PTREND as the PTR value to
1438 rcsbuff_fill, so that we will wind up setting PTR
1439 to the location corresponding to the old PTREND, so
1440 that we don't search the same bytes again. */
1441 ptr = rcsbuf_fill (rcsbuf, ptrend, keyp, valp);
1444 "EOF while looking for end of string in RCS file %s",
1445 primary_root_inverse_translate (rcsbuf->filename));
1446 ptrend = rcsbuf->ptrend;
1449 /* Handle the special case of an '@' right at the end of
1451 if (pat + 1 >= ptrend)
1453 ptr = rcsbuf_fill (rcsbuf, ptr, keyp, valp);
1455 error (1, 0, "EOF in value in RCS file %s",
1456 primary_root_inverse_translate (rcsbuf->filename));
1457 ptrend = rcsbuf->ptrend;
1463 /* We found an '@' pair in the string. Keep looking. */
1467 /* Here PAT points to the final '@' in the string. */
1471 #undef my_whitespace
1476 /* Read an RCS revision number from an RCS file. This sets *REVP to
1477 point to the revision number; it will point to space that is
1478 managed by the rcsbuf functions, and is only good until the next
1479 call to rcsbuf_getkey or rcsbuf_getrevnum.
1481 This function returns 1 on success, or 0 on EOF. If there is an
1482 error reading the file, or an EOF in an unexpected location, it
1483 gives a fatal error. */
1485 rcsbuf_getrevnum (struct rcsbuffer *rcsbuf, char **revp)
1491 ptrend = rcsbuf->ptrend;
1495 /* Skip leading whitespace. */
1501 ptr = rcsbuf_fill (rcsbuf, ptr, NULL, NULL);
1504 ptrend = rcsbuf->ptrend;
1508 if (! whitespace (c))
1514 if (! isdigit ((unsigned char) c) && c != '.')
1517 unexpected '\\x%x' reading revision number in RCS file %s",
1518 c, primary_root_inverse_translate (rcsbuf->filename));
1527 ptr = rcsbuf_fill (rcsbuf, ptr, revp, NULL);
1530 "unexpected EOF reading revision number in RCS file %s",
1531 primary_root_inverse_translate (rcsbuf->filename));
1532 ptrend = rcsbuf->ptrend;
1537 while (isdigit ((unsigned char) c) || c == '.');
1539 if (! whitespace (c))
1541 unexpected '\\x%x' reading revision number in RCS file %s",
1542 c, primary_root_inverse_translate (rcsbuf->filename));
1546 rcsbuf->ptr = ptr + 1;
1553 /* Fill RCSBUF_BUFFER with bytes from the file associated with RCSBUF,
1554 updating PTR and the PTREND field. If KEYP and *KEYP are not NULL,
1555 then *KEYP points into the buffer, and must be adjusted if the
1556 buffer is changed. Likewise for VALP. Returns the new value of
1557 PTR, or NULL on error. */
1559 rcsbuf_fill (struct rcsbuffer *rcsbuf, char *ptr, char **keyp, char **valp)
1563 #else /* HAVE_MMAP */
1566 if (rcsbuf->ptrend - rcsbuf_buffer + RCSBUF_BUFSIZE > rcsbuf_buffer_size)
1568 int poff, peoff, koff, voff;
1570 poff = ptr - rcsbuf_buffer;
1571 peoff = rcsbuf->ptrend - rcsbuf_buffer;
1572 koff = keyp == NULL ? 0 : *keyp - rcsbuf_buffer;
1573 voff = valp == NULL ? 0 : *valp - rcsbuf_buffer;
1575 expand_string (&rcsbuf_buffer, &rcsbuf_buffer_size,
1576 rcsbuf_buffer_size + RCSBUF_BUFSIZE);
1578 ptr = rcsbuf_buffer + poff;
1579 rcsbuf->ptrend = rcsbuf_buffer + peoff;
1581 *keyp = rcsbuf_buffer + koff;
1583 *valp = rcsbuf_buffer + voff;
1586 got = fread (rcsbuf->ptrend, 1, RCSBUF_BUFSIZE, rcsbuf->fp);
1589 if (ferror (rcsbuf->fp))
1590 error (1, errno, "cannot read %s", rcsbuf->filename);
1594 rcsbuf->ptrend += got;
1597 #endif /* HAVE_MMAP */
1602 /* Test whether the last value returned by rcsbuf_getkey is a composite
1605 rcsbuf_valcmp (struct rcsbuffer *rcsbuf)
1607 return rcsbuf->at_string && rcsbuf->embedded_at < 0;
1612 /* Copy the value VAL returned by rcsbuf_getkey into a memory buffer,
1613 returning the memory buffer. Polish the value like
1614 rcsbuf_valpolish, q.v. */
1616 rcsbuf_valcopy (struct rcsbuffer *rcsbuf, char *val, int polish, size_t *lenp)
1629 vlen = rcsbuf->vlen;
1630 embedded_at = rcsbuf->embedded_at < 0 ? 0 : rcsbuf->embedded_at;
1632 ret = xmalloc (vlen - embedded_at + 1);
1634 if (rcsbuf->at_string ? embedded_at == 0 : ! polish)
1636 /* No special action to take. */
1637 memcpy (ret, val, vlen + 1);
1643 rcsbuf_valpolish_internal (rcsbuf, ret, val, lenp);
1649 /* Polish the value VAL returned by rcsbuf_getkey. The POLISH
1650 parameter is non-zero if multiple embedded whitespace characters
1651 should be compressed into a single whitespace character. Note that
1652 leading and trailing whitespace was already removed by
1653 rcsbuf_getkey. Within an '@' string, pairs of '@' characters are
1654 compressed into a single '@' character regardless of the value of
1655 POLISH. If LENP is not NULL, set *LENP to the length of the value. */
1657 rcsbuf_valpolish (struct rcsbuffer *rcsbuf, char *val, int polish,
1667 if (rcsbuf->at_string ? rcsbuf->embedded_at == 0 : ! polish)
1669 /* No special action to take. */
1671 *lenp = rcsbuf->vlen;
1675 rcsbuf_valpolish_internal (rcsbuf, val, val, lenp);
1680 /* Internal polishing routine, called from rcsbuf_valcopy and
1681 rcsbuf_valpolish. */
1683 rcsbuf_valpolish_internal (struct rcsbuffer *rcsbuf, char *to,
1684 const char *from, size_t *lenp)
1690 if (! rcsbuf->at_string)
1697 for (clen = len; clen > 0; ++from, --clen)
1704 /* Note that we know that clen can not drop to zero
1705 while we have whitespace, because we know there is
1706 no trailing whitespace. */
1707 while (whitespace (from[1]))
1720 *lenp = to - orig_to;
1724 const char *orig_from;
1732 embedded_at = rcsbuf->embedded_at;
1733 assert (embedded_at > 0);
1736 *lenp = len - embedded_at;
1738 for (clen = len; clen > 0; ++from, --clen)
1750 * FIXME: I restored this to an abort from an assert based on
1751 * advice from Larry Jones that asserts should not be used to
1752 * confirm the validity of an RCS file... This leaves two
1753 * issues here: 1) I am uncertain that the fact that we will
1754 * only find double '@'s hasn't already been confirmed; and:
1755 * 2) If this is the proper place to spot the error in the RCS
1756 * file, then we should print a much clearer error here for the
1761 if (*from != '@' || clen == 0)
1767 if (embedded_at == 0)
1769 /* We've found all the embedded '@' characters.
1770 We can just memcpy the rest of the buffer after
1771 this '@' character. */
1772 if (orig_to != orig_from)
1773 memcpy (to, from + 1, clen - 1);
1775 memmove (to, from + 1, clen - 1);
1784 assert (from == orig_from + len
1785 && to == orig_to + (len - rcsbuf->embedded_at));
1793 #ifdef PRESERVE_PERMISSIONS_SUPPORT
1795 /* Copy the next word from the value VALP returned by rcsbuf_getkey into a
1796 memory buffer, updating VALP and returning the memory buffer. Return
1797 NULL when there are no more words. */
1800 rcsbuf_valword (struct rcsbuffer *rcsbuf, char **valp)
1802 register const char * const my_spacetab = spacetab;
1803 register char *ptr, *pat;
1806 # define my_whitespace(c) (my_spacetab[(unsigned char)c] != 0)
1811 for (ptr = *valp; my_whitespace (*ptr); ++ptr) ;
1814 assert (ptr - *valp == rcsbuf->vlen);
1820 /* PTR now points to the start of a value. Find out whether it is
1821 a num, an id, a string or a colon. */
1825 rcsbuf->vlen -= ++ptr - *valp;
1827 return xstrdup (":");
1832 int embedded_at = 0;
1836 while ((pat = strchr (pat, '@')) != NULL)
1844 /* Here PAT points to the final '@' in the string. */
1846 assert (rcsbuf->at_string);
1847 vlen = rcsbuf->vlen - (pat - *valp);
1848 rcsbuf->vlen = pat - ptr - 1;
1849 rcsbuf->embedded_at = embedded_at;
1850 ptr = rcsbuf_valcopy (rcsbuf, ptr, 0, NULL);
1852 rcsbuf->vlen = vlen;
1853 if (strchr (pat, '@') == NULL)
1854 rcsbuf->at_string = 0;
1856 rcsbuf->embedded_at = -1;
1860 /* *PTR is neither `:', `;' nor `@', so it should be the start of a num
1861 or an id. Make sure it is not another special character. */
1862 if (c == '$' || c == '.' || c == ',')
1863 error (1, 0, "invalid special character in RCS field in %s",
1864 primary_root_inverse_translate (rcsbuf->filename));
1869 /* Legitimate ID characters are digits, dots and any `graphic
1870 printing character that is not a special.' This test ought
1873 if (!isprint ((unsigned char) c) ||
1874 c == ';' || c == '$' || c == ',' || c == '@' || c == ':')
1878 /* PAT points to the last non-id character in this word, and C is
1879 the character in its memory cell. Check to make sure that it
1880 is a legitimate word delimiter -- whitespace or end. */
1881 if (c != '\0' && !my_whitespace (c))
1882 error (1, 0, "invalid special character in RCS field in %s",
1883 primary_root_inverse_translate (rcsbuf->filename));
1886 rcsbuf->vlen -= pat - *valp;
1888 return xstrdup (ptr);
1890 # undef my_whitespace
1893 #endif /* PRESERVE_PERMISSIONS_SUPPORT */
1897 /* Return the current position of an rcsbuf. */
1899 rcsbuf_ftello (struct rcsbuffer *rcsbuf)
1901 return rcsbuf->pos + rcsbuf->ptr - rcsbuf_buffer;
1906 /* Return a pointer to any data buffered for RCSBUF, along with the
1909 rcsbuf_get_buffered (struct rcsbuffer *rcsbuf, char **datap, size_t *lenp)
1911 *datap = rcsbuf->ptr;
1912 *lenp = rcsbuf->ptrend - rcsbuf->ptr;
1917 /* CVS optimizes by quickly reading some header information from a
1918 file. If it decides it needs to do more with the file, it reopens
1919 it. We speed that up here by maintaining a cache of a single open
1920 file, to save the time it takes to reopen the file in the common
1922 static RCSNode *cached_rcs;
1923 static struct rcsbuffer cached_rcsbuf;
1925 /* Cache RCS and RCSBUF. This takes responsibility for closing
1928 rcsbuf_cache (RCSNode *rcs, struct rcsbuffer *rcsbuf)
1930 if (cached_rcs != NULL)
1931 rcsbuf_cache_close ();
1934 cached_rcsbuf = *rcsbuf;
1939 /* If there is anything in the cache, close it. */
1941 rcsbuf_cache_close (void)
1943 if (cached_rcs != NULL)
1945 rcsbuf_close (&cached_rcsbuf);
1946 if (fclose (cached_rcsbuf.fp) != 0)
1947 error (0, errno, "cannot close %s", cached_rcsbuf.filename);
1948 freercsnode (&cached_rcs);
1955 /* Open an rcsbuffer for RCS, getting it from the cache if possible.
1956 Set *FPP to the file, and *RCSBUFP to the rcsbuf. The file should
1957 be put at position POS. */
1959 rcsbuf_cache_open (RCSNode *rcs, off_t pos, FILE **pfp,
1960 struct rcsbuffer *prcsbuf)
1963 if (cached_rcs == rcs)
1965 if (rcsbuf_ftello (&cached_rcsbuf) != pos)
1967 if (fseeko (cached_rcsbuf.fp, pos, SEEK_SET) != 0)
1968 error (1, 0, "cannot fseeko RCS file %s",
1969 cached_rcsbuf.filename);
1970 cached_rcsbuf.ptr = rcsbuf_buffer;
1971 cached_rcsbuf.ptrend = rcsbuf_buffer;
1972 cached_rcsbuf.pos = pos;
1974 *pfp = cached_rcsbuf.fp;
1976 /* When RCS_parse opens a file using fopen_case, it frees the
1977 filename which we cached in CACHED_RCSBUF and stores a new
1978 file name in RCS->PATH. We avoid problems here by always
1979 copying the filename over. FIXME: This is hackish. */
1980 cached_rcsbuf.filename = rcs->path;
1982 *prcsbuf = cached_rcsbuf;
1986 /* Removing RCS from the cache removes a reference to it. */
1988 if (rcs->refcount <= 0)
1989 error (1, 0, "rcsbuf_cache_open: internal error");
1993 #endif /* ifndef HAVE_MMAP */
1994 /* FIXME: If these routines can be rewritten to not write to the
1995 * rcs file buffer, there would be a considerably larger memory savings
1996 * from using mmap since the shared file would never need be copied to
1999 * If this happens, cached mmapped buffers would be usable, but don't
2000 * forget to make sure rcs->pos < pos here...
2002 if (cached_rcs != NULL)
2003 rcsbuf_cache_close ();
2005 *pfp = CVS_FOPEN (rcs->path, FOPEN_BINARY_READ);
2007 error (1, 0, "unable to reopen `%s'", rcs->path);
2011 if (fseeko (*pfp, pos, SEEK_SET) != 0)
2012 error (1, 0, "cannot fseeko RCS file %s", rcs->path);
2014 #endif /* ifndef HAVE_MMAP */
2015 rcsbuf_open (prcsbuf, *pfp, rcs->path, pos);
2018 #endif /* ifndef HAVE_MMAP */
2024 * process the symbols list of the rcs file
2027 do_symbols (List *list, char *val)
2037 /* skip leading whitespace */
2038 while (whitespace (*cp))
2041 /* if we got to the end, we are done */
2045 /* split it up into tag and rev */
2047 cp = strchr (cp, ':');
2050 while (!whitespace (*cp) && *cp != '\0')
2055 /* make a new node and add it to the list */
2057 p->key = xstrdup (tag);
2058 p->data = xstrdup (rev);
2059 (void) addnode (list, p);
2066 * process the locks list of the rcs file
2067 * Like do_symbols, but hash entries are keyed backwards: i.e.
2068 * an entry like `user:rev' is keyed on REV rather than on USER.
2071 do_locks (List *list, char *val)
2081 /* skip leading whitespace */
2082 while (whitespace (*cp))
2085 /* if we got to the end, we are done */
2089 /* split it up into user and rev */
2091 cp = strchr (cp, ':');
2094 while (!whitespace (*cp) && *cp != '\0')
2099 /* make a new node and add it to the list */
2101 p->key = xstrdup (rev);
2102 p->data = xstrdup (user);
2103 (void) addnode (list, p);
2110 * process the branches list of a revision delta
2113 do_branches (List *list, char *val)
2121 /* skip leading whitespace */
2122 while (whitespace (*cp))
2125 /* if we got to the end, we are done */
2129 /* find the end of this branch */
2131 while (!whitespace (*cp) && *cp != '\0')
2136 /* make a new node and add it to the list */
2138 p->key = xstrdup (branch);
2139 (void) addnode (list, p);
2148 * Returns the requested version number of the RCS file, satisfying tags and/or
2149 * dates, and walking branches, if necessary.
2151 * The result is returned; null-string if error.
2154 RCS_getversion (RCSNode *rcs, const char *tag, const char *date,
2155 int force_tag_match, int *simple_tag)
2157 if (simple_tag != NULL)
2160 /* make sure we have something to look at... */
2161 assert (rcs != NULL);
2167 if (! RCS_nodeisbranch (rcs, tag))
2169 /* We can't get a particular date if the tag is not a
2174 /* Work out the branch. */
2175 if (! isdigit ((unsigned char) tag[0]))
2176 branch = RCS_whatbranch (rcs, tag);
2178 branch = xstrdup (tag);
2180 /* Fetch the revision of branch as of date. */
2181 rev = RCS_getdatebranch (rcs, date, branch);
2186 return RCS_gettag (rcs, tag, force_tag_match, simple_tag);
2188 return RCS_getdate (rcs, date, force_tag_match);
2190 return RCS_head (rcs);
2197 * Get existing revision number corresponding to tag or revision.
2198 * Similar to RCS_gettag but less interpretation imposed.
2200 * -- If tag designates a magic branch, RCS_tag2rev
2201 * returns the magic branch number.
2202 * -- If tag is a branch tag, returns the branch number, not
2203 * the revision of the head of the branch.
2204 * If tag or revision is not valid or does not exist in file,
2208 RCS_tag2rev (RCSNode *rcs, char *tag)
2210 char *rev, *pa, *pb;
2213 assert (rcs != NULL);
2215 if (rcs->flags & PARTIAL)
2216 RCS_reparsercsfile (rcs, NULL, NULL);
2218 /* If a valid revision, try to look it up */
2219 if ( RCS_valid_rev (tag) )
2221 /* Make a copy so we can scribble on it */
2222 rev = xstrdup (tag);
2224 /* If revision exists, return the copy */
2225 if (RCS_exist_rev (rcs, tag))
2228 /* Nope, none such. If tag is not a branch we're done. */
2232 pa = strrchr (rev, '.');
2233 if (i == 1 || *(pa-1) != RCS_MAGIC_BRANCH || *(pa-2) != '.')
2236 error (1, 0, "revision `%s' does not exist", tag);
2240 /* Try for a real (that is, exists in the RCS deltas) branch
2241 (RCS_exist_rev just checks for real revisions and revisions
2242 which have tags pointing to them). */
2243 pa = RCS_getbranch (rcs, rev, 1);
2250 /* Tag is branch, but does not exist, try corresponding
2253 * FIXME: assumes all magic branches are of
2254 * form "n.n.n ... .0.n". I'll fix if somebody can
2255 * send me a method to get a magic branch tag with
2256 * the 0 in some other position -- <dan@gasboy.com>
2258 pa = strrchr (rev, '.');
2260 /* This might happen, for instance, if an RCS file only contained
2261 * revisions 2.x and higher, and REV == "1".
2263 error (1, 0, "revision `%s' does not exist", tag);
2266 pb = Xasprintf ("%s.%d.%s", rev, RCS_MAGIC_BRANCH, pa);
2269 if (RCS_exist_rev (rcs, rev))
2271 error (1, 0, "revision `%s' does not exist", tag);
2275 RCS_check_tag (tag); /* exit if not a valid tag */
2277 /* If tag is "HEAD", special case to get head RCS revision */
2278 if (tag && STREQ (tag, TAG_HEAD))
2279 return RCS_head (rcs);
2281 /* If valid tag let translate_symtag say yea or nay. */
2282 rev = translate_symtag (rcs, tag);
2287 /* Trust the caller to print warnings. */
2294 * Find the revision for a specific tag.
2295 * If force_tag_match is set, return NULL if an exact match is not
2296 * possible otherwise return RCS_head (). We are careful to look for
2297 * and handle "magic" revisions specially.
2299 * If the matched tag is a branch tag, find the head of the branch.
2301 * Returns pointer to newly malloc'd string, or NULL.
2304 RCS_gettag (RCSNode *rcs, const char *symtag, int force_tag_match,
2309 if (simple_tag != NULL)
2312 /* make sure we have something to look at... */
2313 assert (rcs != NULL);
2315 /* XXX this is probably not necessary, --jtc */
2316 if (rcs->flags & PARTIAL)
2317 RCS_reparsercsfile (rcs, NULL, NULL);
2319 /* If symtag is "HEAD", special case to get head RCS revision */
2320 if (symtag && STREQ (symtag, TAG_HEAD))
2321 #if 0 /* This #if 0 is only in the Cygnus code. Why? Death support? */
2322 if (force_tag_match && (rcs->flags & VALID) && (rcs->flags & INATTIC))
2323 return NULL; /* head request for removed file */
2326 return RCS_head (rcs);
2328 if (!isdigit ((unsigned char) symtag[0]))
2332 /* If we got a symbolic tag, resolve it to a numeric */
2333 version = translate_symtag (rcs, symtag);
2334 if (version != NULL)
2337 char *magic, *branch, *cp;
2342 * If this is a magic revision, we turn it into either its
2343 * physical branch equivalent (if one exists) or into
2344 * its base revision, which we assume exists.
2346 dots = numdots (tag);
2347 if (dots > 2 && (dots & 1) != 0)
2349 branch = strrchr (tag, '.');
2354 /* see if we have .magic-branch. (".0.") */
2355 magic = xmalloc (strlen (tag) + 1);
2356 (void) sprintf (magic, ".%d.", RCS_MAGIC_BRANCH);
2357 if (strncmp (magic, cp, strlen (magic)) == 0)
2359 /* it's magic. See if the branch exists */
2360 *cp = '\0'; /* turn it into a revision */
2361 (void) sprintf (magic, "%s.%s", tag, branch);
2362 branch = RCS_getbranch (rcs, magic, 1);
2376 /* The tag wasn't there, so return the head or NULL */
2377 if (force_tag_match)
2380 return RCS_head (rcs);
2384 tag = xstrdup (symtag);
2386 /* tag is always allocated and numeric now. */
2389 * numeric tag processing:
2390 * 1) revision number - just return it
2391 * 2) branch number - find head of branch
2394 /* strip trailing dots */
2395 while (tag[strlen (tag) - 1] == '.')
2396 tag[strlen (tag) - 1] = '\0';
2398 if ((numdots (tag) & 1) == 0)
2402 /* we have a branch tag, so we need to walk the branch */
2403 branch = RCS_getbranch (rcs, tag, force_tag_match);
2411 /* we have a revision tag, so make sure it exists */
2412 p = findnode (rcs->versions, tag);
2415 /* We have found a numeric revision for the revision tag.
2416 To support expanding the RCS keyword Name, if
2417 SIMPLE_TAG is not NULL, tell the the caller that this
2418 is a simple tag which co will recognize. FIXME: Are
2419 there other cases in which we should set this? In
2420 particular, what if we expand RCS keywords internally
2421 without calling co? */
2422 if (simple_tag != NULL)
2428 /* The revision wasn't there, so return the head or NULL */
2430 if (force_tag_match)
2433 return RCS_head (rcs);
2441 * Return a "magic" revision as a virtual branch off of REV for the RCS file.
2442 * A "magic" revision is one which is unique in the RCS file. By unique, I
2443 * mean we return a revision which:
2444 * - has a branch of 0 (see rcs.h RCS_MAGIC_BRANCH)
2445 * - has a revision component which is not an existing branch off REV
2446 * - has a revision component which is not an existing magic revision
2447 * - is an even-numbered revision, to avoid conflicts with vendor branches
2448 * The first point is what makes it "magic".
2450 * As an example, if we pass in 1.37 as REV, we will look for an existing
2451 * branch called 1.37.2. If it did not exist, we would look for an
2452 * existing symbolic tag with a numeric part equal to 1.37.0.2. If that
2453 * didn't exist, then we know that the 1.37.2 branch can be reserved by
2454 * creating a symbolic tag with 1.37.0.2 as the numeric part.
2456 * This allows us to fork development with very little overhead -- just a
2457 * symbolic tag is used in the RCS file. When a commit is done, a physical
2458 * branch is dynamically created to hold the new revision.
2460 * Note: We assume that REV is an RCS revision and not a branch number.
2462 static char *check_rev;
2464 RCS_magicrev (RCSNode *rcs, char *rev)
2467 char *xrev, *test_branch, *local_branch_num;
2469 xrev = xmalloc (strlen (rev) + 14); /* enough for .0.number */
2472 local_branch_num = getenv("CVS_LOCAL_BRANCH_NUM");
2473 if (local_branch_num)
2475 rev_num = atoi(local_branch_num);
2484 /* only look at even numbered branches */
2485 for ( ; ; rev_num += 2)
2487 /* see if the physical branch exists */
2488 (void) sprintf (xrev, "%s.%d", rev, rev_num);
2489 test_branch = RCS_getbranch (rcs, xrev, 1);
2490 if (test_branch != NULL) /* it did, so keep looking */
2496 /* now, create a "magic" revision */
2497 (void) sprintf (xrev, "%s.%d.%d", rev, RCS_MAGIC_BRANCH, rev_num);
2499 /* walk the symbols list to see if a magic one already exists */
2500 if (walklist (RCS_symbols(rcs), checkmagic_proc, NULL) != 0)
2503 /* we found a free magic branch. Claim it as ours */
2511 * walklist proc to look for a match in the symbols list.
2512 * Returns 0 if the symbol does not match, 1 if it does.
2515 checkmagic_proc (Node *p, void *closure)
2517 if (STREQ (check_rev, p->data))
2526 * Given an RCSNode, returns non-zero if the specified revision number
2527 * or symbolic tag resolves to a "branch" within the rcs file.
2529 * FIXME: this is the same as RCS_nodeisbranch except for the special
2530 * case for handling a null rcsnode.
2533 RCS_isbranch (RCSNode *rcs, const char *rev)
2535 /* numeric revisions are easy -- even number of dots is a branch */
2536 if (isdigit ((unsigned char) *rev))
2537 return (numdots (rev) & 1) == 0;
2539 /* assume a revision if you can't find the RCS info */
2543 /* now, look for a match in the symbols list */
2544 return RCS_nodeisbranch (rcs, rev);
2550 * Given an RCSNode, returns non-zero if the specified revision number
2551 * or symbolic tag resolves to a "branch" within the rcs file. We do
2552 * take into account any magic branches as well.
2555 RCS_nodeisbranch (RCSNode *rcs, const char *rev)
2560 assert (rcs != NULL);
2562 /* numeric revisions are easy -- even number of dots is a branch */
2563 if (isdigit ((unsigned char) *rev))
2564 return (numdots (rev) & 1) == 0;
2566 version = translate_symtag (rcs, rev);
2567 if (version == NULL)
2569 dots = numdots (version);
2570 if ((dots & 1) == 0)
2576 /* got a symbolic tag match, but it's not a branch; see if it's magic */
2580 char *branch = strrchr (version, '.');
2581 char *cp = branch - 1;
2585 /* see if we have .magic-branch. (".0.") */
2586 magic = Xasprintf (".%d.", RCS_MAGIC_BRANCH);
2587 if (strncmp (magic, cp, strlen (magic)) == 0)
2602 * Returns a pointer to malloc'ed memory which contains the branch
2603 * for the specified *symbolic* tag. Magic branches are handled correctly.
2606 RCS_whatbranch (RCSNode *rcs, const char *rev)
2611 /* assume no branch if you can't find the RCS info */
2615 /* now, look for a match in the symbols list */
2616 version = translate_symtag (rcs, rev);
2617 if (version == NULL)
2619 dots = numdots (version);
2620 if ((dots & 1) == 0)
2623 /* got a symbolic tag match, but it's not a branch; see if it's magic */
2627 char *branch = strrchr (version, '.');
2628 char *cp = branch++ - 1;
2632 /* see if we have .magic-branch. (".0.") */
2633 magic = xmalloc (strlen (version) + 1);
2634 (void) sprintf (magic, ".%d.", RCS_MAGIC_BRANCH);
2635 if (strncmp (magic, cp, strlen (magic)) == 0)
2637 /* yep. it's magic. now, construct the real branch */
2638 *cp = '\0'; /* turn it into a revision */
2639 (void) sprintf (magic, "%s.%s", version, branch);
2652 * Get the head of the specified branch. If the branch does not exist,
2653 * return NULL or RCS_head depending on force_tag_match.
2654 * Returns NULL or a newly malloc'd string.
2657 RCS_getbranch (RCSNode *rcs, const char *tag, int force_tag_match)
2665 /* make sure we have something to look at... */
2666 assert (rcs != NULL);
2668 if (rcs->flags & PARTIAL)
2669 RCS_reparsercsfile (rcs, NULL, NULL);
2671 /* find out if the tag contains a dot, or is on the trunk */
2672 cp = strrchr (tag, '.');
2674 /* trunk processing is the special case */
2677 xtag = Xasprintf ("%s.", tag);
2678 for (cp = rcs->head; cp != NULL;)
2680 if (strncmp (xtag, cp, strlen (xtag)) == 0)
2682 p = findnode (rcs->versions, cp);
2686 if (force_tag_match)
2689 return RCS_head (rcs);
2697 if (force_tag_match)
2700 return RCS_head (rcs);
2702 return xstrdup (cp);
2705 /* if it had a `.', terminate the string so we have the base revision */
2708 /* look up the revision this branch is based on */
2709 p = findnode (rcs->versions, tag);
2711 /* put the . back so we have the branch again */
2716 /* if the base revision didn't exist, return head or NULL */
2717 if (force_tag_match)
2720 return RCS_head (rcs);
2723 /* find the first element of the branch we are looking for */
2725 if (vn->branches == NULL)
2727 xtag = Xasprintf ("%s.", tag);
2728 head = vn->branches->list;
2729 for (p = head->next; p != head; p = p->next)
2730 if (strncmp (p->key, xtag, strlen (xtag)) == 0)
2736 /* we didn't find a match so return head or NULL */
2737 if (force_tag_match)
2740 return RCS_head (rcs);
2743 /* now walk the next pointers of the branch */
2747 p = findnode (rcs->versions, nextvers);
2750 /* a link in the chain is missing - return head or NULL */
2751 if (force_tag_match)
2754 return RCS_head (rcs);
2757 nextvers = vn->next;
2758 } while (nextvers != NULL);
2760 /* we have the version in our hand, so go for it */
2761 return xstrdup (vn->version);
2766 /* Returns the head of the branch which REV is on. REV can be a
2767 branch tag or non-branch tag; symbolic or numeric.
2769 Returns a newly malloc'd string. Returns NULL if a symbolic name
2772 RCS_branch_head (RCSNode *rcs, char *rev)
2778 assert (rcs != NULL);
2780 if (RCS_nodeisbranch (rcs, rev))
2781 return RCS_getbranch (rcs, rev, 1);
2783 if (isdigit ((unsigned char) *rev))
2784 num = xstrdup (rev);
2787 num = translate_symtag (rcs, rev);
2791 br = truncate_revnum (num);
2792 retval = RCS_getbranch (rcs, br, 1);
2800 /* Get the branch point for a particular branch, that is the first
2801 revision on that branch. For example, RCS_getbranchpoint (rcs,
2802 "1.3.2") will normally return "1.3.2.1". TARGET may be either a
2803 branch number or a revision number; if a revnum, find the
2804 branchpoint of the branch to which TARGET belongs.
2806 Return RCS_head if TARGET is on the trunk or if the root node could
2807 not be found (this is sort of backwards from our behavior on a branch;
2808 the rationale is that the return value is a revision from which you
2809 can start walking the next fields and end up at TARGET).
2810 Return NULL on error. */
2812 RCS_getbranchpoint (RCSNode *rcs, char *target)
2817 int dots, isrevnum, brlen;
2819 dots = numdots (target);
2820 isrevnum = dots & 1;
2823 /* TARGET is a trunk revision; return rcs->head. */
2824 return RCS_head (rcs);
2826 /* Get the revision number of the node at which TARGET's branch is
2827 rooted. If TARGET is a branch number, lop off the last field;
2828 if it's a revision number, lop off the last *two* fields. */
2829 branch = xstrdup (target);
2830 bp = strrchr (branch, '.');
2832 error (1, 0, "%s: confused revision number %s",
2833 rcs->print_path, target);
2835 while (*--bp != '.')
2839 vp = findnode (rcs->versions, branch);
2842 error (0, 0, "%s: can't find branch point %s", rcs->print_path, target);
2849 while (*bp && *bp != '.')
2851 brlen = bp - branch;
2853 vp = rev->branches->list->next;
2854 while (vp != rev->branches->list)
2856 /* BRANCH may be a genuine branch number, e.g. `1.1.3', or
2857 maybe a full revision number, e.g. `1.1.3.6'. We have
2858 found our branch point if the first BRANCHLEN characters
2859 of the revision number match, *and* if the following
2860 character is a dot. */
2861 if (strncmp (vp->key, branch, brlen) == 0 && vp->key[brlen] == '.')
2867 if (vp == rev->branches->list)
2869 error (0, 0, "%s: can't find branch point %s", rcs->print_path, target);
2873 return xstrdup (vp->key);
2879 * Get the head of the RCS file. If branch is set, this is the head of the
2880 * branch, otherwise the real head.
2883 * rcs The parsed rcs node information.
2886 * NULL when rcs->branch exists and cannot be found.
2887 * A newly malloc'd string, otherwise.
2890 RCS_head (RCSNode *rcs)
2892 /* make sure we have something to look at... */
2896 * NOTE: we call getbranch with force_tag_match set to avoid any
2897 * possibility of recursion
2900 return RCS_getbranch (rcs, rcs->branch, 1);
2902 return xstrdup (rcs->head);
2908 * Get the most recent revision, based on the supplied date, but use some
2909 * funky stuff and follow the vendor branch maybe
2912 RCS_getdate (RCSNode *rcs, const char *date, int force_tag_match)
2914 char *cur_rev = NULL;
2915 char *retval = NULL;
2917 RCSVers *vers = NULL;
2919 /* make sure we have something to look at... */
2920 assert (rcs != NULL);
2922 if (rcs->flags & PARTIAL)
2923 RCS_reparsercsfile (rcs, NULL, NULL);
2925 /* if the head is on a branch, try the branch first */
2926 if (rcs->branch != NULL)
2928 retval = RCS_getdatebranch (rcs, date, rcs->branch);
2933 /* otherwise if we have a trunk, try it */
2936 p = findnode (rcs->versions, rcs->head);
2939 error (0, 0, "%s: head revision %s doesn't exist", rcs->print_path,
2944 /* if the date of this one is before date, take it */
2946 if (RCS_datecmp (vers->date, date) <= 0)
2948 cur_rev = vers->version;
2952 /* if there is a next version, find the node */
2953 if (vers->next != NULL)
2954 p = findnode (rcs->versions, vers->next);
2960 error (0, 0, "%s: no head revision", rcs->print_path);
2963 * at this point, either we have the revision we want, or we have the
2964 * first revision on the trunk (1.1?) in our hands, or we've come up
2968 /* if we found what we're looking for, and it's not 1.1 return it */
2969 if (cur_rev != NULL)
2971 if (! STREQ (cur_rev, "1.1"))
2972 return xstrdup (cur_rev);
2974 /* This is 1.1; if the date of 1.1 is not the same as that for the
2975 1.1.1.1 version, then return 1.1. This happens when the first
2976 version of a file is created by a regular cvs add and commit,
2977 and there is a subsequent cvs import of the same file. */
2978 p = findnode (rcs->versions, "1.1.1.1");
2981 char *date_1_1 = vers->date;
2984 if (RCS_datecmp (vers->date, date_1_1) != 0)
2985 return xstrdup ("1.1");
2989 /* look on the vendor branch */
2990 retval = RCS_getdatebranch (rcs, date, CVSBRANCH);
2993 * if we found a match, return it; otherwise, we return the first
2994 * revision on the trunk or NULL depending on force_tag_match and the
2995 * date of the first rev
3000 if (vers && (!force_tag_match || RCS_datecmp (vers->date, date) <= 0))
3001 return xstrdup (vers->version);
3009 * Look up the last element on a branch that was put in before or on
3010 * the specified date and time (return the rev or NULL)
3013 RCS_getdatebranch (RCSNode *rcs, const char *date, const char *branch)
3015 char *cur_rev = NULL;
3017 char *xbranch, *xrev;
3021 /* look up the first revision on the branch */
3022 xrev = xstrdup (branch);
3023 cp = strrchr (xrev, '.');
3029 *cp = '\0'; /* turn it into a revision */
3031 assert (rcs != NULL);
3033 if (rcs->flags & PARTIAL)
3034 RCS_reparsercsfile (rcs, NULL, NULL);
3036 p = findnode (rcs->versions, xrev);
3042 /* Tentatively use this revision, if it is early enough. */
3043 if (RCS_datecmp (vers->date, date) <= 0)
3044 cur_rev = vers->version;
3046 /* If no branches list, return now. This is what happens if the branch
3047 is a (magic) branch with no revisions yet. */
3048 if (vers->branches == NULL)
3049 return xstrdup (cur_rev);
3051 /* walk the branches list looking for the branch number */
3052 xbranch = Xasprintf ("%s.", branch);
3053 for (p = vers->branches->list->next; p != vers->branches->list; p = p->next)
3054 if (strncmp (p->key, xbranch, strlen (xbranch)) == 0)
3057 if (p == vers->branches->list)
3059 /* This is what happens if the branch is a (magic) branch with
3060 no revisions yet. Similar to the case where vers->branches ==
3061 NULL, except here there was a another branch off the same
3063 return xstrdup (cur_rev);
3066 p = findnode (rcs->versions, p->key);
3068 /* walk the next pointers until you find the end, or the date is too late */
3072 if (RCS_datecmp (vers->date, date) <= 0)
3073 cur_rev = vers->version;
3077 /* if there is a next version, find the node */
3078 if (vers->next != NULL)
3079 p = findnode (rcs->versions, vers->next);
3084 /* Return whatever we found, which may be NULL. */
3085 return xstrdup (cur_rev);
3091 * Compare two dates in RCS format. Beware the change in format on January 1,
3092 * 2000, when years go from 2-digit to full format.
3095 RCS_datecmp (const char *date1, const char *date2)
3097 int length_diff = strlen (date1) - strlen (date2);
3099 return length_diff ? length_diff : strcmp (date1, date2);
3104 /* Look up revision REV in RCS and return the date specified for the
3105 revision minus FUDGE seconds (FUDGE will generally be one, so that the
3106 logically previous revision will be found later, or zero, if we want
3109 The return value is the date being returned as a time_t, or (time_t)-1
3110 on error (previously was documented as zero on error; I haven't checked
3111 the callers to make sure that they really check for (time_t)-1, but
3112 the latter is what this function really returns). If DATE is non-NULL,
3113 then it must point to MAXDATELEN characters, and we store the same
3114 return value there in DATEFORM format. */
3116 RCS_getrevtime (RCSNode *rcs, const char *rev, char *date, int fudge)
3119 struct tm xtm, *ftm;
3120 struct timespec revdate;
3124 /* make sure we have something to look at... */
3125 assert (rcs != NULL);
3127 if (rcs->flags & PARTIAL)
3128 RCS_reparsercsfile (rcs, NULL, NULL);
3130 /* look up the revision */
3131 p = findnode (rcs->versions, rev);
3136 /* split up the date */
3137 if (sscanf (vers->date, SDATEFORM, &xtm.tm_year, &xtm.tm_mon,
3138 &xtm.tm_mday, &xtm.tm_hour, &xtm.tm_min, &xtm.tm_sec) != 6)
3139 error (1, 0, "%s: invalid date for revision %s (%s)", rcs->print_path,
3142 /* If the year is from 1900 to 1999, RCS files contain only two
3143 digits, and sscanf gives us a year from 0-99. If the year is
3144 2000+, RCS files contain all four digits and we subtract 1900,
3145 because the tm_year field should contain years since 1900. */
3147 if (xtm.tm_year >= 100 && xtm.tm_year < 2000)
3148 error (0, 0, "%s: non-standard date format for revision %s (%s)",
3149 rcs->print_path, rev, vers->date);
3150 if (xtm.tm_year >= 1900)
3151 xtm.tm_year -= 1900;
3153 /* put the date in a form getdate can grok */
3154 tdate = Xasprintf ("%d-%d-%d %d:%d:%d -0000",
3155 xtm.tm_year + 1900, xtm.tm_mon, xtm.tm_mday,
3156 xtm.tm_hour, xtm.tm_min, xtm.tm_sec);
3158 /* Turn it into seconds since the epoch.
3160 * We use a struct timespec since that is what getdate requires, then
3161 * truncate the nanoseconds.
3163 if (!get_date (&revdate, tdate, NULL))
3170 revdate.tv_sec -= fudge; /* remove "fudge" seconds */
3173 /* Put an appropriate string into `date', if we were given one. */
3174 ftm = gmtime (&revdate.tv_sec);
3175 (void) sprintf (date, DATEFORM,
3176 ftm->tm_year + (ftm->tm_year < 100 ? 0 : 1900),
3177 ftm->tm_mon + 1, ftm->tm_mday, ftm->tm_hour,
3178 ftm->tm_min, ftm->tm_sec);
3181 return revdate.tv_sec;
3187 RCS_getlocks (RCSNode *rcs)
3189 assert(rcs != NULL);
3191 if (rcs->flags & PARTIAL)
3192 RCS_reparsercsfile (rcs, NULL, NULL);
3194 if (rcs->locks_data) {
3195 rcs->locks = getlist ();
3196 do_locks (rcs->locks, rcs->locks_data);
3197 free(rcs->locks_data);
3198 rcs->locks_data = NULL;
3207 RCS_symbols(RCSNode *rcs)
3209 assert(rcs != NULL);
3211 if (rcs->flags & PARTIAL)
3212 RCS_reparsercsfile (rcs, NULL, NULL);
3214 if (rcs->symbols_data) {
3215 rcs->symbols = getlist ();
3216 do_symbols (rcs->symbols, rcs->symbols_data);
3217 free(rcs->symbols_data);
3218 rcs->symbols_data = NULL;
3221 return rcs->symbols;
3227 * Return the version associated with a particular symbolic tag.
3228 * Returns NULL or a newly malloc'd string.
3231 translate_symtag (RCSNode *rcs, const char *tag)
3233 if (rcs->flags & PARTIAL)
3234 RCS_reparsercsfile (rcs, NULL, NULL);
3236 if (rcs->symbols != NULL)
3240 /* The symbols have already been converted into a list. */
3241 p = findnode (rcs->symbols, tag);
3245 return xstrdup (p->data);
3248 if (rcs->symbols_data != NULL)
3253 /* Look through the RCS symbols information. This is like
3254 do_symbols, but we don't add the information to a list. In
3255 most cases, we will only be called once for this file, so
3256 generating the list is unnecessary overhead. */
3259 cp = rcs->symbols_data;
3260 /* Keeping track of LAST below isn't strictly necessary, now that tags
3261 * should be parsed for validity before they are accepted, but tags
3262 * with spaces used to cause the code below to loop indefintely, so
3263 * I have corrected for that. Now, in the event that I missed
3264 * something, the server cannot be hung. -DRP
3267 while ((cp = strchr (cp, tag[0])) != NULL)
3269 if (cp == last) break;
3270 if ((cp == rcs->symbols_data || whitespace (cp[-1]))
3271 && strncmp (cp, tag, len) == 0
3276 /* We found the tag. Return the version number. */
3280 while (! whitespace (*cp) && *cp != '\0')
3282 r = xmalloc (cp - v + 1);
3283 strncpy (r, v, cp - v);
3288 while (! whitespace (*cp) && *cp != '\0')
3302 * The argument ARG is the getopt remainder of the -k option specified on the
3303 * command line. This function returns malloc'ed space that can be used
3304 * directly in calls to RCS V5, with the -k flag munged correctly.
3307 RCS_check_kflag (const char *arg)
3309 static const char *const keyword_usage[] =
3311 "%s %s: invalid RCS keyword expansion mode\n",
3312 "Valid expansion modes include:\n",
3313 " -kkv\tGenerate keywords using the default form.\n",
3314 " -kkvl\tLike -kkv, except locker's name inserted.\n",
3315 " -kk\tGenerate only keyword names in keyword strings.\n",
3316 " -kv\tGenerate only keyword values in keyword strings.\n",
3317 " -ko\tGenerate the old keyword string (no changes from checked in file).\n",
3318 " -kb\tGenerate binary file unmodified (merges not allowed) (RCS 5.7).\n",
3319 "(Specify the --help global option for a list of other help options)\n",
3322 char const *const *cpp = NULL;
3326 for (cpp = kflags; *cpp != NULL; cpp++)
3328 if (STREQ (arg, *cpp))
3333 if (arg == NULL || *cpp == NULL)
3335 usage (keyword_usage);
3338 return Xasprintf ("-k%s", *cpp);
3344 * Do some consistency checks on the symbolic tag... These should equate
3345 * pretty close to what RCS checks, though I don't know for certain.
3348 RCS_check_tag (const char *tag)
3350 char *invalid = "$,.:;@"; /* invalid RCS tag characters */
3354 * The first character must be an alphabetic letter. The remaining
3355 * characters cannot be non-visible graphic characters, and must not be
3356 * in the set of "invalid" RCS identifier characters.
3358 if (isalpha ((unsigned char) *tag))
3360 for (cp = tag; *cp; cp++)
3362 if (!isgraph ((unsigned char) *cp))
3363 error (1, 0, "tag `%s' has non-visible graphic characters",
3365 if (strchr (invalid, *cp))
3366 error (1, 0, "tag `%s' must not contain the characters `%s'",
3371 error (1, 0, "tag `%s' must start with a letter", tag);
3377 * TRUE if argument has valid syntax for an RCS revision or
3378 * branch number. All characters must be digits or dots, first
3379 * and last characters must be digits, and no two consecutive
3380 * characters may be dots.
3382 * Intended for classifying things, so this function doesn't
3386 RCS_valid_rev (const char *rev)
3390 if (!isdigit ((unsigned char) last))
3392 while ((c = *rev++)) /* Extra parens placate -Wall gcc option */
3401 if (!isdigit ((unsigned char) c))
3404 if (!isdigit ((unsigned char) last))
3412 * Return true if RCS revision with TAG is a dead revision.
3415 RCS_isdead (RCSNode *rcs, const char *tag)
3420 if (rcs->flags & PARTIAL)
3421 RCS_reparsercsfile (rcs, NULL, NULL);
3423 p = findnode (rcs->versions, tag);
3428 return version->dead;
3433 /* Return the RCS keyword expansion mode. For example "b" for binary.
3434 Returns a pointer into storage which is allocated and freed along with
3435 the rest of the RCS information; the caller should not modify this
3436 storage. Returns NULL if the RCS file does not specify a keyword
3437 expansion mode; for all other errors, die with a fatal error. */
3439 RCS_getexpand (RCSNode *rcs)
3441 /* Since RCS_parsercsfile_i now reads expand, don't need to worry
3442 about RCS_reparsercsfile. */
3443 assert (rcs != NULL);
3449 /* Set keyword expansion mode to EXPAND. For example "b" for binary. */
3451 RCS_setexpand (RCSNode *rcs, const char *expand)
3453 /* Since RCS_parsercsfile_i now reads expand, don't need to worry
3454 about RCS_reparsercsfile. */
3455 assert (rcs != NULL);
3456 if (rcs->expand != NULL)
3458 rcs->expand = xstrdup (expand);
3463 /* RCS keywords, and a matching enum. */
3484 enum keyword expandto;
3490 static inline struct rcs_keyword *
3493 struct rcs_keyword *new;
3494 new = xcalloc (KEYWORD_LOCALID + 2, sizeof (struct rcs_keyword));
3496 #define KEYWORD_INIT(k, i, s) \
3498 k[i].len = sizeof s - 1; \
3499 k[i].expandto = i; \
3500 k[i].expandit = true
3502 KEYWORD_INIT (new, KEYWORD_AUTHOR, "Author");
3503 KEYWORD_INIT (new, KEYWORD_DATE, "Date");
3504 KEYWORD_INIT (new, KEYWORD_CVSHEADER, "CVSHeader");
3505 KEYWORD_INIT (new, KEYWORD_HEADER, "Header");
3506 KEYWORD_INIT (new, KEYWORD_ID, "Id");
3507 KEYWORD_INIT (new, KEYWORD_LOCKER, "Locker");
3508 KEYWORD_INIT (new, KEYWORD_LOG, "Log");
3509 KEYWORD_INIT (new, KEYWORD_NAME, "Name");
3510 KEYWORD_INIT (new, KEYWORD_RCSFILE, "RCSfile");
3511 KEYWORD_INIT (new, KEYWORD_REVISION, "Revision");
3512 KEYWORD_INIT (new, KEYWORD_SOURCE, "Source");
3513 KEYWORD_INIT (new, KEYWORD_STATE, "State");
3515 /* Per default, expand local keyword like Id */
3516 new[KEYWORD_LOCALID].expandto = KEYWORD_ID;
3524 free_keywords (void *keywords)
3531 /* Convert an RCS date string into a readable string. This is like
3532 the RCS date2str function. */
3534 printable_date (const char *rcs_date)
3536 int year, mon, mday, hour, min, sec;
3539 (void) sscanf (rcs_date, SDATEFORM, &year, &mon, &mday, &hour, &min,
3543 sprintf (buf, "%04d/%02d/%02d %02d:%02d:%02d", year, mon, mday,
3545 return xstrdup (buf);
3550 /* Escape the characters in a string so that it can be included in an
3553 escape_keyword_value (const char *value, int *free_value)
3558 for (s = value; *s != '\0'; s++)
3576 return (char *) value;
3579 ret = xmalloc (strlen (value) * 4 + 1);
3582 for (s = value, t = ret; *s != '\0'; s++, t++)
3623 /* Expand RCS keywords in the memory buffer BUF of length LEN. This
3624 applies to file RCS and version VERS. If NAME is not NULL, and is
3625 not a numeric revision, then it is the symbolic tag used for the
3626 checkout. EXPAND indicates how to expand the keywords. This
3627 function sets *RETBUF and *RETLEN to the new buffer and length.
3628 This function may modify the buffer BUF. If BUF != *RETBUF, then
3629 RETBUF is a newly allocated buffer. */
3631 expand_keywords (RCSNode *rcs, RCSVers *ver, const char *name, const char *log,
3632 size_t loglen, enum kflag expand, char *buf, size_t len,
3633 char **retbuf, size_t *retlen)
3635 struct expand_buffer
3637 struct expand_buffer *next;
3642 struct expand_buffer *ebuf_last = NULL;
3643 size_t ebuf_len = 0;
3645 char *srch, *srch_next;
3647 const struct rcs_keyword *keywords;
3649 if (!config /* For `cvs init', config may not be set. */
3650 ||expand == KFLAG_O || expand == KFLAG_B)
3657 if (!config->keywords) config->keywords = new_keywords ();
3658 keywords = config->keywords;
3660 /* If we are using -kkvl, dig out the locker information if any. */
3662 if (expand == KFLAG_KVL)
3665 lock = findnode (RCS_getlocks(rcs), ver->version);
3667 locker = xstrdup (lock->data);
3670 /* RCS keywords look like $STRING$ or $STRING: VALUE$. */
3673 while ((srch_next = memchr (srch, '$', srch_len)) != NULL)
3677 const struct rcs_keyword *keyword;
3683 srch_len -= (srch_next + 1) - srch;
3684 srch = srch_next + 1;
3686 /* Look for the first non alphabetic character after the '$'. */
3687 send = srch + srch_len;
3688 for (s = srch; s < send; s++)
3689 if (! isalpha ((unsigned char) *s))
3692 /* If the first non alphabetic character is not '$' or ':',
3693 then this is not an RCS keyword. */
3694 if (s == send || (*s != '$' && *s != ':'))
3697 /* See if this is one of the keywords. */
3699 for (keyword = keywords; keyword->string != NULL; keyword++)
3701 if (keyword->expandit
3702 && keyword->len == slen
3703 && strncmp (keyword->string, srch, slen) == 0)
3708 if (keyword->string == NULL)
3711 /* If the keyword ends with a ':', then the old value consists
3712 of the characters up to the next '$'. If there is no '$'
3713 before the end of the line, though, then this wasn't an RCS
3714 keyword after all. */
3717 for (; s < send; s++)
3718 if (*s == '$' || *s == '\n')
3720 if (s == send || *s != '$')
3724 /* At this point we must replace the string from SRCH to S
3725 with the expansion of the keyword KW. */
3727 /* Get the value to use. */
3729 if (expand == KFLAG_K)
3733 switch (keyword->expandto)
3736 assert (!"unreached");
3738 case KEYWORD_AUTHOR:
3739 value = ver->author;
3743 value = printable_date (ver->date);
3747 case KEYWORD_CVSHEADER:
3748 case KEYWORD_HEADER:
3750 case KEYWORD_LOCALID:
3758 if (keyword->expandto == KEYWORD_HEADER)
3759 path = rcs->print_path;
3760 else if (keyword->expandto == KEYWORD_CVSHEADER)
3761 path = getfullCVSname (rcs->print_path, &old_path);
3763 path = last_component (rcs->print_path);
3764 path = escape_keyword_value (path, &free_path);
3765 date = printable_date (ver->date);
3766 value = Xasprintf ("%s %s %s %s %s%s%s",
3767 path, ver->version, date, ver->author,
3769 locker != NULL ? " " : "",
3770 locker != NULL ? locker : "");
3772 /* If free_path is set then we know we allocated path
3773 * and we can discard the const.
3775 free ((char *)path);
3783 case KEYWORD_LOCKER:
3788 case KEYWORD_RCSFILE:
3789 value = escape_keyword_value (last_component (rcs->print_path),
3794 if (name != NULL && ! isdigit ((unsigned char) *name))
3795 value = (char *) name;
3800 case KEYWORD_REVISION:
3801 value = ver->version;
3804 case KEYWORD_SOURCE:
3805 value = escape_keyword_value (rcs->print_path, &free_value);
3814 sub = xmalloc (keyword->len
3815 + (value == NULL ? 0 : strlen (value))
3817 if (expand == KFLAG_V)
3819 /* Decrement SRCH and increment S to remove the $
3828 strcpy (sub, keyword->string);
3829 sublen = strlen (keyword->string);
3830 if (expand != KFLAG_K)
3833 sub[sublen + 1] = ' ';
3839 strcpy (sub + sublen, value);
3840 sublen += strlen (value);
3842 if (expand != KFLAG_V && expand != KFLAG_K)
3852 /* The Log keyword requires special handling. This behaviour
3853 is taken from RCS 5.7. The special log message is what RCS
3855 if (keyword->expandto == KEYWORD_LOG
3856 && (sizeof "checked in with -k by " <= loglen
3858 || strncmp (log, "checked in with -k by ",
3859 sizeof "checked in with -k by " - 1) != 0))
3863 size_t leader_len, leader_sp_len;
3870 /* We are going to insert the trailing $ ourselves, before
3871 the log message, so we must remove it from S, if we
3872 haven't done so already. */
3873 if (expand != KFLAG_V)
3876 /* CVS never has empty log messages, but old RCS files might. */
3880 /* Find the start of the line. */
3883 while (start > buf && start[-1] != '\n'
3884 && leader_len <= xsum (config->MaxCommentLeaderLength,
3885 expand != KFLAG_V ? 1 : 0))
3891 if (expand != KFLAG_V)
3892 /* When automagically determined and !KFLAG_V, we wish to avoid
3893 * including the leading `$' of the Log keyword in our leader.
3897 /* If the automagically determined leader exceeds the limit set in
3898 * CVSROOT/config, try to use a fallback.
3900 if (leader_len > config->MaxCommentLeaderLength)
3902 if (config->UseArchiveCommentLeader && rcs->comment)
3904 leader = xstrdup (rcs->comment);
3905 leader_len = strlen (rcs->comment);
3910 "Skipping `$" "Log$' keyword due to excessive comment leader.");
3914 else /* leader_len <= config->MaxCommentLeaderLength */
3916 /* Copy the start of the line to use as a comment leader. */
3917 leader = xmalloc (leader_len);
3918 memcpy (leader, start, leader_len);
3921 leader_sp_len = leader_len;
3922 while (leader_sp_len > 0 && isspace (leader[leader_sp_len - 1]))
3925 /* RCS does some checking for an old style of Log here,
3926 but we don't bother. RCS issues a warning if it
3927 changes anything. */
3929 /* Count the number of newlines in the log message so that
3930 we know how many copies of the leader we will need. */
3932 logend = log + loglen;
3933 for (snl = log; snl < logend; snl++)
3937 /* If the log message did not end in a newline, increment
3938 * the newline count so we have space for the extra leader.
3939 * Failure to do so results in a buffer overrun.
3941 if (loglen && snl[-1] != '\n')
3944 date = printable_date (ver->date);
3945 sub = xrealloc (sub,
3948 + strlen (ver->version)
3950 + strlen (ver->author)
3952 /* Use CNL + 2 below: One leader for each log
3953 * line, plus the Revision/Author/Date line,
3954 * plus a trailing blank line.
3956 + (cnl + 2) * leader_len
3958 if (expand != KFLAG_V)
3965 memcpy (sub + sublen, leader, leader_len);
3966 sublen += leader_len;
3967 sprintf (sub + sublen, "Revision %s %s %s\n",
3968 ver->version, date, ver->author);
3969 sublen += strlen (sub + sublen);
3977 memcpy (sub + sublen, leader, leader_sp_len);
3978 sublen += leader_sp_len;
3987 memcpy (sub + sublen, leader, leader_len);
3988 sublen += leader_len;
3989 for (slnl = sl; slnl < logend && *slnl != '\n'; ++slnl)
3993 memcpy (sub + sublen, sl, slnl - sl);
3994 sublen += slnl - sl;
3995 if (slnl == logend && slnl[-1] != '\n')
3997 /* There was no EOL at the end of the log message. Add
4007 memcpy (sub + sublen, leader, leader_sp_len);
4008 sublen += leader_sp_len;
4013 /* Now SUB contains a string which is to replace the string
4014 from SRCH to S. SUBLEN is the length of SUB. */
4016 if (srch + sublen == s)
4018 memcpy (srch, sub, sublen);
4023 struct expand_buffer *ebuf;
4025 /* We need to change the size of the buffer. We build a
4026 list of expand_buffer structures. Each expand_buffer
4027 structure represents a portion of the final output. We
4028 concatenate them back into a single buffer when we are
4029 done. This minimizes the number of potentially large
4030 buffer copies we must do. */
4034 ebufs = xmalloc (sizeof *ebuf);
4037 ebufs->free_data = 0;
4038 ebuf_len = srch - buf;
4039 ebufs->len = ebuf_len;
4044 assert (srch >= ebuf_last->data);
4045 assert (srch <= ebuf_last->data + ebuf_last->len);
4046 ebuf_len -= ebuf_last->len - (srch - ebuf_last->data);
4047 ebuf_last->len = srch - ebuf_last->data;
4050 ebuf = xmalloc (sizeof *ebuf);
4053 ebuf->free_data = 1;
4055 ebuf_last->next = ebuf;
4059 ebuf = xmalloc (sizeof *ebuf);
4061 ebuf->len = srch_len - (s - srch);
4062 ebuf->free_data = 0;
4064 ebuf_last->next = ebuf;
4066 ebuf_len += srch_len - (s - srch);
4069 srch_len -= (s - srch);
4085 ret = xmalloc (ebuf_len);
4088 while (ebufs != NULL)
4090 struct expand_buffer *next;
4092 memcpy (ret, ebufs->data, ebufs->len);
4094 if (ebufs->free_data)
4105 /* Check out a revision from an RCS file.
4107 If PFN is not NULL, then ignore WORKFILE and SOUT. Call PFN zero
4108 or more times with the contents of the file. CALLERDAT is passed,
4109 uninterpreted, to PFN. (The current code will always call PFN
4110 exactly once for a non empty file; however, the current code
4111 assumes that it can hold the entire file contents in memory, which
4112 is not a good assumption, and might change in the future).
4114 Otherwise, if WORKFILE is not NULL, check out the revision to
4115 WORKFILE. However, if WORKFILE is not NULL, and noexec is set,
4116 then don't do anything.
4118 Otherwise, if WORKFILE is NULL, check out the revision to SOUT. If
4119 SOUT is RUN_TTY, then write the contents of the revision to
4120 standard output. When using SOUT, the output is generally a
4121 temporary file; don't bother to get the file modes correct. When
4122 NOEXEC is set, WORKFILEs are not written but SOUTs are.
4124 REV is the numeric revision to check out. It may be NULL, which
4125 means to check out the head of the default branch.
4127 If NAMETAG is not NULL, and is not a numeric revision, then it is
4128 the tag that should be used when expanding the RCS Name keyword.
4130 OPTIONS is a string such as "-kb" or "-kv" for keyword expansion
4131 options. It may be NULL to use the default expansion mode of the
4132 file, typically "-kkv".
4134 On an error which prevented checking out the file, either print a
4135 nonfatal error and return 1, or give a fatal error. On success,
4138 /* This function mimics the behavior of `rcs co' almost exactly. The
4139 chief difference is in its support for preserving file ownership,
4140 permissions, and special files across checkin and checkout -- see
4141 comments in RCS_checkin for some issues about this. -twp */
4143 RCS_checkout (RCSNode *rcs, const char *workfile, const char *rev,
4144 const char *nametag, const char *options, const char *sout,
4145 RCSCHECKOUTPROC pfn, void *callerdat)
4150 *ofp = NULL; /* Initialize since -Wall doesn't understand that
4151 * error (1, ...) does not return.
4154 struct rcsbuffer rcsbuf;
4162 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4163 uid_t rcs_owner = (uid_t) -1;
4164 gid_t rcs_group = (gid_t) -1;
4166 int change_rcs_owner_or_group = 0;
4167 int change_rcs_mode = 0;
4168 int special_file = 0;
4169 unsigned long devnum_long;
4173 TRACE (TRACE_FUNCTION, "RCS_checkout (%s, %s, %s, %s, %s)",
4175 rev != NULL ? rev : "",
4176 nametag != NULL ? nametag : "",
4177 options != NULL ? options : "",
4178 (pfn != NULL ? "(function)"
4179 : (workfile != NULL ? workfile
4180 : (sout != RUN_TTY ? sout
4183 assert (rev == NULL || isdigit ((unsigned char) *rev));
4185 if (noexec && !server_active && workfile != NULL)
4188 assert (sout == RUN_TTY || workfile == NULL);
4189 assert (pfn == NULL || (sout == RUN_TTY && workfile == NULL));
4191 /* Some callers, such as Checkin or remove_file, will pass us a
4193 if (rev != NULL && (numdots (rev) & 1) == 0)
4195 rev = RCS_getbranch (rcs, rev, 1);
4197 error (1, 0, "internal error: bad branch tag in checkout");
4201 if (rev == NULL || STREQ (rev, rcs->head))
4205 /* We want the head revision. Try to read it directly. */
4207 if (rcs->flags & PARTIAL)
4208 RCS_reparsercsfile (rcs, &fp, &rcsbuf);
4210 rcsbuf_cache_open (rcs, rcs->delta_pos, &fp, &rcsbuf);
4213 if (! rcsbuf_getrevnum (&rcsbuf, &key))
4214 error (1, 0, "unexpected EOF reading %s", rcs->print_path);
4215 while (rcsbuf_getkey (&rcsbuf, &key, &value))
4217 if (STREQ (key, "log"))
4222 "Duplicate log keyword found for head revision in RCS file.");
4225 log = rcsbuf_valcopy (&rcsbuf, value, 0, &loglen);
4227 else if (STREQ (key, "text"))
4236 error (0, 0, "internal error: cannot find head text");
4238 /* It's okay to discard the const when free_rev is set, because
4239 * we know we allocated it in this function.
4245 rcsbuf_valpolish (&rcsbuf, value, 0, &len);
4247 if (fstat (fileno (fp), &sb) < 0)
4248 error (1, errno, "cannot fstat %s", rcs->path);
4250 rcsbuf_cache (rcs, &rcsbuf);
4254 struct rcsbuffer *rcsbufp;
4256 /* It isn't the head revision of the trunk. We'll need to
4257 walk through the deltas. */
4260 if (rcs->flags & PARTIAL)
4261 RCS_reparsercsfile (rcs, &fp, &rcsbuf);
4265 /* If RCS_deltas didn't close the file, we could use fstat
4266 here too. Probably should change it thusly.... */
4267 if (stat (rcs->path, &sb) < 0)
4268 error (1, errno, "cannot stat %s", rcs->path);
4273 if (fstat (fileno (fp), &sb) < 0)
4274 error (1, errno, "cannot fstat %s", rcs->path);
4278 RCS_deltas (rcs, fp, rcsbufp, rev, RCS_FETCH, &value, &len,
4283 /* If OPTIONS is NULL or the empty string, then the old code would
4284 invoke the RCS co program with no -k option, which means that
4285 co would use the string we have stored in rcs->expand. */
4286 if ((options == NULL || options[0] == '\0') && rcs->expand == NULL)
4290 const char *ouroptions;
4291 const char * const *cpp;
4293 if (options != NULL && options[0] != '\0')
4295 assert (options[0] == '-' && options[1] == 'k');
4296 ouroptions = options + 2;
4299 ouroptions = rcs->expand;
4301 for (cpp = kflags; *cpp != NULL; cpp++)
4302 if (STREQ (*cpp, ouroptions))
4306 expand = (enum kflag) (cpp - kflags);
4310 "internal error: unsupported substitution string -k%s",
4316 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4317 /* Handle special files and permissions, if that is desired. */
4323 vp = findnode (rcs->versions, rev == NULL ? rcs->head : rev);
4325 error (1, 0, "internal error: no revision information for %s",
4326 rev == NULL ? rcs->head : rev);
4329 /* First we look for symlinks, which are simplest to handle. */
4330 info = findnode (vers->other_delta, "symlink");
4335 if (pfn != NULL || (workfile == NULL && sout == RUN_TTY))
4336 error (1, 0, "symbolic link %s:%s cannot be piped",
4337 rcs->path, vers->version);
4338 if (workfile == NULL)
4343 /* Remove `dest', just in case. It's okay to get ENOENT here,
4344 since we just want the file not to be there. (TODO: decide
4345 whether it should be considered an error for `dest' to exist
4346 at this point. If so, the unlink call should be removed and
4347 `symlink' should signal the error. -twp) */
4348 if (CVS_UNLINK (dest) < 0 && !existence_error (errno))
4349 error (1, errno, "cannot remove %s", dest);
4350 if (symlink (info->data, dest) < 0)
4351 error (1, errno, "cannot create symbolic link from %s to %s",
4352 dest, (char *)info->data);
4356 /* It's okay to discard the const when free_rev is set, because
4357 * we know we allocated it in this function.
4363 /* Next, we look at this file's hardlinks field, and see whether
4364 it is linked to any other file that has been checked out.
4365 If so, we don't do anything else -- just link it to that file.
4367 If we are checking out a file to a pipe or temporary storage,
4368 none of this should matter. Hence the `workfile != NULL'
4369 wrapper around the whole thing. -twp */
4371 if (workfile != NULL)
4373 List *links = vers->hardlinks;
4376 Node *uptodate_link;
4378 /* For each file in the hardlinks field, check to see
4379 if it exists, and if so, if it has been checked out
4380 this iteration. When walklist returns, uptodate_link
4381 should point to a hardlist node representing a file
4382 in `links' which has recently been checked out, or
4383 NULL if no file in `links' has yet been checked out. */
4385 uptodate_link = NULL;
4386 (void) walklist (links, find_checkedout_proc, &uptodate_link);
4389 /* If we've found a file that `workfile' is supposed to be
4390 linked to, and it has been checked out since CVS was
4391 invoked, then simply link workfile to that file and return.
4393 If one of these conditions is not met, then
4394 workfile is the first one in its hardlink group to
4395 be checked out, and we must continue with a full
4398 if (uptodate_link != NULL)
4400 struct hardlink_info *hlinfo = uptodate_link->data;
4402 if (link (uptodate_link->key, workfile) < 0)
4403 error (1, errno, "cannot link %s to %s",
4404 workfile, uptodate_link->key);
4405 hlinfo->checked_out = 1; /* probably unnecessary */
4409 /* It's okay to discard the const when free_rev is set,
4410 * because we know we allocated it in this function.
4418 info = findnode (vers->other_delta, "owner");
4421 change_rcs_owner_or_group = 1;
4422 rcs_owner = (uid_t) strtoul (info->data, NULL, 10);
4424 info = findnode (vers->other_delta, "group");
4427 change_rcs_owner_or_group = 1;
4428 rcs_group = (gid_t) strtoul (info->data, NULL, 10);
4430 info = findnode (vers->other_delta, "permissions");
4433 change_rcs_mode = 1;
4434 rcs_mode = (mode_t) strtoul (info->data, NULL, 8);
4436 info = findnode (vers->other_delta, "special");
4439 /* If the size of `devtype' changes, fix the sscanf call also */
4442 if (sscanf (info->data, "%15s %lu",
4443 devtype, &devnum_long) < 2)
4444 error (1, 0, "%s:%s has bad `special' newphrase %s",
4445 workfile, vers->version, (char *)info->data);
4446 devnum = devnum_long;
4447 if (STREQ (devtype, "character"))
4448 special_file = S_IFCHR;
4449 else if (STREQ (devtype, "block"))
4450 special_file = S_IFBLK;
4452 error (0, 0, "%s is a special file of unsupported type `%s'",
4453 workfile, (char *)info->data);
4456 #endif /* PRESERVE_PERMISSIONS_SUPPORT */
4458 if (expand != KFLAG_O && expand != KFLAG_B)
4462 /* Don't fetch the delta node again if we already have it. */
4465 vp = findnode (rcs->versions, rev == NULL ? rcs->head : rev);
4467 error (1, 0, "internal error: no revision information for %s",
4468 rev == NULL ? rcs->head : rev);
4471 expand_keywords (rcs, vp->data, nametag, log, loglen,
4472 expand, value, len, &newvalue, &len);
4474 if (newvalue != value)
4484 /* It's okay to discard the const when free_rev is set, because
4485 * we know we allocated it in this function.
4497 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4499 error (1, 0, "special file %s cannot be piped to anything",
4502 /* The PFN interface is very simple to implement right now, as
4503 we always have the entire file in memory. */
4505 pfn (callerdat, value, len);
4507 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4508 else if (special_file)
4513 /* Can send either to WORKFILE or to SOUT, as long as SOUT is
4518 if (sout == RUN_TTY)
4519 error (1, 0, "special file %s cannot be written to stdout",
4524 /* Unlink `dest', just in case. It's okay if this provokes a
4526 if (CVS_UNLINK (dest) < 0 && existence_error (errno))
4527 error (1, errno, "cannot remove %s", dest);
4528 if (mknod (dest, special_file, devnum) < 0)
4529 error (1, errno, "could not create special file %s",
4533 "cannot create %s: unable to create special files on this system",
4540 /* Not a special file: write to WORKFILE or SOUT. */
4541 if (workfile == NULL)
4543 if (sout == RUN_TTY)
4547 /* Symbolic links should be removed before replacement, so that
4548 `fopen' doesn't follow the link and open the wrong file. */
4550 if (unlink_file (sout) < 0)
4551 error (1, errno, "cannot remove %s", sout);
4552 ofp = CVS_FOPEN (sout, expand == KFLAG_B ? "wb" : "w");
4554 error (1, errno, "cannot open %s", sout);
4559 /* Output is supposed to go to WORKFILE, so we should open that
4560 file. Symbolic links should be removed first (see above). */
4561 if (islink (workfile))
4562 if (unlink_file (workfile) < 0)
4563 error (1, errno, "cannot remove %s", workfile);
4565 ofp = CVS_FOPEN (workfile, expand == KFLAG_B ? "wb" : "w");
4567 /* If the open failed because the existing workfile was not
4568 writable, try to chmod the file and retry the open. */
4569 if (ofp == NULL && errno == EACCES
4570 && isfile (workfile) && !iswritable (workfile))
4572 xchmod (workfile, 1);
4573 ofp = CVS_FOPEN (workfile, expand == KFLAG_B ? "wb" : "w");
4578 error (0, errno, "cannot open %s", workfile);
4585 if (workfile == NULL && sout == RUN_TTY)
4587 if (expand == KFLAG_B)
4588 cvs_output_binary (value, len);
4591 /* cvs_output requires the caller to check for zero
4594 cvs_output (value, len);
4599 /* NT 4.0 is said to have trouble writing 2099999 bytes
4600 (for example) in a single fwrite. So break it down
4601 (there is no need to be writing that much at once
4602 anyway; it is possible that LARGEST_FWRITE should be
4603 somewhat larger for good performance, but for testing I
4604 want to start with a small value until/unless a bigger
4605 one proves useful). */
4606 #define LARGEST_FWRITE 8192
4608 size_t nstep = (len < LARGEST_FWRITE ? len : LARGEST_FWRITE);
4613 if (fwrite (p, 1, nstep, ofp) != nstep)
4615 error (0, errno, "cannot write %s",
4618 : (sout != RUN_TTY ? sout : "stdout")));
4634 if (workfile != NULL)
4638 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4639 if (!special_file && fclose (ofp) < 0)
4641 error (0, errno, "cannot close %s", workfile);
4645 if (change_rcs_owner_or_group)
4647 if (chown (workfile, rcs_owner, rcs_group) < 0)
4648 error (0, errno, "could not change owner or group of %s",
4652 ret = chmod (workfile,
4655 : sb.st_mode & ~(S_IWRITE | S_IWGRP | S_IWOTH));
4657 if (fclose (ofp) < 0)
4659 error (0, errno, "cannot close %s", workfile);
4663 ret = chmod (workfile,
4664 sb.st_mode & ~(S_IWRITE | S_IWGRP | S_IWOTH));
4668 error (0, errno, "cannot change mode of file %s",
4672 else if (sout != RUN_TTY)
4675 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4680 error (0, errno, "cannot close %s", sout);
4685 #ifdef PRESERVE_PERMISSIONS_SUPPORT
4686 /* If we are in the business of preserving hardlinks, then
4687 mark this file as having been checked out. */
4688 if (preserve_perms && workfile != NULL)
4689 update_hardlink_info (workfile);
4697 /* Find the delta currently locked by the user. From the `ci' man page:
4699 "If rev is omitted, ci tries to derive the new revision
4700 number from the caller's last lock. If the caller has
4701 locked the tip revision of a branch, the new revision is
4702 appended to that branch. The new revision number is
4703 obtained by incrementing the tip revision number. If the
4704 caller locked a non-tip revision, a new branch is started
4705 at that revision by incrementing the highest branch number
4706 at that revision. The default initial branch and level
4709 If rev is omitted and the caller has no lock, but owns the
4710 file and locking is not set to strict, then the revision
4711 is appended to the default branch (normally the trunk; see
4712 the -b option of rcs(1))."
4714 RCS_findlock_or_tip finds the unique revision locked by the caller
4715 and returns its delta node. If the caller has not locked any
4716 revisions (and is permitted to commit to an unlocked delta, as
4717 described above), return the tip of the default branch. */
4719 RCS_findlock_or_tip (RCSNode *rcs)
4721 char *user = getcaller();
4725 /* Find unique delta locked by caller. This code is very similar
4726 to the code in RCS_unlock -- perhaps it could be abstracted
4727 into a RCS_findlock function. */
4728 locklist = RCS_getlocks (rcs);
4730 for (p = locklist->list->next; p != locklist->list; p = p->next)
4732 if (STREQ (p->data, user))
4737 %s: multiple revisions locked by %s; please specify one", rcs->print_path, user);
4746 /* Found an old lock, but check that the revision still exists. */
4747 p = findnode (rcs->versions, lock->key);
4750 error (0, 0, "%s: can't unlock nonexistent revision %s",
4758 /* No existing lock. The RCS rule is that this is an error unless
4759 locking is nonstrict AND the file is owned by the current
4760 user. Trying to determine the latter is a portability nightmare
4761 in the face of NT, VMS, AFS, and other systems with non-unix-like
4762 ideas of users and owners. In the case of CVS, we should never get
4763 here (as long as the traditional behavior of making sure to call
4764 RCS_lock persists). Anyway, we skip the RCS error checks
4765 and just return the default branch or head. The reasoning is that
4766 those error checks are to make users lock before a checkin, and we do
4767 that in other ways if at all anyway (e.g. rcslock.pl). */
4769 p = findnode (rcs->versions, RCS_getbranch (rcs, rcs->branch, 0));
4772 error (0, 0, "RCS file `%s' does not contain its default revision.",
4782 /* Revision number string, R, must contain a `.'.
4783 Return a newly-malloc'd copy of the prefix of R up
4784 to but not including the final `.'. */
4786 truncate_revnum (const char *r)
4790 char *dot = strrchr (r, '.');
4794 new_r = xmalloc (len + 1);
4795 memcpy (new_r, r, len);
4796 *(new_r + len) = '\0';
4802 /* Revision number string, R, must contain a `.'.
4803 R must be writable. Replace the rightmost `.' in R with
4804 the NUL byte and return a pointer to that NUL byte. */
4806 truncate_revnum_in_place (char *r)
4808 char *dot = strrchr (r, '.');
4816 /* Revision number strings, R and S, must each contain a `.'.
4817 R and S must be writable and must have the same number of dots.
4818 Truncate R and S for the comparison, then restored them to their
4820 Return the result (see compare_revnums) of comparing R and S
4821 ignoring differences in any component after the rightmost `.'. */
4823 compare_truncated_revnums (char *r, char *s)
4825 char *r_dot = truncate_revnum_in_place (r);
4826 char *s_dot = truncate_revnum_in_place (s);
4829 assert (numdots (r) == numdots (s));
4831 cmp = compare_revnums (r, s);
4841 /* Return a malloc'd copy of the string representing the highest branch
4842 number on BRANCHNODE. If there are no branches on BRANCHNODE, return NULL.
4843 FIXME: isn't the max rev always the last one?
4844 If so, we don't even need a loop. */
4846 max_rev (const RCSVers *branchnode)
4852 if (branchnode->branches == NULL)
4858 head = branchnode->branches->list;
4859 for (bp = head->next; bp != head; bp = bp->next)
4861 if (max == NULL || compare_truncated_revnums (max, bp->key) < 0)
4868 return truncate_revnum (max);
4873 /* Create BRANCH in RCS's delta tree. BRANCH may be either a branch
4874 number or a revision number. In the former case, create the branch
4875 with the specified number; in the latter case, create a new branch
4876 rooted at node BRANCH with a higher branch number than any others.
4877 Return the number of the tip node on the new branch. */
4879 RCS_addbranch (RCSNode *rcs, const char *branch)
4881 char *branchpoint, *newrevnum;
4884 RCSVers *branchnode;
4888 /* Append to end by default. */
4891 branchpoint = xstrdup (branch);
4892 if ((numdots (branchpoint) & 1) == 0)
4894 truncate_revnum_in_place (branchpoint);
4897 /* Find the branch rooted at BRANCHPOINT. */
4898 nodep = findnode (rcs->versions, branchpoint);
4901 error (0, 0, "%s: can't find branch point %s", rcs->print_path, branchpoint);
4906 branchnode = nodep->data;
4908 /* If BRANCH was a full branch number, make sure it is higher than MAX. */
4909 if ((numdots (branch) & 1) == 1)
4911 if (branchnode->branches == NULL)
4913 /* We have to create the first branch on this node, which means
4914 appending ".2" to the revision number. */
4915 newrevnum = Xasprintf ("%s.2", branch);
4919 char *max = max_rev (branchnode);
4921 newrevnum = increment_revnum (max);
4927 newrevnum = xstrdup (branch);
4929 if (branchnode->branches != NULL)
4934 /* Find the position of this new branch in the sorted list
4936 head = branchnode->branches->list;
4937 for (bp = head->next; bp != head; bp = bp->next)
4942 /* The existing list must be sorted on increasing revnum. */
4943 assert (bp->next == head
4944 || compare_truncated_revnums (bp->key,
4945 bp->next->key) < 0);
4946 dot = truncate_revnum_in_place (bp->key);
4947 found_pos = (compare_revnums (branch, bp->key) < 0);
4959 newrevnum = xrealloc (newrevnum, strlen (newrevnum) + 3);
4960 strcat (newrevnum, ".1");
4962 /* Add this new revision number to BRANCHPOINT's branches list. */
4963 if (branchnode->branches == NULL)
4964 branchnode->branches = getlist();
4966 bp->key = xstrdup (newrevnum);
4968 /* Append to the end of the list by default, that is, just before
4969 the header node, `list'. */
4971 marker = branchnode->branches->list;
4975 fail = insert_before (branchnode->branches, marker, bp);
4984 /* Check in to RCSFILE with revision REV (which must be greater than
4985 the largest revision) and message MESSAGE (which is checked for
4986 validity). If FLAGS & RCS_FLAGS_DEAD, check in a dead revision.
4987 If FLAGS & RCS_FLAGS_QUIET, tell ci to be quiet. If FLAGS &
4988 RCS_FLAGS_MODTIME, use the working file's modification time for the
4989 checkin time. WORKFILE is the working file to check in from, or
4990 NULL to use the usual RCS rules for deriving it from the RCSFILE.
4991 If FLAGS & RCS_FLAGS_KEEPFILE, don't unlink the working file;
4992 unlinking the working file is standard RCS behavior, but is rarely
4993 appropriate for CVS.
4995 UPDATE_DIR is used to print the path for the file. This argument is
4996 unnecessary when FLAGS & RCS_FLAGS_QUIET since the path won't be printed
4999 This function should almost exactly mimic the behavior of `rcs ci'. The
5000 principal point of difference is the support here for preserving file
5001 ownership and permissions in the delta nodes. This is not a clean
5002 solution -- precisely because it diverges from RCS's behavior -- but
5003 it doesn't seem feasible to do this anywhere else in the code. [-twp]
5005 Return value is -1 for error (and errno is set to indicate the
5006 error), positive for error (and an error message has been printed),
5007 or zero for success. */
5009 RCS_checkin (RCSNode *rcs, const char *update_dir, const char *workfile_in,
5010 const char *message, const char *rev, time_t citime, int flags)
5012 RCSVers *delta, *commitpt;
5015 char *tmpfile, *changefile;
5017 size_t darg_allocated = 0;
5018 char **dargv = NULL;
5020 int status, checkin_quiet;
5023 int adding_branch = 0;
5024 char *workfile = xstrdup (workfile_in);
5025 #ifdef PRESERVE_PERMISSIONS_SUPPORT
5032 if (rcs->flags & PARTIAL)
5033 RCS_reparsercsfile (rcs, NULL, NULL);
5035 /* Get basename of working file. Is there a library function to
5036 do this? I couldn't find one. -twp */
5037 if (workfile == NULL)
5040 int extlen = strlen (RCSEXT);
5042 workfile = xstrdup (last_component (rcs->path));
5043 p = workfile + (strlen (workfile) - extlen);
5044 assert (strncmp (p, RCSEXT, extlen) == 0);
5048 /* If the filename is a symbolic link, follow it and replace it
5049 with the destination of the link. We need to do this before
5050 calling rcs_internal_lockfile, or else we won't put the lock in
5052 resolve_symlink (&(rcs->path));
5054 checkin_quiet = flags & RCS_FLAGS_QUIET;
5055 if (!(checkin_quiet || really_quiet))
5057 cvs_output (rcs->path, 0);
5058 cvs_output (" <-- ", 7);
5059 if (update_dir && strlen (update_dir))
5061 cvs_output (update_dir, 0);
5062 cvs_output ("/", 1);
5064 cvs_output (workfile, 0);
5065 cvs_output ("\n", 1);
5068 /* Create new delta node. */
5069 delta = xmalloc (sizeof (RCSVers));
5070 memset (delta, 0, sizeof (RCSVers));
5071 delta->author = xstrdup (getcaller ());
5072 if (flags & RCS_FLAGS_MODTIME)
5075 if (stat (workfile, &ws) < 0)
5077 error (1, errno, "cannot stat %s", workfile);
5079 modtime = ws.st_mtime;
5081 else if (flags & RCS_FLAGS_USETIME)
5084 (void) time (&modtime);
5085 ftm = gmtime (&modtime);
5086 delta->date = Xasprintf (DATEFORM,
5087 ftm->tm_year + (ftm->tm_year < 100 ? 0 : 1900),
5088 ftm->tm_mon + 1, ftm->tm_mday, ftm->tm_hour,
5089 ftm->tm_min, ftm->tm_sec);
5090 if (flags & RCS_FLAGS_DEAD)
5092 delta->state = xstrdup (RCSDEAD);
5096 delta->state = xstrdup ("Exp");
5098 delta->other_delta = getlist();
5100 /* save the commit ID */
5102 np->type = RCSFIELD;
5103 np->key = xstrdup ("commitid");
5104 np->data = xstrdup(global_session_id);
5105 addnode (delta->other_delta, np);
5108 #ifdef PRESERVE_PERMISSIONS_SUPPORT
5109 /* If permissions should be preserved on this project, then
5110 save the permission info. */
5114 char buf[64]; /* static buffer should be safe: see usage. -twp */
5116 delta->other_delta = getlist();
5118 if (lstat (workfile, &sb) < 0)
5119 error (1, errno, "cannot lstat %s", workfile);
5121 if (S_ISLNK (sb.st_mode))
5124 np->type = RCSFIELD;
5125 np->key = xstrdup ("symlink");
5126 np->data = Xreadlink (workfile, sb.st_size);
5127 addnode (delta->other_delta, np);
5131 (void) sprintf (buf, "%u", sb.st_uid);
5133 np->type = RCSFIELD;
5134 np->key = xstrdup ("owner");
5135 np->data = xstrdup (buf);
5136 addnode (delta->other_delta, np);
5138 (void) sprintf (buf, "%u", sb.st_gid);
5140 np->type = RCSFIELD;
5141 np->key = xstrdup ("group");
5142 np->data = xstrdup (buf);
5143 addnode (delta->other_delta, np);
5145 (void) sprintf (buf, "%o", sb.st_mode & 07777);
5147 np->type = RCSFIELD;
5148 np->key = xstrdup ("permissions");
5149 np->data = xstrdup (buf);
5150 addnode (delta->other_delta, np);
5152 /* Save device number. */
5153 switch (sb.st_mode & S_IFMT)
5155 case S_IFREG: break;
5158 # ifdef HAVE_STRUCT_STAT_ST_RDEV
5160 np->type = RCSFIELD;
5161 np->key = xstrdup ("special");
5162 sprintf (buf, "%s %lu",
5163 ((sb.st_mode & S_IFMT) == S_IFCHR
5164 ? "character" : "block"),
5165 (unsigned long) sb.st_rdev);
5166 np->data = xstrdup (buf);
5167 addnode (delta->other_delta, np);
5170 "can't preserve %s: unable to save device files on this system",
5176 error (0, 0, "special file %s has unknown type", workfile);
5179 /* Save hardlinks. */
5180 delta->hardlinks = list_linked_files_on_disk (workfile);
5185 /* Create a new deltatext node. */
5186 dtext = xmalloc (sizeof (Deltatext));
5187 memset (dtext, 0, sizeof (Deltatext));
5189 dtext->log = make_message_rcsvalid (message);
5191 /* If the delta tree is empty, then there's nothing to link the
5192 new delta into. So make a new delta tree, snarf the working
5193 file contents, and just write the new RCS file. */
5194 if (rcs->head == NULL)
5199 /* Figure out what the first revision number should be. */
5200 if (rev == NULL || *rev == '\0')
5201 newrev = xstrdup ("1.1");
5202 else if (numdots (rev) == 0)
5204 newrev = Xasprintf ("%s.1", rev);
5207 newrev = xstrdup (rev);
5209 /* Don't need to xstrdup NEWREV because it's already dynamic, and
5210 not used for anything else. (Don't need to free it, either.) */
5212 delta->version = xstrdup (newrev);
5214 nodep->type = RCSVERS;
5215 nodep->delproc = rcsvers_delproc;
5216 nodep->data = delta;
5217 nodep->key = delta->version;
5218 (void) addnode (rcs->versions, nodep);
5220 dtext->version = xstrdup (newrev);
5222 #ifdef PRESERVE_PERMISSIONS_SUPPORT
5223 if (preserve_perms && !S_ISREG (sb.st_mode))
5224 /* Pretend file is empty. */
5228 get_file (workfile, workfile,
5229 rcs->expand != NULL && STREQ (rcs->expand, "b") ? "rb" : "r",
5230 &dtext->text, &bufsize, &dtext->len);
5232 if (!(checkin_quiet || really_quiet))
5234 cvs_output ("initial revision: ", 0);
5235 cvs_output (rcs->head, 0);
5236 cvs_output ("\n", 1);
5239 /* We are probably about to invalidate any cached file. */
5240 rcsbuf_cache_close ();
5242 fout = rcs_internal_lockfile (rcs->path);
5243 RCS_putadmin (rcs, fout);
5244 RCS_putdtree (rcs, rcs->head, fout);
5245 RCS_putdesc (rcs, fout);
5246 rcs->delta_pos = ftello (fout);
5247 if (rcs->delta_pos == -1)
5248 error (1, errno, "cannot ftello for %s", rcs->path);
5249 putdeltatext (fout, dtext);
5250 rcs_internal_unlockfile (fout, rcs->path);
5252 if ((flags & RCS_FLAGS_KEEPFILE) == 0)
5254 if (unlink_file (workfile) < 0)
5255 /* FIXME-update-dir: message does not include update_dir. */
5256 error (0, errno, "cannot remove %s", workfile);
5263 /* Derive a new revision number. From the `ci' man page:
5265 "If rev is a revision number, it must be higher than the
5266 latest one on the branch to which rev belongs, or must
5269 If rev is a branch rather than a revision number, the new
5270 revision is appended to that branch. The level number is
5271 obtained by incrementing the tip revision number of that
5272 branch. If rev indicates a non-existing branch, that
5273 branch is created with the initial revision numbered
5276 RCS_findlock_or_tip handles the case where REV is omitted.
5277 RCS 5.7 also permits REV to be "$" or to begin with a dot, but
5278 we do not address those cases -- every routine that calls
5279 RCS_checkin passes it a numeric revision. */
5281 if (rev == NULL || *rev == '\0')
5283 /* Figure out where the commit point is by looking for locks.
5284 If the commit point is at the tip of a branch (or is the
5285 head of the delta tree), then increment its revision number
5286 to obtain the new revnum. Otherwise, start a new
5288 commitpt = RCS_findlock_or_tip (rcs);
5289 if (commitpt == NULL)
5294 else if (commitpt->next == NULL
5295 || STREQ (commitpt->version, rcs->head))
5296 delta->version = increment_revnum (commitpt->version);
5298 delta->version = RCS_addbranch (rcs, commitpt->version);
5302 /* REV is either a revision number or a branch number. Find the
5303 tip of the target branch. */
5304 char *branch, *tip, *newrev, *p;
5307 assert (isdigit ((unsigned char) *rev));
5309 newrev = xstrdup (rev);
5310 dots = numdots (newrev);
5311 isrevnum = dots & 1;
5313 branch = xstrdup (rev);
5316 p = strrchr (branch, '.');
5320 /* Find the tip of the target branch. If we got a one- or two-digit
5321 revision number, this will be the head of the tree. Exception:
5322 if rev is a single-field revision equal to the branch number of
5323 the trunk (usually "1") then we want to treat it like an ordinary
5327 tip = xstrdup (rcs->head);
5328 if (atoi (tip) != atoi (branch))
5330 newrev = xrealloc (newrev, strlen (newrev) + 3);
5331 strcat (newrev, ".1");
5332 dots = isrevnum = 1;
5336 tip = xstrdup (rcs->head);
5338 tip = RCS_getbranch (rcs, branch, 1);
5340 /* If the branch does not exist, and we were supplied an exact
5341 revision number, signal an error. Otherwise, if we were
5342 given only a branch number, create it and set COMMITPT to
5343 the branch point. */
5348 error (0, 0, "%s: can't find branch point %s",
5349 rcs->print_path, branch);
5355 delta->version = RCS_addbranch (rcs, branch);
5356 if (!delta->version)
5364 p = strrchr (branch, '.');
5366 tip = xstrdup (branch);
5372 /* NEWREV must be higher than TIP. */
5373 if (compare_revnums (tip, newrev) >= 0)
5376 "%s: revision %s too low; must be higher than %s",
5385 delta->version = xstrdup (newrev);
5388 /* Just increment the tip number to get the new revision. */
5389 delta->version = increment_revnum (tip);
5392 nodep = findnode (rcs->versions, tip);
5393 commitpt = nodep->data;
5400 assert (delta->version != NULL);
5402 /* If COMMITPT is locked by us, break the lock. If it's locked
5403 by someone else, signal an error. */
5404 nodep = findnode (RCS_getlocks (rcs), commitpt->version);
5407 if (! STREQ (nodep->data, delta->author))
5409 /* If we are adding a branch, then leave the old lock around.
5410 That is sensible in the sense that when adding a branch,
5411 we don't need to use the lock to tell us where to check
5412 in. It is fishy in the sense that if it is our own lock,
5413 we break it. However, this is the RCS 5.7 behavior (at
5414 the end of addbranch in ci.c in RCS 5.7, it calls
5415 removelock only if it is our own lock, not someone
5420 error (0, 0, "%s: revision %s locked by %s",
5422 nodep->key, (char *)nodep->data);
5431 dtext->version = xstrdup (delta->version);
5433 /* Obtain the change text for the new delta. If DELTA is to be the
5434 new head of the tree, then its change text should be the contents
5435 of the working file, and LEAFNODE's change text should be a diff.
5436 Else, DELTA's change text should be a diff between LEAFNODE and
5437 the working file. */
5439 tmpfile = cvs_temp_name();
5440 status = RCS_checkout (rcs, NULL, commitpt->version, NULL,
5441 ((rcs->expand != NULL
5442 && STREQ (rcs->expand, "b"))
5449 "could not check out revision %s of `%s'",
5450 commitpt->version, rcs->print_path);
5453 changefile = cvs_temp_name();
5455 /* Diff options should include --binary if the RCS file has -kb set
5456 in its `expand' field. */
5457 run_add_arg_p (&dargc, &darg_allocated, &dargv, "-a");
5458 run_add_arg_p (&dargc, &darg_allocated, &dargv, "-n");
5459 if (rcs->expand != NULL && STREQ (rcs->expand, "b"))
5460 run_add_arg_p (&dargc, &darg_allocated, &dargv, "--binary");
5462 if (STREQ (commitpt->version, rcs->head) &&
5463 numdots (delta->version) == 1)
5465 /* If this revision is being inserted on the trunk, the change text
5466 for the new delta should be the contents of the working file ... */
5468 #ifdef PRESERVE_PERMISSIONS_SUPPORT
5469 if (preserve_perms && !S_ISREG (sb.st_mode))
5470 /* Pretend file is empty. */
5474 get_file (workfile, workfile,
5475 rcs->expand != NULL && STREQ (rcs->expand, "b") ? "rb" : "r",
5476 &dtext->text, &bufsize, &dtext->len);
5478 /* ... and the change text for the old delta should be a diff. */
5479 commitpt->text = xmalloc (sizeof (Deltatext));
5480 memset (commitpt->text, 0, sizeof (Deltatext));
5483 switch (diff_exec (workfile, tmpfile, NULL, NULL,
5484 dargc, dargv, changefile))
5490 /* FIXME-update-dir: message does not include update_dir. */
5491 error (1, errno, "error diffing %s", workfile);
5494 /* FIXME-update-dir: message does not include update_dir. */
5495 error (1, 0, "error diffing %s", workfile);
5499 /* OK, the text file case here is really dumb. Logically
5500 speaking we want diff to read the files in text mode,
5501 convert them to the canonical form found in RCS files
5502 (which, we hope at least, is independent of OS--always
5503 bare linefeeds), and then work with change texts in that
5504 format. However, diff_exec both generates change
5505 texts and produces output for user purposes (e.g. patch.c),
5506 and there is no way to distinguish between the two cases.
5507 So we actually implement the text file case by writing the
5508 change text as a text file, then reading it as a text file.
5509 This should cause no harm, but doesn't strike me as
5511 get_file (changefile, changefile,
5512 rcs->expand != NULL && STREQ (rcs->expand, "b") ? "rb" : "r",
5513 &commitpt->text->text, &bufsize, &commitpt->text->len);
5515 /* If COMMITPT->TEXT->TEXT is NULL, it means that CHANGEFILE
5516 was empty and that there are no differences between revisions.
5517 In that event, we want to force RCS_rewrite to write an empty
5518 string for COMMITPT's change text. Leaving the change text
5519 field set NULL won't work, since that means "preserve the original
5520 change text for this delta." */
5521 if (commitpt->text->text == NULL)
5523 commitpt->text->text = xstrdup ("");
5524 commitpt->text->len = 0;
5529 /* This file is not being inserted at the head, but on a side
5530 branch somewhere. Make a diff from the previous revision
5531 to the working file. */
5532 switch (diff_exec (tmpfile, workfile, NULL, NULL,
5533 dargc, dargv, changefile))
5539 /* FIXME-update-dir: message does not include update_dir. */
5540 error (1, errno, "error diffing %s", workfile);
5543 /* FIXME-update-dir: message does not include update_dir. */
5544 error (1, 0, "error diffing %s", workfile);
5547 /* See the comment above, at the other get_file invocation,
5548 regarding binary vs. text. */
5549 get_file (changefile, changefile,
5550 rcs->expand != NULL && STREQ (rcs->expand, "b") ? "rb" : "r",
5551 &dtext->text, &bufsize,
5553 if (dtext->text == NULL)
5555 dtext->text = xstrdup ("");
5560 run_arg_free_p (dargc, dargv);
5563 /* Update DELTA linkage. It is important not to do this before
5564 the very end of RCS_checkin; if an error arises that forces
5565 us to abort checking in, we must not have malformed deltas
5566 partially linked into the tree.
5568 If DELTA and COMMITPT are on different branches, do nothing --
5569 DELTA is linked to the tree through COMMITPT->BRANCHES, and we
5570 don't want to change `next' pointers.
5572 Otherwise, if the nodes are both on the trunk, link DELTA to
5573 COMMITPT; otherwise, link COMMITPT to DELTA. */
5575 if (numdots (commitpt->version) == numdots (delta->version))
5577 if (STREQ (commitpt->version, rcs->head))
5579 delta->next = rcs->head;
5580 rcs->head = xstrdup (delta->version);
5583 commitpt->next = xstrdup (delta->version);
5586 /* Add DELTA to RCS->VERSIONS. */
5587 if (rcs->versions == NULL)
5588 rcs->versions = getlist();
5590 nodep->type = RCSVERS;
5591 nodep->delproc = rcsvers_delproc;
5592 nodep->data = delta;
5593 nodep->key = delta->version;
5594 (void) addnode (rcs->versions, nodep);
5596 /* Write the new RCS file, inserting the new delta at COMMITPT. */
5597 if (!(checkin_quiet || really_quiet))
5599 cvs_output ("new revision: ", 14);
5600 cvs_output (delta->version, 0);
5601 cvs_output ("; previous revision: ", 21);
5602 cvs_output (commitpt->version, 0);
5603 cvs_output ("\n", 1);
5606 RCS_rewrite (rcs, dtext, commitpt->version);
5608 if ((flags & RCS_FLAGS_KEEPFILE) == 0)
5610 if (unlink_file (workfile) < 0)
5611 /* FIXME-update-dir: message does not include update_dir. */
5612 error (1, errno, "cannot remove %s", workfile);
5614 if (unlink_file (tmpfile) < 0)
5615 error (0, errno, "cannot remove %s", tmpfile);
5617 if (unlink_file (changefile) < 0)
5618 error (0, errno, "cannot remove %s", changefile);
5624 if (commitpt != NULL && commitpt->text != NULL)
5626 freedeltatext (commitpt->text);
5627 commitpt->text = NULL;
5630 freedeltatext (dtext);
5633 /* If delta has not been added to a List, then freeing the Node key
5634 * won't free delta->version.
5636 if (delta->version) free (delta->version);
5637 free_rcsvers_contents (delta);
5645 /* This structure is passed between RCS_cmp_file and cmp_file_buffer. */
5646 struct cmp_file_data
5648 const char *filename;
5653 /* Compare the contents of revision REV1 of RCS file RCS with the
5654 contents of REV2 if given, otherwise, compare with the contents of
5655 the file FILENAME. OPTIONS is a string for the keyword
5656 expansion options. Return 0 if the contents of the revision are
5657 the same as the contents of the file, 1 if they are different. */
5659 RCS_cmp_file (RCSNode *rcs, const char *rev1, char **rev1_cache,
5660 const char *rev2, const char *options, const char *filename)
5664 TRACE (TRACE_FUNCTION, "RCS_cmp_file( %s, %s, %s, %s, %s )",
5665 rcs->path ? rcs->path : "(null)",
5666 rev1 ? rev1 : "(null)", rev2 ? rev2 : "(null)",
5667 options ? options : "(null)", filename ? filename : "(null)");
5669 if (options != NULL && options[0] != '\0')
5670 binary = STREQ (options, "-kb");
5675 expand = RCS_getexpand (rcs);
5676 if (expand != NULL && STREQ (expand, "b"))
5682 #ifdef PRESERVE_PERMISSIONS_SUPPORT
5683 /* If CVS is to deal properly with special files (when
5684 PreservePermissions is on), the best way is to check out the
5685 revision to a temporary file and call `xcmp' on the two disk
5686 files. xcmp needs to handle non-regular files properly anyway,
5687 so calling it simplifies RCS_cmp_file. We *could* just yank
5688 the delta node out of the version tree and look for device
5689 numbers, but writing to disk and calling xcmp is a better
5690 abstraction (therefore probably more robust). -twp */
5697 tmp = cvs_temp_name();
5698 retcode = RCS_checkout(rcs, NULL, rev, NULL, options, tmp, NULL, NULL);
5702 retcode = xcmp (tmp, filename);
5703 if (CVS_UNLINK (tmp) < 0)
5704 error (0, errno, "cannot remove %s", tmp);
5712 struct cmp_file_data data;
5713 const char *use_file1;
5714 char *tmpfile = NULL;
5718 /* Open & cache rev1 */
5719 tmpfile = cvs_temp_name();
5720 if (RCS_checkout (rcs, NULL, rev1, NULL, options, tmpfile,
5723 "cannot check out revision %s of %s",
5724 rev1, rcs->print_path);
5725 use_file1 = tmpfile;
5726 if (rev1_cache != NULL)
5727 *rev1_cache = tmpfile;
5730 use_file1 = filename;
5732 fp = CVS_FOPEN (use_file1, binary ? FOPEN_BINARY_READ : "r");
5734 /* FIXME-update-dir: should include update_dir in message. */
5735 error (1, errno, "cannot open file %s for comparing", use_file1);
5737 data.filename = use_file1;
5741 if (RCS_checkout (rcs, NULL, rev2 ? rev2 : rev1, NULL, options,
5742 RUN_TTY, cmp_file_buffer, &data ))
5744 "cannot check out revision %s of %s",
5745 rev2 ? rev2 : rev1, rcs->print_path);
5747 /* If we have not yet found a difference, make sure that we are at
5748 the end of the file. */
5749 if (!data.different)
5751 if (getc (fp) != EOF)
5756 if (rev1_cache == NULL && tmpfile)
5758 if (CVS_UNLINK (tmpfile ) < 0)
5759 error (0, errno, "cannot remove %s", tmpfile);
5763 return data.different;
5769 /* This is a subroutine of RCS_cmp_file. It is passed to
5771 #define CMP_BUF_SIZE (8 * 1024)
5774 cmp_file_buffer (void *callerdat, const char *buffer, size_t len)
5776 struct cmp_file_data *data = callerdat;
5779 /* If we've already found a difference, we don't need to check
5781 if (data->different)
5784 filebuf = xmalloc (len > CMP_BUF_SIZE ? CMP_BUF_SIZE : len);
5790 checklen = len > CMP_BUF_SIZE ? CMP_BUF_SIZE : len;
5791 if (fread (filebuf, 1, checklen, data->fp) != checklen)
5793 if (ferror (data->fp))
5794 error (1, errno, "cannot read file %s for comparing",
5796 data->different = 1;
5801 if (memcmp (filebuf, buffer, checklen) != 0)
5803 data->different = 1;
5817 /* For RCS file RCS, make symbolic tag TAG point to revision REV.
5818 This validates that TAG is OK for a user to use. Return value is
5819 -1 for error (and errno is set to indicate the error), positive for
5820 error (and an error message has been printed), or zero for success. */
5822 RCS_settag (RCSNode *rcs, const char *tag, const char *rev)
5827 if (rcs->flags & PARTIAL)
5828 RCS_reparsercsfile (rcs, NULL, NULL);
5830 /* FIXME: This check should be moved to RCS_check_tag. There is no
5831 reason for it to be here. */
5832 if (STREQ (tag, TAG_BASE)
5833 || STREQ (tag, TAG_HEAD))
5835 /* Print the name of the tag might be considered redundant
5836 with the caller, which also prints it. Perhaps this helps
5837 clarify why the tag name is considered reserved, I don't
5839 error (0, 0, "Attempt to add reserved tag name %s", tag);
5843 /* A revision number of NULL means use the head or default branch.
5844 If rev is not NULL, it may be a symbolic tag or branch number;
5845 expand it to the correct numeric revision or branch head. */
5847 rev = rcs->branch ? rcs->branch : rcs->head;
5849 /* At this point rcs->symbol_data may not have been parsed.
5850 Calling RCS_symbols will force it to be parsed into a list
5851 which we can easily manipulate. */
5852 symbols = RCS_symbols (rcs);
5853 if (symbols == NULL)
5855 symbols = getlist ();
5856 rcs->symbols = symbols;
5858 node = findnode (symbols, tag);
5862 node->data = xstrdup (rev);
5867 node->key = xstrdup (tag);
5868 node->data = xstrdup (rev);
5869 (void)addnode_at_front (symbols, node);
5877 /* Delete the symbolic tag TAG from the RCS file RCS. Return 0 if
5878 the tag was found (and removed), or 1 if it was not present. (In
5879 either case, the tag will no longer be in RCS->SYMBOLS.) */
5881 RCS_deltag (RCSNode *rcs, const char *tag)
5885 if (rcs->flags & PARTIAL)
5886 RCS_reparsercsfile (rcs, NULL, NULL);
5888 symbols = RCS_symbols (rcs);
5889 if (symbols == NULL)
5892 node = findnode (symbols, tag);
5903 /* Set the default branch of RCS to REV. */
5905 RCS_setbranch (RCSNode *rcs, const char *rev)
5907 if (rcs->flags & PARTIAL)
5908 RCS_reparsercsfile (rcs, NULL, NULL);
5913 if (rev == NULL && rcs->branch == NULL)
5915 if (rev != NULL && rcs->branch != NULL && STREQ (rev, rcs->branch))
5918 if (rcs->branch != NULL)
5920 rcs->branch = xstrdup (rev);
5927 /* Lock revision REV. LOCK_QUIET is 1 to suppress output. FIXME:
5928 Most of the callers only call us because RCS_checkin still tends to
5929 like a lock (a relic of old behavior inherited from the RCS ci
5930 program). If we clean this up, only "cvs admin -l" will still need
5931 to call RCS_lock. */
5933 /* FIXME-twp: if a lock owned by someone else is broken, should this
5934 send mail to the lock owner? Prompt user? It seems like such an
5935 obscure situation for CVS as almost not worth worrying much
5938 RCS_lock (RCSNode *rcs, const char *rev, int lock_quiet)
5945 if (rcs->flags & PARTIAL)
5946 RCS_reparsercsfile (rcs, NULL, NULL);
5948 locks = RCS_getlocks (rcs);
5950 locks = rcs->locks = getlist();
5953 /* A revision number of NULL means lock the head or default branch. */
5955 xrev = RCS_head (rcs);
5957 xrev = RCS_gettag (rcs, rev, 1, NULL);
5959 /* Make sure that the desired revision exists. Technically,
5960 we can update the locks list without even checking this,
5961 but RCS 5.7 did this. And it can't hurt. */
5962 if (xrev == NULL || findnode (rcs->versions, xrev) == NULL)
5965 error (0, 0, "%s: revision %s absent", rcs->print_path, rev);
5970 /* Is this rev already locked? */
5971 p = findnode (locks, xrev);
5974 if (STREQ (p->data, user))
5976 /* We already own the lock on this revision, so do nothing. */
5982 /* Well, first of all, "rev" below should be "xrev" to avoid
5983 core dumps. But more importantly, should we really be
5984 breaking the lock unconditionally? What CVS 1.9 does (via
5985 RCS) is to prompt "Revision 1.1 is already locked by fred.
5986 Do you want to break the lock? [ny](n): ". Well, we don't
5987 want to interact with the user (certainly not at the
5988 server/protocol level, and probably not in the command-line
5989 client), but isn't it more sensible to give an error and
5990 let the user run "cvs admin -u" if they want to break the
5993 /* Break the lock. */
5996 cvs_output (rev, 0);
5997 cvs_output (" unlocked\n", 0);
6001 error (1, 0, "Revision %s is already locked by %s",
6002 xrev, (char *)p->data);
6006 /* Create a new lock. */
6008 p->key = xrev; /* already xstrdupped */
6009 p->data = xstrdup (getcaller());
6010 (void)addnode_at_front (locks, p);
6014 cvs_output (xrev, 0);
6015 cvs_output (" locked\n", 0);
6023 /* Unlock revision REV. UNLOCK_QUIET is 1 to suppress output. FIXME:
6024 Like RCS_lock, this can become a no-op if we do the checkin
6027 If REV is not null and is locked by someone else, break their
6028 lock and notify them. It is an open issue whether RCS_unlock
6029 queries the user about whether or not to break the lock. */
6031 RCS_unlock (RCSNode *rcs, char *rev, int unlock_quiet)
6039 if (rcs->flags & PARTIAL)
6040 RCS_reparsercsfile (rcs, NULL, NULL);
6042 /* If rev is NULL, unlock the revision held by the caller; if more
6043 than one, make the user specify the revision explicitly. This
6044 differs from RCS which unlocks the latest revision (first in
6045 rcs->locks) held by the caller. */
6050 /* No-ops: attempts to unlock an empty tree or an unlocked file. */
6051 if (rcs->head == NULL)
6054 cvs_outerr ("can't unlock an empty tree\n", 0);
6058 locks = RCS_getlocks (rcs);
6062 cvs_outerr ("No locks are set.\n", 0);
6067 for (p = locks->list->next; p != locks->list; p = p->next)
6069 if (STREQ (p->data, user))
6075 %s: multiple revisions locked by %s; please specify one", rcs->print_path, user);
6084 error (0, 0, "No locks are set for %s.\n", user);
6085 return 0; /* no lock found, ergo nothing to do */
6087 xrev = xstrdup (lock->key);
6091 xrev = RCS_gettag (rcs, rev, 1, NULL);
6094 error (0, 0, "%s: revision %s absent", rcs->print_path, rev);
6099 lock = findnode (RCS_getlocks (rcs), xrev);
6102 /* This revision isn't locked. */
6107 if (! STREQ (lock->data, user))
6109 /* If the revision is locked by someone else, notify
6110 them. Note that this shouldn't ever happen if RCS_unlock
6111 is called with a NULL revision, since that means "whatever
6112 revision is currently locked by the caller." */
6113 char *repos, *workfile;
6116 %s: revision %s locked by %s; breaking lock", rcs->print_path, xrev,
6117 (char *)lock->data);
6118 repos = xstrdup (rcs->path);
6119 workfile = strrchr (repos, '/');
6121 notify_do ('C', workfile, NULL, user, NULL, NULL, repos);
6128 cvs_output (xrev, 0);
6129 cvs_output (" unlocked\n", 0);
6138 /* Add USER to the access list of RCS. Do nothing if already present.
6139 FIXME-twp: check syntax of USER to make sure it's a valid id. */
6142 RCS_addaccess (RCSNode *rcs, char *user)
6146 if (rcs->flags & PARTIAL)
6147 RCS_reparsercsfile (rcs, NULL, NULL);
6149 if (rcs->access == NULL)
6150 rcs->access = xstrdup (user);
6153 access = xstrdup (rcs->access);
6154 for (a = strtok (access, " "); a != NULL; a = strtok (NULL, " "))
6156 if (STREQ (a, user))
6163 rcs->access = xrealloc (rcs->access,
6164 strlen (rcs->access) + strlen (user) + 2);
6165 strcat (rcs->access, " ");
6166 strcat (rcs->access, user);
6172 /* Remove USER from the access list of RCS. */
6174 RCS_delaccess (RCSNode *rcs, char *user)
6179 if (rcs->flags & PARTIAL)
6180 RCS_reparsercsfile (rcs, NULL, NULL);
6182 if (rcs->access == NULL)
6193 ulen = strlen (user);
6196 if (strncmp (p, user, ulen) == 0 && (p[ulen] == '\0' || p[ulen] == ' '))
6198 p = strchr (p, ' ');
6215 RCS_getaccess (RCSNode *rcs)
6217 if (rcs->flags & PARTIAL)
6218 RCS_reparsercsfile (rcs, NULL, NULL);
6225 /* Return a nonzero value if the revision specified by ARG is found. */
6227 findtag (Node *node, void *arg)
6231 if (STREQ (node->data, rev))
6239 /* Delete revisions between REV1 and REV2. The changes between the two
6240 revisions must be collapsed, and the result stored in the revision
6241 immediately preceding the lower one. Return 0 for successful completion,
6244 Solution: check out the revision preceding REV1 and the revision
6245 following REV2. Use call_diff to find aggregate diffs between
6246 these two revisions, and replace the delta text for the latter one
6247 with the new aggregate diff. Alternatively, we could write a
6248 function that takes two change texts and combines them to produce a
6249 new change text, without checking out any revs or calling diff. It
6250 would be hairy, but so, so cool.
6252 If INCLUSIVE is set, then TAG1 and TAG2, if non-NULL, tell us to
6253 delete that revision as well (cvs admin -o tag1:tag2). If clear,
6254 delete up to but not including that revision (cvs admin -o tag1::tag2).
6255 This does not affect TAG1 or TAG2 being NULL; the meaning of the start
6256 point in ::tag2 and :tag2 is the same and likewise for end points. */
6258 RCS_delete_revs (RCSNode *rcs, char *tag1, char *tag2, int inclusive)
6262 RCSVers *revp = NULL;
6267 char *branchpoint = NULL;
6270 int rev1_inclusive = inclusive;
6271 int rev2_inclusive = inclusive;
6272 char *before = NULL;
6274 char *beforefile = NULL;
6275 char *afterfile = NULL;
6276 char *outfile = NULL;
6278 if (tag1 == NULL && tag2 == NULL)
6281 /* Assume error status until everything is finished. */
6284 /* Make sure both revisions exist. */
6287 rev1 = RCS_gettag (rcs, tag1, 1, NULL);
6288 if (rev1 == NULL || (nodep = findnode (rcs->versions, rev1)) == NULL)
6290 error (0, 0, "%s: Revision %s doesn't exist.", rcs->print_path, tag1);
6296 rev2 = RCS_gettag (rcs, tag2, 1, NULL);
6297 if (rev2 == NULL || (nodep = findnode (rcs->versions, rev2)) == NULL)
6299 error (0, 0, "%s: Revision %s doesn't exist.", rcs->print_path, tag2);
6304 /* If rev1 is on the trunk and rev2 is NULL, rev2 should be
6305 RCS->HEAD. (*Not* RCS_head(rcs), which may return rcs->branch
6306 instead.) We need to check this special case early, in order
6307 to make sure that rev1 and rev2 get ordered correctly. */
6308 if (rev2 == NULL && numdots (rev1) == 1)
6310 rev2 = xstrdup (rcs->head);
6317 if (rev1 != NULL && rev2 != NULL)
6319 /* A range consisting of a branch number means the latest revision
6321 if (RCS_isbranch (rcs, rev1) && STREQ (rev1, rev2))
6323 char *tmp = RCS_getbranch (rcs, rev1, 0);
6330 /* Make sure REV1 and REV2 are ordered correctly (in the
6331 same order as the next field). For revisions on the
6332 trunk, REV1 should be higher than REV2; for branches,
6333 REV1 should be lower. */
6334 /* Shouldn't we just be giving an error in the case where
6335 the user specifies the revisions in the wrong order
6336 (that is, always swap on the trunk, never swap on a
6337 branch, in the non-error cases)? It is not at all
6338 clear to me that users who specify -o 1.4:1.2 really
6339 meant to type -o 1.2:1.4, and the out of order usage
6340 has never been documented, either by cvs.texinfo or
6344 if (numdots (rev1) == 1)
6346 if (compare_revnums (rev1, rev2) <= 0)
6352 temp_inclusive = rev2_inclusive;
6353 rev2_inclusive = rev1_inclusive;
6354 rev1_inclusive = temp_inclusive;
6357 else if (compare_revnums (rev1, rev2) > 0)
6363 temp_inclusive = rev2_inclusive;
6364 rev2_inclusive = rev1_inclusive;
6365 rev1_inclusive = temp_inclusive;
6370 /* Basically the same thing; make sure that the ordering is what we
6374 assert (rev2 != NULL);
6375 if (numdots (rev2) == 1)
6377 /* Swap rev1 and rev2. */
6383 temp_inclusive = rev2_inclusive;
6384 rev2_inclusive = rev1_inclusive;
6385 rev1_inclusive = temp_inclusive;
6389 /* Put the revision number preceding the first one to delete into
6390 BEFORE (where "preceding" means according to the next field).
6391 If the first revision to delete is the first revision on its
6392 branch (e.g. 1.3.2.1), BEFORE should be the node on the trunk
6393 at which the branch is rooted. If the first revision to delete
6394 is the head revision of the trunk, set BEFORE to NULL.
6396 Note that because BEFORE may not be on the same branch as REV1,
6397 it is not very handy for navigating the revision tree. It's
6398 most useful just for checking out the revision preceding REV1. */
6400 branchpoint = RCS_getbranchpoint (rcs, rev1 != NULL ? rev1 : rev2);
6403 rev1 = xstrdup (branchpoint);
6404 if (numdots (branchpoint) > 1)
6407 bp = strrchr (branchpoint, '.');
6408 while (*--bp != '.')
6411 /* Note that this is exclusive, always, because the inclusive
6412 flag doesn't affect the meaning when rev1 == NULL. */
6413 before = xstrdup (branchpoint);
6417 else if (! STREQ (rev1, branchpoint))
6419 /* Walk deltas from BRANCHPOINT on, looking for REV1. */
6420 nodep = findnode (rcs->versions, branchpoint);
6422 while (revp->next != NULL && ! STREQ (revp->next, rev1))
6425 nodep = findnode (rcs->versions, revp->next);
6427 if (revp->next == NULL)
6429 error (0, 0, "%s: Revision %s doesn't exist.", rcs->print_path, rev1);
6433 before = xstrdup (revp->version);
6437 nodep = findnode (rcs->versions, before);
6438 rev1 = xstrdup (((RCSVers *)nodep->data)->next);
6441 else if (!rev1_inclusive)
6444 nodep = findnode (rcs->versions, before);
6445 rev1 = xstrdup (((RCSVers *)nodep->data)->next);
6447 else if (numdots (branchpoint) > 1)
6449 /* Example: rev1 is "1.3.2.1", branchpoint is "1.3.2.1".
6450 Set before to "1.3". */
6452 bp = strrchr (branchpoint, '.');
6453 while (*--bp != '.')
6456 before = xstrdup (branchpoint);
6460 /* If any revision between REV1 and REV2 is locked or is a branch point,
6461 we can't delete that revision and must abort. */
6465 while (!found && next != NULL)
6467 nodep = findnode (rcs->versions, next);
6471 found = STREQ (revp->version, rev2);
6474 if ((!found && next != NULL) || rev2_inclusive || rev2 == NULL)
6476 if (findnode (RCS_getlocks (rcs), revp->version))
6478 error (0, 0, "%s: can't remove locked revision %s",
6483 if (revp->branches != NULL)
6485 error (0, 0, "%s: can't remove branch point %s",
6491 /* Doing this only for the :: syntax is for compatibility.
6492 See cvs.texinfo for somewhat more discussion. */
6494 && walklist (RCS_symbols (rcs), findtag, revp->version))
6496 /* We don't print which file this happens to on the theory
6497 that the caller will print the name of the file in a
6498 more useful fashion (fullname not rcs->path). */
6499 error (0, 0, "cannot remove revision %s because it has tags",
6504 /* It's misleading to print the `deleting revision' output
6505 here, since we may not actually delete these revisions.
6506 But that's how RCS does it. Bleah. Someday this should be
6507 moved to the point where the revs are actually marked for
6509 cvs_output ("deleting revision ", 0);
6510 cvs_output (revp->version, 0);
6511 cvs_output ("\n", 1);
6520 after = xstrdup (next);
6522 after = xstrdup (revp->version);
6524 else if (!inclusive)
6526 /* In the case of an empty range, for example 1.2::1.2 or
6527 1.2::1.3, we want to just do nothing. */
6533 /* This looks fishy in the cases where tag1 == NULL or tag2 == NULL.
6534 Are those cases really impossible? */
6535 assert (tag1 != NULL);
6536 assert (tag2 != NULL);
6538 error (0, 0, "%s: invalid revision range %s:%s", rcs->print_path,
6543 if (after == NULL && before == NULL)
6545 /* The user is trying to delete all revisions. While an
6546 RCS file without revisions makes sense to RCS (e.g. the
6547 state after "rcs -i"), CVS has never been able to cope with
6548 it. So at least for now we just make this an error.
6550 We don't include rcs->path in the message since "cvs admin"
6551 already printed "RCS file:" and the name. */
6552 error (1, 0, "attempt to delete all revisions");
6555 /* The conditionals at this point get really hairy. Here is the
6558 IF before != NULL and after == NULL
6559 THEN don't check out any revisions, just delete them
6560 IF before == NULL and after != NULL
6561 THEN only check out after's revision, and use it for the new deltatext
6563 check out both revisions and diff -n them. This could use
6564 RCS_exec_rcsdiff with some changes, like being able
6565 to suppress diagnostic messages and to direct output. */
6570 size_t bufsize, len;
6572 #if defined (WOE32) && !defined (__CYGWIN32__)
6573 /* FIXME: This is an awful kludge, but at least until I have
6574 time to work on it a little more and test it, I'd rather
6575 give a fatal error than corrupt the file. I think that we
6576 need to use "-kb" and "--binary" and "rb" to get_file
6577 (probably can do it always, not just for binary files, if
6578 we are consistent between the RCS_checkout and the diff). */
6580 char *expand = RCS_getexpand (rcs);
6581 if (expand != NULL && STREQ (expand, "b"))
6583 "admin -o not implemented yet for binary on this system");
6587 afterfile = cvs_temp_name();
6588 status = RCS_checkout (rcs, NULL, after, NULL, "-ko", afterfile,
6595 /* We are deleting revisions from the head of the tree,
6596 so must create a new head. */
6599 get_file (afterfile, afterfile, "r", &diffbuf, &bufsize, &len);
6601 save_noexec = noexec;
6603 if (unlink_file (afterfile) < 0)
6604 error (0, errno, "cannot remove %s", afterfile);
6605 noexec = save_noexec;
6611 rcs->head = xstrdup (after);
6616 size_t darg_allocated = 0;
6617 char **dargv = NULL;
6619 beforefile = cvs_temp_name();
6620 status = RCS_checkout (rcs, NULL, before, NULL, "-ko", beforefile,
6625 outfile = cvs_temp_name();
6626 run_add_arg_p (&dargc, &darg_allocated, &dargv, "-a");
6627 run_add_arg_p (&dargc, &darg_allocated, &dargv, "-n");
6628 status = diff_exec (beforefile, afterfile, NULL, NULL,
6629 dargc, dargv, outfile);
6630 run_arg_free_p (dargc, dargv);
6635 /* Not sure we need this message; will diff_exec already
6636 have printed an error? */
6637 error (0, 0, "%s: could not diff", rcs->print_path);
6644 get_file (outfile, outfile, "r", &diffbuf, &bufsize, &len);
6647 /* Save the new change text in after's delta node. */
6648 nodep = findnode (rcs->versions, after);
6651 assert (revp->text == NULL);
6653 revp->text = xmalloc (sizeof (Deltatext));
6654 memset (revp->text, 0, sizeof (Deltatext));
6655 revp->text->version = xstrdup (revp->version);
6656 revp->text->text = diffbuf;
6657 revp->text->len = len;
6659 /* If DIFFBUF is NULL, it means that OUTFILE is empty and that
6660 there are no differences between the two revisions. In that
6661 case, we want to force RCS_copydeltas to write an empty string
6662 for the new change text (leaving the text field set NULL
6663 means "preserve the original change text for this delta," so
6664 we don't want that). */
6665 if (revp->text->text == NULL)
6666 revp->text->text = xstrdup ("");
6669 /* Walk through the revisions (again) to mark each one as
6670 outdated. (FIXME: would it be safe to use the `dead' field for
6673 next != NULL && (after == NULL || ! STREQ (next, after));
6676 nodep = findnode (rcs->versions, next);
6681 /* Update delta links. If BEFORE == NULL, we're changing the
6682 head of the tree and don't need to update any `next' links. */
6685 /* If REV1 is the first node on its branch, then BEFORE is its
6686 root node (on the trunk) and we have to update its branches
6687 list. Otherwise, BEFORE is on the same branch as AFTER, and
6688 we can just change BEFORE's `next' field to point to AFTER.
6689 (This should be safe: since findnode manages its lists via
6690 the `hashnext' and `hashprev' fields, rather than `next' and
6691 `prev', mucking with `next' and `prev' should not corrupt the
6692 delta tree's internal structure. Much. -twp) */
6695 /* beforep's ->next field already should be equal to after,
6696 which I think is always NULL in this case. */
6698 else if (STREQ (rev1, branchpoint))
6700 nodep = findnode (rcs->versions, before);
6702 nodep = revp->branches->list->next;
6703 while (nodep != revp->branches->list &&
6704 ! STREQ (nodep->key, rev1))
6705 nodep = nodep->next;
6706 assert (nodep != revp->branches->list);
6712 nodep->key = xstrdup (after);
6717 nodep = findnode (rcs->versions, before);
6718 beforep = nodep->data;
6719 free (beforep->next);
6720 beforep->next = xstrdup (after);
6729 if (rev2 && rev2 != rev1)
6731 if (branchpoint != NULL)
6738 save_noexec = noexec;
6740 if (beforefile != NULL)
6742 if (unlink_file (beforefile) < 0)
6743 error (0, errno, "cannot remove %s", beforefile);
6746 if (afterfile != NULL)
6748 if (unlink_file (afterfile) < 0)
6749 error (0, errno, "cannot remove %s", afterfile);
6752 if (outfile != NULL)
6754 if (unlink_file (outfile) < 0)
6755 error (0, errno, "cannot remove %s", outfile);
6758 noexec = save_noexec;
6766 * TRUE if there exists a symbolic tag "tag" in file.
6769 RCS_exist_tag (RCSNode *rcs, char *tag)
6772 assert (rcs != NULL);
6774 if (findnode (RCS_symbols (rcs), tag))
6783 * TRUE if RCS revision number "rev" exists.
6784 * This includes magic branch revisions, not found in rcs->versions,
6785 * but only in rcs->symbols, requiring a list walk to find them.
6786 * Take advantage of list walk callback function already used by
6787 * RCS_delete_revs, above.
6790 RCS_exist_rev (RCSNode *rcs, char *rev)
6793 assert (rcs != NULL);
6795 if (rcs->flags & PARTIAL)
6796 RCS_reparsercsfile (rcs, NULL, NULL);
6798 if (findnode(rcs->versions, rev) != 0)
6801 if (walklist (RCS_symbols(rcs), findtag, rev) != 0)
6811 /* RCS_deltas and friends. Processing of the deltas in RCS files. */
6814 /* Text of this line. Part of the same malloc'd block as the struct
6815 line itself (we probably should use the "struct hack" (char text[1])
6816 and save ourselves sizeof (char *) bytes). Does not include \n;
6817 instead has_newline indicates the presence or absence of \n. */
6819 /* Length of this line, not counting \n if has_newline is true. */
6821 /* Version in which it was introduced. */
6823 /* Nonzero if this line ends with \n. This will always be true
6824 except possibly for the last line. */
6826 /* Number of pointers to this struct line. */
6832 /* How many lines in use for this linevector? */
6833 unsigned int nlines;
6834 /* How many lines allocated for this linevector? */
6835 unsigned int lines_alloced;
6836 /* Pointer to array containing a pointer to each line. */
6837 struct line **vector;
6842 /* Initialize *VEC to be a linevector with no lines. */
6844 linevector_init (struct linevector *vec)
6846 vec->lines_alloced = 0;
6853 /* Given some text TEXT, add each of its lines to VEC before line POS
6854 (where line 0 is the first line). The last line in TEXT may or may
6855 not be \n terminated.
6856 Set the version for each of the new lines to VERS. This
6857 function returns non-zero for success. It returns zero if the line
6858 number is out of range.
6860 Each of the lines in TEXT are copied to space which is managed with
6861 the linevector (and freed by linevector_free). So the caller doesn't
6862 need to keep TEXT around after the call to this function. */
6864 linevector_add (struct linevector *vec, const char *text, size_t len,
6865 RCSVers *vers, unsigned int pos)
6867 const char *textend;
6871 const char *nextline_text;
6872 size_t nextline_len;
6873 int nextline_newline;
6879 textend = text + len;
6881 /* Count the number of lines we will need to add. */
6883 for (p = text; p < textend; ++p)
6884 if (*p == '\n' && p + 1 < textend)
6887 /* Expand VEC->VECTOR if needed. */
6888 if (vec->nlines + nnew >= vec->lines_alloced)
6890 if (vec->lines_alloced == 0)
6891 vec->lines_alloced = 10;
6892 while (vec->nlines + nnew >= vec->lines_alloced)
6893 vec->lines_alloced *= 2;
6894 vec->vector = xnrealloc (vec->vector,
6895 vec->lines_alloced, sizeof (*vec->vector));
6898 /* Make room for the new lines in VEC->VECTOR. */
6899 for (i = vec->nlines + nnew - 1; i >= pos + nnew; --i)
6900 vec->vector[i] = vec->vector[i - nnew];
6902 if (pos > vec->nlines)
6905 /* Actually add the lines, to VEC->VECTOR. */
6907 nextline_text = text;
6908 nextline_newline = 0;
6909 for (p = text; p < textend; ++p)
6912 nextline_newline = 1;
6913 if (p + 1 == textend)
6914 /* If there are no characters beyond the last newline, we
6915 don't consider it another line. */
6917 nextline_len = p - nextline_text;
6918 q = xmalloc (sizeof (struct line) + nextline_len);
6920 q->text = (char *)q + sizeof (struct line);
6921 q->len = nextline_len;
6922 q->has_newline = nextline_newline;
6924 memcpy (q->text, nextline_text, nextline_len);
6925 vec->vector[i++] = q;
6927 nextline_text = (char *)p + 1;
6928 nextline_newline = 0;
6930 nextline_len = p - nextline_text;
6931 q = xmalloc (sizeof (struct line) + nextline_len);
6933 q->text = (char *)q + sizeof (struct line);
6934 q->len = nextline_len;
6935 q->has_newline = nextline_newline;
6937 memcpy (q->text, nextline_text, nextline_len);
6940 vec->nlines += nnew;
6947 /* Remove NLINES lines from VEC at position POS (where line 0 is the
6950 linevector_delete (struct linevector *vec, unsigned int pos,
6951 unsigned int nlines)
6956 last = vec->nlines - nlines;
6957 for (i = pos; i < pos + nlines; ++i)
6959 if (--vec->vector[i]->refcount == 0)
6960 free (vec->vector[i]);
6962 for (i = pos; i < last; ++i)
6963 vec->vector[i] = vec->vector[i + nlines];
6964 vec->nlines -= nlines;
6969 /* Copy FROM to TO, copying the vectors but not the lines pointed to. */
6971 linevector_copy (struct linevector *to, struct linevector *from)
6975 for (ln = 0; ln < to->nlines; ++ln)
6977 if (--to->vector[ln]->refcount == 0)
6978 free (to->vector[ln]);
6980 if (from->nlines > to->lines_alloced)
6982 if (to->lines_alloced == 0)
6983 to->lines_alloced = 10;
6984 while (from->nlines > to->lines_alloced)
6985 to->lines_alloced *= 2;
6986 to->vector = xnrealloc (to->vector,
6988 sizeof (*to->vector));
6990 memcpy (to->vector, from->vector,
6991 xtimes (from->nlines, sizeof (*to->vector)));
6992 to->nlines = from->nlines;
6993 for (ln = 0; ln < to->nlines; ++ln)
6994 ++to->vector[ln]->refcount;
6999 /* Free storage associated with linevector. */
7001 linevector_free (struct linevector *vec)
7005 if (vec->vector != NULL)
7007 for (ln = 0; ln < vec->nlines; ++ln)
7008 if (--vec->vector[ln]->refcount == 0)
7009 free (vec->vector[ln]);
7017 /* Given a textual string giving the month (1-12), terminated with any
7018 character not recognized by atoi, return the 3 character name to
7019 print it with. I do not think it is a good idea to change these
7020 strings based on the locale; they are standard abbreviations (for
7021 example in rfc822 mail messages) which should be widely understood.
7022 Returns a pointer into static readonly storage. */
7024 month_printname (const char *month)
7026 static const char *const months[] =
7027 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
7028 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
7031 mnum = atoi (month);
7032 if (mnum < 1 || mnum > 12)
7034 return months[mnum - 1];
7039 /* Apply changes to the line vector LINES. DIFFBUF is a buffer of
7040 length DIFFLEN holding the change text from an RCS file (the output
7041 of diff -n). NAME is used in error messages. The VERS field of
7042 any line added is set to ADDVERS. The VERS field of any line
7043 deleted is set to DELVERS, unless DELVERS is NULL, in which case
7044 the VERS field of deleted lines is unchanged. The function returns
7045 non-zero if the change text is applied successfully. It returns
7046 zero if the change text does not appear to apply to LINES (e.g., a
7047 line number is invalid). If the change text is improperly
7048 formatted (e.g., it is not the output of diff -n), the function
7049 calls error with a status of 1, causing the program to exit. */
7051 apply_rcs_changes (struct linevector *lines, const char *diffbuf,
7052 size_t difflen, const char *name, RCSVers *addvers,
7058 /* The RCS format throws us for a loop in that the deltafrags (if
7059 we define a deltafrag as an add or a delete) need to be applied
7060 in reverse order. So we stick them into a linked list. */
7062 enum {FRAG_ADD, FRAG_DELETE} type;
7064 unsigned long nlines;
7065 const char *new_lines;
7067 struct deltafrag *next;
7069 struct deltafrag *dfhead;
7070 struct deltafrag *df;
7074 for (p = diffbuf; p != NULL && p < diffbuf + difflen; )
7077 if (op != 'a' && op != 'd')
7078 /* Can't just skip over the deltafrag, because the value
7079 of op determines the syntax. */
7080 error (1, 0, "unrecognized operation '\\x%x' in %s",
7082 df = xmalloc (sizeof (struct deltafrag));
7085 df->pos = strtoul (p, (char **) &q, 10);
7088 error (1, 0, "number expected in %s", name);
7091 error (1, 0, "space expected in %s", name);
7092 df->nlines = strtoul (p, (char **) &q, 10);
7094 error (1, 0, "number expected in %s", name);
7097 error (1, 0, "linefeed expected in %s", name);
7103 df->type = FRAG_ADD;
7105 /* The text we want is the number of lines specified, or
7106 until the end of the value, whichever comes first (it
7107 will be the former except in the case where we are
7108 adding a line which does not end in newline). */
7109 for (q = p; i != 0; ++q)
7112 else if (q == diffbuf + difflen)
7115 error (1, 0, "premature end of change in %s", name);
7120 /* Stash away a pointer to the text we are adding. */
7128 /* Correct for the fact that line numbers in RCS files
7133 df->type = FRAG_DELETE;
7138 for (df = dfhead; df != NULL;)
7142 /* Once an error is encountered, just free the rest of the list and
7149 if (! linevector_add (lines, df->new_lines, df->len, addvers,
7154 if (df->pos > lines->nlines
7155 || df->pos + df->nlines > lines->nlines)
7157 if (delvers != NULL)
7158 for (ln = df->pos; ln < df->pos + df->nlines; ++ln)
7159 lines->vector[ln]->vers = delvers;
7160 linevector_delete (lines, df->pos, df->nlines);
7174 /* Apply an RCS change text to a buffer. The function name starts
7175 with rcs rather than RCS because this does not take an RCSNode
7176 argument. NAME is used in error messages. TEXTBUF is the text
7177 buffer to change, and TEXTLEN is the size. DIFFBUF and DIFFLEN are
7178 the change buffer and size. The new buffer is returned in *RETBUF
7179 and *RETLEN. The new buffer is allocated by xmalloc.
7181 Return 1 for success. On failure, call error and return 0. */
7183 rcs_change_text (const char *name, char *textbuf, size_t textlen,
7184 const char *diffbuf, size_t difflen, char **retbuf,
7187 struct linevector lines;
7193 linevector_init (&lines);
7195 if (! linevector_add (&lines, textbuf, textlen, NULL, 0))
7196 error (1, 0, "cannot initialize line vector");
7198 if (! apply_rcs_changes (&lines, diffbuf, difflen, name, NULL, NULL))
7200 error (0, 0, "invalid change text in %s", name);
7210 for (ln = 0; ln < lines.nlines; ++ln)
7212 n += lines.vector[ln]->len + 1;
7217 for (ln = 0; ln < lines.nlines; ++ln)
7219 memcpy (p, lines.vector[ln]->text, lines.vector[ln]->len);
7220 p += lines.vector[ln]->len;
7221 if (lines.vector[ln]->has_newline)
7225 *retlen = p - *retbuf;
7226 assert (*retlen <= n);
7231 linevector_free (&lines);
7238 /* Walk the deltas in RCS to get to revision VERSION.
7240 If OP is RCS_ANNOTATE, then write annotations using cvs_output.
7242 If OP is RCS_FETCH, then put the contents of VERSION into a
7243 newly-malloc'd array and put a pointer to it in *TEXT. Each line
7244 is \n terminated; the caller is responsible for converting text
7245 files if desired. The total length is put in *LEN.
7247 If FP is non-NULL, it should be a file descriptor open to the file
7248 RCS with file position pointing to the deltas. We close the file
7251 If LOG is non-NULL, then *LOG is set to the log message of VERSION,
7252 and *LOGLEN is set to the length of the log message.
7254 On error, give a fatal error. */
7256 RCS_deltas (RCSNode *rcs, FILE *fp, struct rcsbuffer *rcsbuf,
7257 const char *version, enum rcs_delta_op op, char **text,
7258 size_t *len, char **log, size_t *loglen)
7260 struct rcsbuffer rcsbuf_local;
7261 char *branchversion;
7268 RCSVers *trunk_vers;
7271 int ishead, isnext, isversion, onbranch;
7273 struct linevector headlines;
7274 struct linevector curlines;
7275 struct linevector trunklines;
7283 rcsbuf_cache_open (rcs, rcs->delta_pos, &fp, &rcsbuf_local);
7284 rcsbuf = &rcsbuf_local;
7287 if (log) *log = NULL;
7299 if (op == RCS_ANNOTATE_BACKWARDS) {
7304 linevector_init (&curlines);
7305 linevector_init (&headlines);
7306 linevector_init (&trunklines);
7308 /* We set BRANCHVERSION to the version we are currently looking
7309 for. Initially, this is the version on the trunk from which
7310 VERSION branches off. If VERSION is not a branch, then
7311 BRANCHVERSION is just VERSION. */
7312 branchversion = xstrdup (version);
7313 cpversion = strchr (branchversion, '.');
7314 if (cpversion != NULL)
7315 cpversion = strchr (cpversion + 1, '.');
7316 if (cpversion != NULL)
7320 if (! rcsbuf_getrevnum (rcsbuf, &key))
7321 error (1, 0, "unexpected EOF reading RCS file %s", rcs->print_path);
7323 if (next != NULL && ! STREQ (next, key))
7325 /* This is not the next version we need. It is a branch
7326 version which we want to ignore. */
7334 /* look up the revision */
7335 node = findnode (rcs->versions, key);
7338 "mismatch in rcs file %s between deltas and deltatexts (%s)",
7339 rcs->print_path, key);
7341 /* Stash the previous version. */
7347 /* The top version is either HEAD or
7348 the last version on the branch. */
7349 if (top_vers == NULL || onbranch && backwards)
7352 /* Compare key and trunkversion now, because key points to
7353 storage controlled by rcsbuf_getkey. */
7354 if (STREQ (branchversion, key))
7359 if (backwards && STREQ (version, key)) {
7363 for (ln = 0; ln < curlines.nlines; ++ln)
7364 curlines.vector[ln]->vers = NULL;
7367 linevector_copy (&headlines, &curlines);
7375 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7376 error (1, 0, "%s does not appear to be a valid rcs file",
7381 && STREQ (key, "log")
7382 && STREQ (branchversion, version))
7386 error (0, 0, "Duplicate `log' keyword in RCS file (`%s').",
7390 *log = rcsbuf_valcopy (rcsbuf, value, 0, loglen);
7393 if (STREQ (key, "text"))
7395 rcsbuf_valpolish (rcsbuf, value, 0, &vallen);
7398 if (! linevector_add (&curlines, value, vallen,
7399 backwards ? vers : NULL, 0))
7400 error (1, 0, "invalid rcs file %s", rcs->print_path);
7406 RCSVers *addv, *delv;
7425 if (! apply_rcs_changes (&curlines, value, vallen,
7428 error (1, 0, "invalid change text in %s", rcs->print_path);
7436 /* This is either the version we want, or it is the
7437 branchpoint to the version we want. */
7438 if (STREQ (branchversion, version))
7440 /* This is the version we want. */
7441 linevector_copy (&headlines, &curlines);
7443 /* If we are annotating backwards, we have to
7444 continue tracking when we're tracking a branch. */
7445 if (onbranch && !backwards)
7447 /* We have found this version by tracking up a
7448 branch. Restore back to the lines we saved
7449 when we left the trunk, and continue tracking
7454 linevector_copy (&curlines, &trunklines);
7461 /* We need to look up the branch. */
7464 if (numdots (branchversion) < 2)
7468 /* We are leaving the trunk; save the current
7469 lines so that we can restore them when we
7470 continue tracking down the trunk. */
7472 linevector_copy (&trunklines, &curlines);
7474 /* Reset the version information we have
7475 accumulated so far. It only applies to the
7476 changes from the head to this version. */
7477 for (ln = 0; ln < curlines.nlines; ++ln)
7478 curlines.vector[ln]->vers = NULL;
7481 /* The next version we want is the entry on
7482 VERS->branches which matches this branch. For
7483 example, suppose VERSION is 1.21.4.3 and
7484 BRANCHVERSION was 1.21. Then we look for an entry
7485 starting with "1.21.4" and we'll put it (probably
7486 1.21.4.1) in NEXT. We'll advance BRANCHVERSION by
7487 two dots (in this example, to 1.21.4.3). */
7489 if (vers->branches == NULL)
7490 error (1, 0, "missing expected branches in %s",
7493 error (1, 0, "Invalid revision number in `%s'.",
7497 cpversion = strchr (cpversion, '.');
7498 if (cpversion == NULL)
7499 error (1, 0, "version number confusion in %s",
7501 for (p = vers->branches->list->next;
7502 p != vers->branches->list;
7504 if (strncmp (p->key, branchversion,
7505 cpversion - branchversion) == 0)
7507 if (p == vers->branches->list)
7508 error (1, 0, "missing expected branch in %s",
7513 cpversion = strchr (cpversion + 1, '.');
7514 if (cpversion != NULL)
7518 if (op == RCS_FETCH && foundhead)
7520 } while (next != NULL);
7522 free (branchversion);
7524 rcsbuf_cache (rcs, rcsbuf);
7527 error (1, 0, "could not find desired version %s in %s",
7528 version, rcs->print_path);
7530 /* Now print out or return the data we have just computed. */
7537 for (ln = 0; ln < headlines.nlines; ++ln)
7540 /* Period which separates year from month in date. */
7542 /* Period which separates month from day in date. */
7546 prvers = headlines.vector[ln]->vers;
7550 buf = xmalloc (strlen (prvers->version) + 24);
7551 sprintf (buf, "%-12s (%-8.8s ",
7554 cvs_output (buf, 0);
7557 /* Now output the date. */
7558 ym = strchr (prvers->date, '.');
7561 cvs_output ("??", 0);
7562 cvs_output ("-???", 0);
7563 cvs_output ("-??", 0);
7567 md = strchr (ym + 1, '.');
7569 cvs_output ("??", 0);
7571 cvs_output (md + 1, 2);
7573 cvs_output ("-", 1);
7574 cvs_output (month_printname (ym + 1), 0);
7575 cvs_output ("-", 1);
7576 /* Only output the last two digits of the year. Our output
7577 lines are long enough as it is without printing the
7579 cvs_output (ym - 2, 2);
7581 cvs_output ("): ", 0);
7582 if (headlines.vector[ln]->len != 0)
7583 cvs_output (headlines.vector[ln]->text,
7584 headlines.vector[ln]->len);
7585 cvs_output ("\n", 1);
7595 assert (text != NULL);
7596 assert (len != NULL);
7599 for (ln = 0; ln < headlines.nlines; ++ln)
7601 n += headlines.vector[ln]->len + 1;
7604 for (ln = 0; ln < headlines.nlines; ++ln)
7606 memcpy (p, headlines.vector[ln]->text,
7607 headlines.vector[ln]->len);
7608 p += headlines.vector[ln]->len;
7609 if (headlines.vector[ln]->has_newline)
7618 linevector_free (&curlines);
7619 linevector_free (&headlines);
7620 linevector_free (&trunklines);
7627 /* Read the information for a single delta from the RCS buffer RCSBUF,
7628 whose name is RCSFILE. *KEYP and *VALP are either NULL, or the
7629 first key/value pair to read, as set by rcsbuf_getkey. Return NULL
7630 if there are no more deltas. Store the key/value pair which
7631 terminated the read in *KEYP and *VALP. */
7633 getdelta (struct rcsbuffer *rcsbuf, char *rcsfile, char **keyp, char **valp)
7636 char *key, *value, *cp;
7639 /* Get revision number if it wasn't passed in. This uses
7640 rcsbuf_getkey because it doesn't croak when encountering
7641 unexpected input. As a result, we have to play unholy games
7642 with `key' and `value'. */
7650 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7651 error (1, 0, "%s: unexpected EOF", rcsfile);
7654 /* Make sure that it is a revision number and not a cabbage
7657 (isdigit ((unsigned char) *cp) || *cp == '.') && *cp != '\0';
7660 /* Note that when comparing with RCSDATE, we are not massaging
7661 VALUE from the string found in the RCS file. This is OK since
7662 we know exactly what to expect. */
7663 if (*cp != '\0' || strncmp (RCSDATE, value, (sizeof RCSDATE) - 1) != 0)
7670 vnode = xmalloc (sizeof (RCSVers));
7671 memset (vnode, 0, sizeof (RCSVers));
7673 vnode->version = xstrdup (key);
7675 /* Grab the value of the date from value. Note that we are not
7676 massaging VALUE from the string found in the RCS file. */
7677 cp = value + (sizeof RCSDATE) - 1; /* skip the "date" keyword */
7678 while (whitespace (*cp)) /* take space off front of value */
7681 vnode->date = xstrdup (cp);
7683 /* Get author field. */
7684 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7686 error (1, 0, "unexpected end of file reading %s", rcsfile);
7688 if (! STREQ (key, "author"))
7690 unable to parse %s; `author' not in the expected place", rcsfile);
7691 vnode->author = rcsbuf_valcopy (rcsbuf, value, 0, NULL);
7693 /* Get state field. */
7694 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7696 error (1, 0, "unexpected end of file reading %s", rcsfile);
7698 if (! STREQ (key, "state"))
7700 unable to parse %s; `state' not in the expected place", rcsfile);
7701 vnode->state = rcsbuf_valcopy (rcsbuf, value, 0, NULL);
7702 /* The value is optional, according to rcsfile(5). */
7703 if (value != NULL && STREQ (value, RCSDEAD))
7708 /* Note that "branches" and "next" are in fact mandatory, according
7711 /* fill in the branch list (if any branches exist) */
7712 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7714 error (1, 0, "unexpected end of file reading %s", rcsfile);
7716 if (STREQ (key, RCSDESC))
7720 /* Probably could/should be a fatal error. */
7721 error (0, 0, "warning: 'branches' keyword missing from %s", rcsfile);
7726 vnode->branches = getlist ();
7727 /* Note that we are not massaging VALUE from the string found
7729 do_branches (vnode->branches, value);
7732 /* fill in the next field if there is a next revision */
7733 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7735 error (1, 0, "unexpected end of file reading %s", rcsfile);
7737 if (STREQ (key, RCSDESC))
7741 /* Probably could/should be a fatal error. */
7742 error (0, 0, "warning: 'next' keyword missing from %s", rcsfile);
7746 vnode->next = rcsbuf_valcopy (rcsbuf, value, 0, NULL);
7749 * XXX - this is where we put the symbolic link stuff???
7750 * (into newphrases in the deltas).
7754 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7755 error (1, 0, "unexpected end of file reading %s", rcsfile);
7757 /* The `desc' keyword is the end of the deltas. */
7758 if (strcmp (key, RCSDESC) == 0)
7761 #ifdef PRESERVE_PERMISSIONS_SUPPORT
7763 /* The `hardlinks' value is a group of words, which must
7764 be parsed separately and added as a list to vnode->hardlinks. */
7765 if (strcmp (key, "hardlinks") == 0)
7769 vnode->hardlinks = getlist();
7770 while ((word = rcsbuf_valword (rcsbuf, &value)) != NULL)
7772 Node *n = getnode();
7774 addnode (vnode->hardlinks, n);
7780 /* Enable use of repositories created by certain obsolete
7781 versions of CVS. This code should remain indefinately;
7782 there is no procedure for converting old repositories, and
7783 checking for it is harmless. */
7784 if (STREQ (key, RCSDEAD))
7787 if (vnode->state != NULL)
7788 free (vnode->state);
7789 vnode->state = xstrdup (RCSDEAD);
7792 /* if we have a new revision number, we're done with this delta */
7794 (isdigit ((unsigned char) *cp) || *cp == '.') && *cp != '\0';
7797 /* Note that when comparing with RCSDATE, we are not massaging
7798 VALUE from the string found in the RCS file. This is OK
7799 since we know exactly what to expect. */
7800 if (*cp == '\0' && strncmp (RCSDATE, value, strlen (RCSDATE)) == 0)
7803 /* At this point, key and value represent a user-defined field
7804 in the delta node. */
7805 if (vnode->other_delta == NULL)
7806 vnode->other_delta = getlist ();
7808 kv->type = rcsbuf_valcmp (rcsbuf) ? RCSCMPFLD : RCSFIELD;
7809 kv->key = xstrdup (key);
7810 kv->data = rcsbuf_valcopy (rcsbuf, value, kv->type == RCSFIELD, NULL);
7811 if (addnode (vnode->other_delta, kv) != 0)
7813 /* Complaining about duplicate keys in newphrases seems
7814 questionable, in that we don't know what they mean and
7815 doc/RCSFILES has no prohibition on several newphrases
7816 with the same key. But we can't store more than one as
7817 long as we store them in a List *. */
7818 error (0, 0, "warning: duplicate key `%s' in RCS file `%s'",
7824 /* Return the key which caused us to fail back to the caller. */
7834 freedeltatext (Deltatext *d)
7836 if (d->version != NULL)
7840 if (d->text != NULL)
7842 if (d->other != NULL)
7843 dellist (&d->other);
7848 RCS_getdeltatext (RCSNode *rcs, FILE *fp, struct rcsbuffer *rcsbuf)
7855 /* Get the revision number. */
7856 if (! rcsbuf_getrevnum (rcsbuf, &num))
7858 /* If num == NULL, it means we reached EOF naturally. That's
7863 error (1, 0, "%s: unexpected EOF", rcs->print_path);
7866 p = findnode (rcs->versions, num);
7868 error (1, 0, "mismatch in rcs file %s between deltas and deltatexts (%s)",
7869 rcs->print_path, num);
7871 d = xmalloc (sizeof (Deltatext));
7872 d->version = xstrdup (num);
7874 /* Get the log message. */
7875 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7876 error (1, 0, "%s, delta %s: unexpected EOF", rcs->print_path, num);
7877 if (! STREQ (key, "log"))
7878 error (1, 0, "%s, delta %s: expected `log', got `%s'",
7879 rcs->print_path, num, key);
7880 d->log = rcsbuf_valcopy (rcsbuf, value, 0, NULL);
7882 /* Get random newphrases. */
7883 d->other = getlist();
7886 if (! rcsbuf_getkey (rcsbuf, &key, &value))
7887 error (1, 0, "%s, delta %s: unexpected EOF", rcs->print_path, num);
7889 if (STREQ (key, "text"))
7893 p->type = rcsbuf_valcmp (rcsbuf) ? RCSCMPFLD : RCSFIELD;
7894 p->key = xstrdup (key);
7895 p->data = rcsbuf_valcopy (rcsbuf, value, p->type == RCSFIELD, NULL);
7896 if (addnode (d->other, p) < 0)
7898 error (0, 0, "warning: %s, delta %s: duplicate field `%s'",
7899 rcs->print_path, num, key);
7903 /* Get the change text. We already know that this key is `text'. */
7904 d->text = rcsbuf_valcopy (rcsbuf, value, 0, &d->len);
7911 /* RCS output functions, for writing RCS format files from RCSNode
7914 For most of this work, RCS 5.7 uses an `aprintf' function which aborts
7915 program upon error. Instead, these functions check the output status
7916 of the stream right before closing it, and aborts if an error condition
7917 is found. The RCS solution is probably the better one: it produces
7918 more overhead, but will produce a clearer diagnostic in the case of
7919 catastrophic error. In either case, however, the repository will probably
7920 not get corrupted. */
7922 putsymbol_proc (Node *symnode, void *fparg)
7926 /* A fiddly optimization: this code used to just call fprintf, but
7927 in an old repository with hundreds of tags this can get called
7928 hundreds of thousands of times when doing a cvs tag. Since
7929 tagging is a relatively common operation, and using putc and
7930 fputs is just as comprehensible, the change is worthwhile. */
7933 fputs (symnode->key, fp);
7935 fputs (symnode->data, fp);
7941 /* putlock_proc is like putsymbol_proc, but key and data are reversed. */
7943 putlock_proc (Node *symnode, void *fp)
7945 return fprintf (fp, "\n\t%s:%s", (char *)symnode->data, symnode->key);
7951 putrcsfield_proc (Node *node, void *vfp)
7955 /* Some magic keys used internally by CVS start with `;'. Skip them. */
7956 if (node->key[0] == ';')
7959 fprintf (fp, "\n%s\t", node->key);
7960 if (node->data != NULL)
7962 /* If the field's value contains evil characters,
7963 it must be stringified. */
7964 /* FIXME: This does not quite get it right. "7jk8f" is not a valid
7965 value for a value in a newpharse, according to doc/RCSFILES,
7966 because digits are not valid in an "id". We might do OK by
7967 always writing strings (enclosed in @@). Would be nice to
7968 explicitly mention this one way or another in doc/RCSFILES.
7969 A case where we are wrong in a much more clear-cut way is that
7970 we let through non-graphic characters such as whitespace and
7971 control characters. */
7973 if (node->type == RCSCMPFLD || strpbrk (node->data, "$,.:;@") == NULL)
7974 fputs (node->data, fp);
7978 expand_at_signs (node->data, (off_t) strlen (node->data), fp);
7983 /* desc, log and text fields should not be terminated with semicolon;
7984 all other fields should be. */
7985 if (! STREQ (node->key, "desc") &&
7986 ! STREQ (node->key, "log") &&
7987 ! STREQ (node->key, "text"))
7996 #ifdef PRESERVE_PERMISSIONS_SUPPORT
7998 /* Save a filename in a `hardlinks' RCS field. NODE->KEY will contain
7999 a full pathname, but currently only basenames are stored in the RCS
8000 node. Assume that the filename includes nasty characters and
8004 puthardlink_proc (node, vfp)
8009 char *basename = strrchr (node->key, '/');
8011 if (basename == NULL)
8012 basename = node->key;
8018 (void) expand_at_signs (basename, strlen (basename), fp);
8024 #endif /* PRESERVE_PERMISSIONS_SUPPORT */
8028 /* Output the admin node for RCS into stream FP. */
8030 RCS_putadmin (RCSNode *rcs, FILE *fp)
8032 fprintf (fp, "%s\t%s;\n", RCSHEAD, rcs->head ? rcs->head : "");
8034 fprintf (fp, "%s\t%s;\n", RCSBRANCH, rcs->branch);
8036 fputs ("access", fp);
8040 s = xstrdup (rcs->access);
8041 for (p = strtok (s, " \n\t"); p != NULL; p = strtok (NULL, " \n\t"))
8042 fprintf (fp, "\n\t%s", p);
8047 fputs (RCSSYMBOLS, fp);
8048 /* If we haven't had to convert the symbols to a list yet, don't
8049 force a conversion now; just write out the string. */
8050 if (rcs->symbols == NULL && rcs->symbols_data != NULL)
8053 fputs (rcs->symbols_data, fp);
8056 walklist (RCS_symbols (rcs), putsymbol_proc, fp);
8059 fputs ("locks", fp);
8060 if (rcs->locks_data)
8061 fprintf (fp, "\t%s", rcs->locks_data);
8062 else if (rcs->locks)
8063 walklist (rcs->locks, putlock_proc, fp);
8064 if (rcs->strict_locks)
8065 fprintf (fp, "; strict");
8070 fprintf (fp, "comment\t@");
8071 expand_at_signs (rcs->comment, (off_t) strlen (rcs->comment), fp);
8074 if (rcs->expand && ! STREQ (rcs->expand, "kv"))
8075 fprintf (fp, "%s\t@%s@;\n", RCSEXPAND, rcs->expand);
8077 walklist (rcs->other, putrcsfield_proc, fp);
8085 putdelta (RCSVers *vers, FILE *fp)
8089 /* Skip if no revision was supplied, or if it is outdated (cvs admin -o) */
8090 if (vers == NULL || vers->outdated)
8093 fprintf (fp, "\n%s\n%s\t%s;\t%s %s;\t%s %s;\nbranches",
8095 RCSDATE, vers->date,
8096 "author", vers->author,
8097 "state", vers->state ? vers->state : "");
8099 if (vers->branches != NULL)
8101 start = vers->branches->list;
8102 for (bp = start->next; bp != start; bp = bp->next)
8103 fprintf (fp, "\n\t%s", bp->key);
8106 fprintf (fp, ";\nnext\t%s;", vers->next ? vers->next : "");
8108 walklist (vers->other_delta, putrcsfield_proc, fp);
8110 #ifdef PRESERVE_PERMISSIONS_SUPPORT
8111 if (vers->hardlinks)
8113 fprintf (fp, "\nhardlinks");
8114 walklist (vers->hardlinks, puthardlink_proc, fp);
8124 RCS_putdtree (RCSNode *rcs, char *rev, FILE *fp)
8129 /* Previously, this function used a recursive implementation, but
8130 if the trunk has a huge number of revisions and the program
8131 stack is not big, a stack overflow could occur, so this
8132 nonrecursive version was developed to be more safe. */
8133 Node *branchlist, *onebranch;
8135 List *onebranchlist;
8140 branches = getlist();
8142 for (; rev != NULL;)
8144 /* Find the delta node for this revision. */
8145 p = findnode (rcs->versions, rev);
8149 "error parsing repository file %s, file may be corrupt.",
8155 /* Print the delta node and go for its `next' node. This
8156 prints the trunk. If there are any branches printed on this
8157 revision, mark we have some. */
8158 putdelta (versp, fp);
8159 /* Store branch information into branch list so to write its
8161 if (versp->branches != NULL)
8164 branch->data = versp->branches;
8166 addnode(branches, branch);
8172 /* If there are any branches printed on this revision,
8173 print those trunks as well. */
8174 branchlist = branches->list;
8175 for (branch = branchlist->next;
8176 branch != branchlist;
8177 branch = branch->next)
8179 onebranchlist = (List *)(branch->data);
8180 onebranch = onebranchlist->list;
8181 for (p = onebranch->next; p != onebranch; p = p->next)
8182 RCS_putdtree (rcs, p->key, fp);
8184 branch->data = NULL; /* so to prevent its freeing on dellist */
8193 RCS_putdesc (RCSNode *rcs, FILE *fp)
8195 fprintf (fp, "\n\n%s\n@", RCSDESC);
8196 if (rcs->desc != NULL)
8198 off_t len = (off_t) strlen (rcs->desc);
8201 expand_at_signs (rcs->desc, len, fp);
8202 if (rcs->desc[len-1] != '\n')
8212 putdeltatext (FILE *fp, Deltatext *d)
8214 fprintf (fp, "\n\n%s\nlog\n@", d->version);
8217 int loglen = strlen (d->log);
8218 expand_at_signs (d->log, (off_t) loglen, fp);
8219 if (d->log[loglen-1] != '\n')
8224 walklist (d->other, putrcsfield_proc, fp);
8226 fputs ("\ntext\n@", fp);
8227 if (d->text != NULL)
8228 expand_at_signs (d->text, (off_t) d->len, fp);
8234 /* TODO: the whole mechanism for updating deltas is kludgey... more
8235 sensible would be to supply all the necessary info in a `newdeltatext'
8236 field for RCSVers nodes. -twp */
8238 /* Copy delta text nodes from FIN to FOUT. If NEWDTEXT is non-NULL, it
8239 is a new delta text node, and should be added to the tree at the
8240 node whose revision number is INSERTPT. (Note that trunk nodes are
8241 written in decreasing order, and branch nodes are written in
8242 increasing order.) */
8244 RCS_copydeltas (RCSNode *rcs, FILE *fin, struct rcsbuffer *rcsbufin,
8245 FILE *fout, Deltatext *newdtext, char *insertpt)
8250 int insertbefore, found;
8259 /* Count the number of versions for which we have to do some
8260 special operation. */
8261 actions = walklist (rcs->versions, count_delta_actions, NULL);
8263 /* Make a note of whether NEWDTEXT should be inserted
8264 before or after its INSERTPT. */
8265 insertbefore = (newdtext != NULL && numdots (newdtext->version) == 1);
8267 while (actions != 0 || newdtext != NULL)
8271 dtext = RCS_getdeltatext (rcs, fin, rcsbufin);
8273 /* We shouldn't hit EOF here, because that would imply that
8274 some action was not taken, or that we could not insert
8277 error (1, 0, "internal error: EOF too early in RCS_copydeltas");
8279 found = (insertpt != NULL && STREQ (dtext->version, insertpt));
8280 if (found && insertbefore)
8282 putdeltatext (fout, newdtext);
8287 np = findnode (rcs->versions, dtext->version);
8290 /* If this revision has been outdated, just skip it. */
8291 if (dadmin->outdated)
8293 freedeltatext (dtext);
8298 /* Update the change text for this delta. New change text
8299 data may come from cvs admin -m, cvs admin -o, or cvs ci. */
8300 if (dadmin->text != NULL)
8302 if (dadmin->text->log != NULL || dadmin->text->text != NULL)
8304 if (dadmin->text->log != NULL)
8307 dtext->log = dadmin->text->log;
8308 dadmin->text->log = NULL;
8310 if (dadmin->text->text != NULL)
8313 dtext->text = dadmin->text->text;
8314 dtext->len = dadmin->text->len;
8315 dadmin->text->text = NULL;
8318 putdeltatext (fout, dtext);
8319 freedeltatext (dtext);
8321 if (found && !insertbefore)
8323 putdeltatext (fout, newdtext);
8329 /* Copy the rest of the file directly, without bothering to
8330 interpret it. The caller will handle error checking by calling
8333 We just wrote a newline to the file, either in putdeltatext or
8334 in the caller. However, we may not have read the corresponding
8335 newline from the file, because rcsbuf_getkey returns as soon as
8336 it finds the end of the '@' string for the desc or text key.
8337 Therefore, we may read three newlines when we should really
8338 only write two, and we check for that case here. This is not
8339 an semantically important issue; we only do it to make our RCS
8340 files look traditional. */
8344 rcsbuf_get_buffered (rcsbufin, &bufrest, &buflen);
8347 if (bufrest[0] != '\n'
8348 || strncmp (bufrest, "\n\n\n", buflen < 3 ? buflen : 3) != 0)
8364 fwrite (bufrest, 1, buflen, fout);
8367 /* This bit isn't necessary when using mmap since the entire file
8368 * will already be available via the RCS buffer. Besides, the
8369 * mmap code doesn't always keep the file pointer up to date, so
8370 * this adds some data twice.
8372 while ((got = fread (buf, 1, sizeof buf, fin)) != 0)
8377 && strncmp (buf, "\n\n\n", nls) == 0)
8379 fwrite (buf + 1, 1, got - 1, fout);
8383 fwrite (buf, 1, got, fout);
8388 #endif /* HAVE_MMAP */
8393 /* A helper procedure for RCS_copydeltas. This is called via walklist
8394 to count the number of RCS revisions for which some special action
8397 count_delta_actions (Node *np, void *ignore)
8399 RCSVers *dadmin = np->data;
8401 if (dadmin->outdated)
8404 if (dadmin->text != NULL
8405 && (dadmin->text->log != NULL || dadmin->text->text != NULL))
8416 * Clean up temporary files.
8419 * This function needs to be reentrant since a call to exit() can cause a
8420 * call to this function, which can then be interrupted by a signal, which
8421 * can cause a second call to this function.
8429 TRACE (TRACE_FUNCTION, "rcs_cleanup()");
8431 /* FIXME: Do not perform buffered I/O from an interrupt handler like
8432 * this (via error). However, I'm leaving the error-calling code there
8433 * in the hope that on the rare occasion the error call is actually made
8434 * (e.g., a fluky I/O error or permissions problem prevents the deletion
8435 * of a just-created file) reentrancy won't be an issue.
8438 /* We don't want to be interrupted during calls which set globals to NULL,
8439 * but we know that by the time we reach this function, interrupts have
8440 * already been blocked.
8442 if (rcs_lockfile != NULL)
8444 /* Use a tmp var since any of these functions could call exit, causing
8445 * us to be called a second time.
8447 char *tmp = rcs_lockfile;
8448 rcs_lockfile = NULL;
8449 if (rcs_lockfd >= 0)
8451 if (close (rcs_lockfd) != 0)
8452 error (0, errno, "error closing lock file %s", tmp);
8456 /* Note that the checks for existence_error are because we can be
8457 * called from a signal handler, so we don't know whether the
8458 * files got created.
8460 if (unlink_file (tmp) < 0
8461 && !existence_error (errno))
8462 error (0, errno, "cannot remove %s", tmp);
8468 /* RCS_internal_lockfile and RCS_internal_unlockfile perform RCS-style
8469 locking on the specified RCSFILE: for a file called `foo,v', open
8470 for writing a file called `,foo,'.
8472 Note that we what do here is quite different from what RCS does.
8473 RCS creates the ,foo, file before it reads the RCS file (if it
8474 knows that it will be writing later), so that it actually serves as
8475 a lock. We don't; instead we rely on CVS writelocks. This means
8476 that if someone is running RCS on the file at the same time they
8477 are running CVS on it, they might lose (we read the file,
8478 then RCS writes it, then we write it, clobbering the
8479 changes made by RCS). I believe the current sentiment about this
8480 is "well, don't do that".
8482 A concern has been expressed about whether adopting the RCS
8483 strategy would slow us down. I don't think so, since we need to
8484 write the ,foo, file anyway (unless perhaps if O_EXCL is slower or
8487 These do not perform quite the same function as the RCS -l option
8488 for locking files: they are intended to prevent competing RCS
8489 processes from stomping all over each other's laundry. Hence,
8490 they are `internal' locking functions.
8492 If there is an error, give a fatal error; if we return we always
8493 return a non-NULL value. */
8495 rcs_internal_lockfile (char *rcsfile)
8499 static int first_call = 1;
8504 /* Clean up if we get a signal or exit. */
8505 cleanup_register (rcs_cleanup);
8508 /* Get the lock file name: `,file,' for RCS file `file,v'. */
8509 assert (rcs_lockfile == NULL);
8510 assert (rcs_lockfd < 0);
8511 rcs_lockfile = rcs_lockfilename (rcsfile);
8513 /* Use the existing RCS file mode, or read-only if this is a new
8514 file. (Really, this is a lie -- if this is a new file,
8515 RCS_checkin uses the permissions from the working copy. For
8516 actually creating the file, we use 0444 as a safe default mode.) */
8517 if (stat (rcsfile, &rstat) < 0)
8519 if (existence_error (errno))
8520 rstat.st_mode = S_IRUSR | S_IRGRP | S_IROTH;
8522 error (1, errno, "cannot stat %s", rcsfile);
8525 /* Try to open exclusively. POSIX.1 guarantees that O_EXCL|O_CREAT
8526 guarantees an exclusive open. According to the RCS source, with
8527 NFS v2 we must also throw in O_TRUNC and use an open mask that makes
8528 the file unwriteable. For extensive justification, see the comments for
8529 rcswriteopen() in rcsedit.c, in RCS 5.7. This is kind of pointless
8530 in the CVS case; see comment at the start of this file concerning
8531 general ,foo, file strategy.
8533 There is some sentiment that with NFSv3 and such, that one can
8534 rely on O_EXCL these days. This might be true for unix (I
8535 don't really know), but I am still pretty skeptical in the case
8536 of the non-unix systems. */
8537 rcs_lockfd = open (rcs_lockfile,
8538 OPEN_BINARY | O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
8539 S_IRUSR | S_IRGRP | S_IROTH);
8543 error (1, errno, "could not open lock file `%s'", rcs_lockfile);
8546 /* Force the file permissions, and return a stream object. */
8547 /* Because we change the modes later, we don't worry about
8548 this in the non-HAVE_FCHMOD case. */
8550 if (fchmod (rcs_lockfd, rstat.st_mode) < 0)
8551 error (1, errno, "cannot change mode for %s", rcs_lockfile);
8553 fp = fdopen (rcs_lockfd, FOPEN_BINARY_WRITE);
8555 error (1, errno, "cannot fdopen %s", rcs_lockfile);
8563 rcs_internal_unlockfile (FILE *fp, char *rcsfile)
8565 assert (rcs_lockfile != NULL);
8566 assert (rcs_lockfd >= 0);
8568 /* Abort if we could not write everything successfully to LOCKFILE.
8569 This is not a great error-handling mechanism, but should prevent
8570 corrupting the repository. */
8573 /* Using errno here may well be misleanding since the most recent
8574 call that set errno may not have anything whatsoever to do with
8575 the error that set the flag, but it's better than nothing. The
8576 real solution is to check each call to fprintf rather than waiting
8577 until the end like this. */
8578 error (1, errno, "error writing to lock file %s", rcs_lockfile);
8580 /* Flush and sync the file, or the user may be told the commit completed,
8581 * while a server crash/power failure could still cause the data to be
8584 * Invoking rename(",<file>," , "<file>,v") on Linux and almost all UNIXs
8585 * only flushes the inode for the target file to disk, it does not
8586 * guarantee flush of the kernel buffers allocated for the ,<file>,.
8587 * Depending upon the load on the machine, the Linux kernel's flush daemon
8588 * process may not flush for a while. In the meantime the CVS transaction
8589 * could have been declared committed to the end CVS user (CVS process has
8590 * returned the final "OK"). If the machine crashes prior to syncing the
8591 * changes to disk, the committed transaction can be lost.
8593 if (fflush (fp) != 0)
8594 error (1, errno, "error flushing file `%s' to kernel buffers",
8597 if (fsync (rcs_lockfd) < 0)
8598 error (1, errno, "error fsyncing file `%s'", rcs_lockfile);
8601 if (fclose (fp) == EOF)
8602 error (1, errno, "error closing lock file %s", rcs_lockfile);
8605 rename_file (rcs_lockfile, rcsfile);
8608 /* Use a temporary to make sure there's no interval
8609 (after rcs_lockfile has been freed but before it's set to NULL)
8610 during which the signal handler's use of rcs_lockfile would
8611 reference freed memory. */
8612 char *tmp = rcs_lockfile;
8613 rcs_lockfile = NULL;
8621 rcs_lockfilename (const char *rcsfile)
8623 char *lockfile, *lockp;
8624 const char *rcsbase, *rcsp, *rcsend;
8627 /* Create the lockfile name. */
8628 rcslen = strlen (rcsfile);
8629 lockfile = xmalloc (rcslen + 10);
8630 rcsbase = last_component (rcsfile);
8631 rcsend = rcsfile + rcslen - sizeof(RCSEXT);
8632 for (lockp = lockfile, rcsp = rcsfile; rcsp < rcsbase; ++rcsp)
8635 while (rcsp <= rcsend)
8645 /* Rewrite an RCS file. The basic idea here is that the caller should
8646 first call RCS_reparsercsfile, then munge the data structures as
8647 desired (via RCS_delete_revs, RCS_settag, &c), then call RCS_rewrite. */
8649 RCS_rewrite (RCSNode *rcs, Deltatext *newdtext, char *insertpt)
8652 struct rcsbuffer rcsbufin;
8657 /* Make sure we're operating on an actual file and not a symlink. */
8658 resolve_symlink (&(rcs->path));
8660 fout = rcs_internal_lockfile (rcs->path);
8662 RCS_putadmin (rcs, fout);
8663 RCS_putdtree (rcs, rcs->head, fout);
8664 RCS_putdesc (rcs, fout);
8666 /* Open the original RCS file and seek to the first delta text. */
8667 rcsbuf_cache_open (rcs, rcs->delta_pos, &fin, &rcsbufin);
8669 /* Update delta_pos to the current position in the output file.
8670 Do NOT move these statements: they must be done after fin has
8671 been positioned at the old delta_pos, but before any delta
8672 texts have been written to fout.
8674 rcs->delta_pos = ftello (fout);
8675 if (rcs->delta_pos == -1)
8676 error (1, errno, "cannot ftello in RCS file %s", rcs->path);
8678 RCS_copydeltas (rcs, fin, &rcsbufin, fout, newdtext, insertpt);
8680 /* We don't want to call rcsbuf_cache here, since we're about to
8682 rcsbuf_close (&rcsbufin);
8684 /* The only case in which using errno here would be meaningful
8685 is if we happen to have left errno unmolested since the call
8686 which produced the error (e.g. fread). That is pretty
8687 fragile even if it happens to sometimes be true. The real
8688 solution is to make sure that all the code which reads
8689 from fin checks for errors itself (some does, some doesn't). */
8690 error (0, 0, "warning: ferror set while rewriting RCS file `%s'", rcs->path);
8691 if (fclose (fin) < 0)
8692 error (0, errno, "warning: closing RCS file `%s'", rcs->path);
8694 rcs_internal_unlockfile (fout, rcs->path);
8699 /* Abandon changes to an RCS file. */
8701 RCS_abandon (RCSNode *rcs)
8703 free_rcsnode_contents (rcs);
8704 rcs->symbols_data = NULL;
8707 rcs->locks_data = NULL;
8708 rcs->comment = NULL;
8710 rcs->flags |= PARTIAL;
8716 * For a given file with full pathname PATH and revision number REV,
8717 * produce a file label suitable for passing to diff. The default
8718 * file label as used by RCS 5.7 looks like this:
8720 * FILENAME <tab> YYYY/MM/DD <sp> HH:MM:SS <tab> REVNUM
8722 * The date and time used are the revision's last checkin date and time.
8723 * If REV is NULL, use the working copy's mtime instead.
8725 * /dev/null is not statted but assumed to have been created on the Epoch.
8726 * At least using the POSIX.2 definition of patch, this should cause creation
8727 * of files on platforms such as Windoze where the null IO device isn't named
8728 * /dev/null to be parsed by patch properly.
8731 make_file_label (const char *path, const char *rev, RCSNode *rcs)
8733 char datebuf[MAXDATELEN + 1];
8738 char date[MAXDATELEN + 1];
8739 /* revs cannot be attached to /dev/null ... duh. */
8740 assert (strcmp(DEVNULL, path));
8741 RCS_getrevtime (rcs, rev, datebuf, 0);
8742 (void) date_to_internet (date, datebuf);
8743 label = Xasprintf ("-L%s\t%s\t%s", path, date, rev);
8750 if (strcmp(DEVNULL, path))
8752 const char *file = last_component (path);
8753 if (stat (file, &sb) < 0)
8754 /* Assume that if the stat fails,then the later read for the
8757 error (1, errno, "could not get info for `%s'", path);
8758 wm = gmtime (&sb.st_mtime);
8766 (void) tm_to_internet (datebuf, wm);
8767 label = Xasprintf ("-L%s\t%s", path, datebuf);
8775 * Set up a local/custom RCS keyword for expansion.
8778 * infopath Path to file being parsed, for error messages.
8779 * ln Line number of INFOPATH being processed, for error
8788 RCS_setlocalid (const char *infopath, unsigned int ln,
8789 void **keywords_in, const char *arg)
8791 char *copy, *next, *key, *s;
8792 struct rcs_keyword *keywords;
8793 enum keyword save_expandto;
8796 *keywords_in = new_keywords ();
8797 keywords = *keywords_in;
8799 copy = xstrdup (arg);
8801 key = strtok (next, "=");
8806 for (s = key; *s != '\0'; s++)
8808 if (! isalpha ((unsigned char) *s))
8810 if (!parse_error (infopath, ln))
8812 "%s [%u]: LocalKeyword ignored: Bad character `%c' in key `%s'",
8813 primary_root_inverse_translate (infopath),
8820 save_expandto = keywords[KEYWORD_LOCALID].expandto;
8823 while ((key = strtok (NULL, ",")) != NULL) {
8824 if (!strcmp(key, keywords[KEYWORD_ID].string))
8825 keywords[KEYWORD_LOCALID].expandto = KEYWORD_ID;
8826 else if (!strcmp(key, keywords[KEYWORD_HEADER].string))
8827 keywords[KEYWORD_LOCALID].expandto = KEYWORD_HEADER;
8828 else if (!strcmp(key, keywords[KEYWORD_CVSHEADER].string))
8829 keywords[KEYWORD_LOCALID].expandto = KEYWORD_CVSHEADER;
8832 keywords[KEYWORD_LOCALID].expandto = save_expandto;
8833 if (!parse_error (infopath, ln))
8835 "%s [%u]: LocalKeyword ignored: Unknown LocalId mode: `%s'",
8836 primary_root_inverse_translate (infopath),
8843 keywords[KEYWORD_LOCALID].string = xstrdup (next);
8844 keywords[KEYWORD_LOCALID].len = strlen (next);
8845 keywords[KEYWORD_LOCALID].expandit = 1;
8853 RCS_setincexc (void **keywords_in, const char *arg)
8857 bool include = false;
8858 struct rcs_keyword *keyword;
8859 struct rcs_keyword *keywords;
8862 *keywords_in = new_keywords ();
8863 keywords = *keywords_in;
8865 copy = xstrdup(arg);
8880 for (keyword = keywords; keyword->string != NULL; keyword++)
8882 keyword->expandit = false;
8885 key = strtok(next, ",");
8887 for (keyword = keywords; keyword->string != NULL; keyword++) {
8888 if (strcmp (keyword->string, key) == 0)
8889 keyword->expandit = include;
8891 key = strtok(NULL, ",");
8899 #define ATTIC "/" CVSATTIC
8901 getfullCVSname(char *CVSname, char **pathstore)
8903 if (current_parsed_root->directory) {
8906 int alen = sizeof(ATTIC) - 1;
8908 *pathstore = xstrdup(CVSname);
8909 if ((c = strrchr(*pathstore, '/')) != NULL) {
8910 if (c - *pathstore >= alen) {
8911 if (!strncmp(c - alen, ATTIC, alen)) {
8912 while (*c != '\0') {
8921 rootlen = strlen(current_parsed_root->directory);
8922 if (!strncmp(*pathstore, current_parsed_root->directory, rootlen) &&
8923 (*pathstore)[rootlen] == '/')
8924 CVSname = (*pathstore + rootlen + 1);
8926 CVSname = (*pathstore);