2 * Copyright (c) 1992, Brian Berliner and Jeff Polk
3 * Copyright (c) 1989-1992, Brian Berliner
5 * You may distribute under the terms of the GNU General Public License as
6 * specified in the README file that comes with the CVS source distribution.
8 * Various useful functions for the CVS support code.
17 #else /* HAVE_NANOSLEEP */
18 # if !defined HAVE_USLEEP && defined HAVE_SELECT
19 /* use select as a workaround */
21 # endif /* !defined HAVE_USLEEP && defined HAVE_SELECT */
22 #endif /* !HAVE_NANOSLEEP */
24 extern char *getlogin ();
27 * malloc some data and die if it fails
35 /* Parts of CVS try to xmalloc zero bytes and then free it. Some
36 systems have a malloc which returns NULL for zero byte
37 allocations but a free which can't handle NULL, so compensate. */
45 sprintf (buf, "out of memory; can not allocate %lu bytes",
46 (unsigned long) bytes);
53 * realloc data and die if it fails [I've always wanted to have "realloc" do
54 * a "malloc" if the argument is NULL, but you can't depend on it. Here, I
67 cp = realloc (ptr, bytes);
72 sprintf (buf, "out of memory; can not reallocate %lu bytes",
73 (unsigned long) bytes);
79 /* Two constants which tune expand_string. Having MIN_INCR as large
80 as 1024 might waste a bit of memory, but it shouldn't be too bad
81 (CVS used to allocate arrays of, say, 3000, PATH_MAX (8192, often),
82 or other such sizes). Probably anything which is going to allocate
83 memory which is likely to get as big as MAX_INCR shouldn't be doing
84 it in one block which must be contiguous, but since getrcskey does
85 so, we might as well limit the wasted memory to MAX_INCR or so
88 MIN_INCR and MAX_INCR should both be powers of two and we generally
89 try to keep our allocations to powers of two for the most part.
90 Most malloc implementations these days tend to like that. */
93 #define MAX_INCR (2*1024*1024)
95 /* *STRPTR is a pointer returned from malloc (or NULL), pointing to *N
96 characters of space. Reallocate it so that points to at least
97 NEWSIZE bytes of space. Gives a fatal error if out of memory;
98 if it returns it was successful. */
100 expand_string (strptr, n, newsize)
111 else if (*n >= MAX_INCR)
120 *strptr = xrealloc (*strptr, *n);
124 /* *STR is a pointer to a malloc'd string. *LENP is its allocated
125 length. Add SRC to the end of it, reallocating if necessary. */
127 xrealloc_and_strcat (str, lenp, src)
133 expand_string (str, lenp, strlen (*str) + strlen (src) + 1);
138 * Duplicate a string, calling xmalloc to allocate some dynamic space
147 return ((char *) NULL);
148 s = xmalloc (strlen (str) + 1);
149 (void) strcpy (s, str);
155 /* Remove trailing newlines from STRING, destructively.
159 * True if any newlines were removed, false otherwise.
162 strip_trailing_newlines (str)
165 size_t index, origlen;
166 index = origlen = strlen (str);
168 while (index > 0 && str[index-1] == '\n')
171 return index != origlen;
176 /* Return the number of levels that PATH ascends above where it starts.
180 * "foo/../../bar" -> 1
189 if (p == NULL) return 0;
195 /* Now look for pathname level-ups. */
196 if (p[0] == '.' && p[1] == '.' && (p[2] == '\0' || ISDIRSEP (p[2])))
199 if (-level > max_level)
202 else if (p[0] == '\0' || ISDIRSEP (p[0]) ||
203 (p[0] == '.' && (p[1] == '\0' || ISDIRSEP (p[1]))))
208 /* q = strchr (p, '/'); but sub ISDIRSEP() for '/': */
209 while (*p != '\0' && !ISDIRSEP (*p)) p++;
211 } while (*p != '\0');
217 /* Free a vector, where (*ARGV)[0], (*ARGV)[1], ... (*ARGV)[*PARGC - 1]
218 are malloc'd and so is *ARGV itself. Such a vector is allocated by
219 line2argv or expand_wild, for example. */
221 free_names (pargc, argv)
227 for (i = 0; i < *pargc; i++)
228 { /* only do through *pargc */
232 *pargc = 0; /* and set it to zero when done */
235 /* Convert LINE into arguments separated by SEPCHARS. Set *ARGC
236 to the number of arguments found, and (*ARGV)[0] to the first argument,
237 (*ARGV)[1] to the second, etc. *ARGV is malloc'd and so are each of
238 (*ARGV)[0], (*ARGV)[1], ... Use free_names() to return the memory
239 allocated here back to the free pool. */
241 line2argv (pargc, argv, line, sepchars)
248 /* Could make a case for size_t or some other unsigned type, but
249 we'll stick with int to avoid signed/unsigned warnings when
250 comparing with *pargc. */
253 /* Small for testing. */
255 *argv = (char **) xmalloc (argv_allocated * sizeof (**argv));
258 for (cp = strtok (line, sepchars); cp; cp = strtok ((char *) NULL, sepchars))
260 if (*pargc == argv_allocated)
263 *argv = xrealloc (*argv, argv_allocated * sizeof (**argv));
265 (*argv)[*pargc] = xstrdup (cp);
271 * Returns the number of dots ('.') found in an RCS revision number
287 /* Compare revision numbers REV1 and REV2 by consecutive fields.
288 Return negative, zero, or positive in the manner of strcmp. The
289 two revision numbers must have the same number of fields, or else
290 compare_revnums will return an inaccurate result. */
292 compare_revnums (rev1, rev2)
304 result = strtoul (sp, &snext, 10) - strtoul (tp, &tnext, 10);
305 if (*snext == '\0' || *tnext == '\0')
314 /* Increment a revision number. Working on the string is a bit awkward,
315 but it avoid problems with integer overflow should the revision numbers
318 increment_revnum (rev)
323 size_t len = strlen (rev);
325 newrev = xmalloc (len + 2);
326 memcpy (newrev, rev, len + 1);
327 for (p = newrev + len; p != newrev; )
342 /* The number was all 9s, so change the first character to 1 and add
351 /* Return the username by which the caller should be identified in
352 CVS, in contexts such as the author field of RCS files, various
357 #ifndef SYSTEM_GETCALLER
363 /* If there is a CVS username, return it. */
364 #ifdef AUTH_SERVER_SUPPORT
365 if (CVS_Username != NULL)
369 #ifdef SYSTEM_GETCALLER
370 return SYSTEM_GETCALLER ();
372 /* Get the caller's login from his uid. If the real uid is "root"
373 try LOGNAME USER or getlogin(). If getlogin() and getpwuid()
374 both fail, return the uid as a string. */
380 if (uid == (uid_t) 0)
384 /* super-user; try getlogin() to distinguish */
385 if (((name = getlogin ()) || (name = getenv("LOGNAME")) ||
386 (name = getenv("USER"))) && *name)
388 cache = xstrdup (name);
392 if ((pw = (struct passwd *) getpwuid (uid)) == NULL)
396 (void) sprintf (uidname, "uid%lu", (unsigned long) uid);
397 cache = xstrdup (uidname);
400 cache = xstrdup (pw->pw_name);
422 /* Given some revision, REV, return the first prior revision that exists in the
429 * RCS The RCS node pointer.
430 * REV An existing revision in the RCS file referred to by RCS.
433 * The first prior revision that exists in the RCS file, or NULL if no prior
434 * revision exists. The caller is responsible for disposing of this string.
437 * This function currently neglects the case where we are on the trunk with
438 * rev = X.1, where X != 1. If rev = X.Y, where X != 1 and Y > 1, then this
439 * function should work fine, as revision X.1 must exist, due to RCS rules.
442 previous_rev (rcs, rev)
447 char *tmp = xstrdup (rev);
451 /* Our retval can have no more digits and dots than our input revision. */
452 retval = xmalloc (strlen (rev) + 1);
453 p = strrchr (tmp, '.');
455 r1 = strtol (p+1, NULL, 10);
459 /* If r1 == 0, then we must be on a branch and our parent must
460 * exist, or we must be on the trunk with a REV like X.1.
461 * We are neglecting the X.1 with X != 1 case by assuming that
462 * there is no previous revision when we discover we were on
465 p = strrchr (tmp, '.');
467 /* We are on the trunk. */
472 sprintf (retval, "%s", tmp);
476 sprintf (retval, "%s.%ld", tmp, r1);
477 } while (!RCS_exist_rev (rcs, retval));
485 /* Given two revisions, find their greatest common ancestor. If the
486 two input revisions exist, then rcs guarantees that the gca will
500 if (rev1 == NULL || rev2 == NULL)
502 error (0, 0, "sanity failure in gca");
506 /* The greatest common ancestor will have no more dots, and numbers
507 of digits for each component no greater than the arguments. Therefore
508 this string will be big enough. */
509 g = gca = xmalloc (strlen (rev1) + strlen (rev2) + 100);
511 /* walk the strings, reading the common parts. */
516 r1 = strtol (p1, (char **) &p1, 10);
517 r2 = strtol (p2, (char **) &p2, 10);
519 /* use the lowest. */
520 (void) sprintf (g, "%d.", r1 < r2 ? r1 : r2);
522 if (*p1 == '.') ++p1;
524 if (*p2 == '.') ++p2;
528 /* erase that last dot. */
531 /* numbers differ, or we ran out of strings. we're done with the
534 dots = numdots (gca);
537 /* revisions differ in trunk major number. */
539 if (r2 < r1) p1 = p2;
542 /* we only got one number. this is strange. */
543 error (0, 0, "bad revisions %s or %s", rev1, rev2);
548 /* we have a minor number. use it. */
550 while (*p1 != '.' && *p1 != '\0')
555 else if ((dots & 1) == 0)
557 /* if we have an even number of dots, then we have a branch.
558 remove the last number in order to make it a revision. */
560 g = strrchr (gca, '.');
564 retval = xstrdup (gca);
569 /* Give fatal error if REV is numeric and ARGC,ARGV imply we are
570 planning to operate on more than one file. The current directory
571 should be the working directory. Note that callers assume that we
572 will only be checking the first character of REV; it need not have
573 '\0' at the end of the tag name and other niceties. Right now this
574 is only called from admin.c, but if people like the concept it probably
575 should also be called from diff -r, update -r, get -r, and log -r. */
578 check_numeric (rev, argc, argv)
583 if (rev == NULL || !isdigit ((unsigned char) *rev))
586 /* Note that the check for whether we are processing more than one
587 file is (basically) syntactic; that is, we don't behave differently
588 depending on whether a directory happens to contain only a single
589 file or whether it contains more than one. I strongly suspect this
590 is the least confusing behavior. */
592 || (!wrap_name_has (argv[0], WRAP_TOCVS) && isdir (argv[0])))
594 error (0, 0, "while processing more than one file:");
595 error (1, 0, "attempt to specify a numeric revision");
600 * Sanity checks and any required fix-up on message passed to RCS via '-m'.
601 * RCS 5.7 requires that a non-total-whitespace, non-null message be provided
602 * with '-m'. Returns a newly allocated, non-empty buffer with whitespace
603 * stripped from end of lines and end of buffer.
605 * TODO: We no longer use RCS to manage repository files, so maybe this
606 * nonsense about non-empty log fields can be dropped.
609 make_message_rcslegal (message)
615 if (message == NULL) message = "";
617 /* Strip whitespace from end of lines and end of string. */
618 dp = dst = (char *) xmalloc (strlen (message) + 1);
619 for (mp = message; *mp != '\0'; ++mp)
623 /* At end-of-line; backtrack to last non-space. */
624 while (dp > dst && (dp[-1] == ' ' || dp[-1] == '\t'))
630 /* Backtrack to last non-space at end of string, and truncate. */
631 while (dp > dst && isspace ((unsigned char) dp[-1]))
635 /* After all that, if there was no non-space in the string,
636 substitute a non-empty message. */
640 dst = xstrdup ("*** empty log message ***");
651 * This function compares the timestamp of a file with ts_conflict set
652 * to the timestamp on the actual file and returns TRUE or FALSE based
655 * This function does not check for actual markers in the file and
656 * file_has_markers() function should be called when that is interesting.
659 * The ts_conflict field is not NULL.
662 * TRUE ts_conflict matches the current timestamp.
663 * FALSE The ts_conflict field does not match the file's
667 file_has_conflict (finfo, ts_conflict)
668 const struct file_info *finfo;
669 const char *ts_conflict;
674 /* If ts_conflict is NULL, there was no merge since the last
675 * commit and there can be no conflict.
677 assert (ts_conflict);
680 * If the timestamp has changed and no
681 * conflict indicators are found, it isn't a
685 #ifdef SERVER_SUPPORT
687 retcode = ts_conflict[0] == '=';
689 #endif /* SERVER_SUPPORT */
691 filestamp = time_stamp (finfo->file);
692 retcode = !strcmp (ts_conflict, filestamp);
701 /* Does the file FINFO contain conflict markers? The whole concept
702 of looking at the contents of the file to figure out whether there are
703 unresolved conflicts is kind of bogus (people do want to manage files
704 which contain those patterns not as conflict markers), but for now it
707 file_has_markers (finfo)
708 const struct file_info *finfo;
712 size_t line_allocated = 0;
716 fp = CVS_FOPEN (finfo->file, "r");
718 error (1, errno, "cannot open %s", finfo->fullname);
719 while (getline (&line, &line_allocated, fp) > 0)
721 if (strncmp (line, RCS_MERGE_PAT_1, sizeof RCS_MERGE_PAT_1 - 1) == 0 ||
722 strncmp (line, RCS_MERGE_PAT_2, sizeof RCS_MERGE_PAT_2 - 1) == 0 ||
723 strncmp (line, RCS_MERGE_PAT_3, sizeof RCS_MERGE_PAT_3 - 1) == 0)
730 error (0, errno, "cannot read %s", finfo->fullname);
733 error (0, errno, "cannot close %s", finfo->fullname);
739 /* Read the entire contents of the file NAME into *BUF.
740 If NAME is NULL, read from stdin. *BUF
741 is a pointer returned from malloc (or NULL), pointing to *BUFSIZE
742 bytes of space. The actual size is returned in *LEN. On error,
743 give a fatal error. The name of the file to use in error messages
744 (typically will include a directory if we have changed directory)
745 is FULLNAME. MODE is "r" for text or "rb" for binary. */
748 get_file (name, fullname, mode, buf, bufsize, len)
750 const char *fullname;
765 filesize = 100; /* force allocation of minimum buffer */
769 /* Although it would be cleaner in some ways to just read
770 until end of file, reallocating the buffer, this function
771 does get called on files in the working directory which can
772 be of arbitrary size, so I think we better do all that
775 if (CVS_STAT (name, &s) < 0)
776 error (1, errno, "can't stat %s", fullname);
778 /* Convert from signed to unsigned. */
779 filesize = s.st_size;
781 e = open_file (name, mode);
784 if (*buf == NULL || *bufsize <= filesize)
786 *bufsize = filesize + 1;
787 *buf = xrealloc (*buf, *bufsize);
796 got = fread (tobuf, 1, *bufsize - (tobuf - *buf), e);
798 error (1, errno, "can't read %s", fullname);
805 /* Allocate more space if needed. */
806 if (tobuf == *buf + *bufsize)
815 expand_string (buf, bufsize, *bufsize + 100);
822 if (e != stdin && fclose (e) < 0)
823 error (0, errno, "cannot close %s", fullname);
827 /* Force *BUF to be large enough to hold a null terminator. */
828 if (nread == *bufsize)
829 expand_string (buf, bufsize, *bufsize + 1);
830 (*buf)[nread] = '\0';
834 /* Follow a chain of symbolic links to its destination. FILENAME
835 should be a handle to a malloc'd block of memory which contains the
836 beginning of the chain. This routine will replace the contents of
837 FILENAME with the destination (a real file). */
840 resolve_symlink (filename)
843 if (filename == NULL || *filename == NULL)
846 while (islink (*filename))
849 /* The clean thing to do is probably to have each filesubr.c
850 implement this (with an error if not supported by the
851 platform, in which case islink would presumably return 0).
852 But that would require editing each filesubr.c and so the
853 expedient hack seems to be looking at HAVE_READLINK. */
854 char *newname = xreadlink (*filename);
856 if (isabsolute (newname))
863 const char *oldname = last_component (*filename);
864 int dirlen = oldname - *filename;
865 char *fullnewname = xmalloc (dirlen + strlen (newname) + 1);
866 strncpy (fullnewname, *filename, dirlen);
867 strcpy (fullnewname + dirlen, newname);
870 *filename = fullnewname;
873 error (1, 0, "internal error: islink doesn't like readlink");
879 * Rename a file to an appropriate backup name based on BAKPREFIX.
880 * If suffix non-null, then ".<suffix>" is appended to the new name.
882 * Returns the new name, which caller may free() if desired.
885 backup_file (filename, suffix)
886 const char *filename;
893 backup_name = xmalloc (sizeof (BAKPREFIX) + strlen (filename) + 1);
894 sprintf (backup_name, "%s%s", BAKPREFIX, filename);
898 backup_name = xmalloc (sizeof (BAKPREFIX)
901 + 2); /* one for dot, one for trailing '\0' */
902 sprintf (backup_name, "%s%s.%s", BAKPREFIX, filename, suffix);
905 if (isfile (filename))
906 copy_file (filename, backup_name);
912 * Copy a string into a buffer escaping any shell metacharacters. The
913 * buffer should be at least twice as long as the string.
915 * Returns a pointer to the terminating NUL byte in buffer.
919 shell_escape(buf, str)
923 static const char meta[] = "$`\\\"";
928 p = strpbrk(str, meta);
929 if (!p) p = str + strlen(str);
932 memcpy(buf, str, p - str);
947 * We can only travel forwards in time, not backwards. :)
950 sleep_past (desttime)
957 while (time (&t) <= desttime)
959 #ifdef HAVE_GETTIMEOFDAY
961 gettimeofday (&tv, NULL);
962 if (tv.tv_sec > desttime)
964 s = desttime - tv.tv_sec;
966 us = 1000000 - tv.tv_usec;
973 /* default to 20 ms increments */
978 #if defined(HAVE_NANOSLEEP)
982 ts.tv_nsec = us * 1000;
983 (void)nanosleep (&ts, NULL);
985 #elif defined(HAVE_USLEEP)
990 #elif defined(HAVE_SELECT)
992 /* use select instead of sleep since it is a fairly portable way of
998 (void)select (0, (fd_set *)NULL, (fd_set *)NULL, (fd_set *)NULL,
1010 /* Return non-zero iff FILENAME is absolute.
1011 Trivial under Unix, but more complicated under other systems. */
1013 isabsolute (filename)
1014 const char *filename;
1016 return ISABSOLUTE (filename);