Update NEWS with the latest changes
[geany-mirror.git] / ctags / main / routines.c
blob5ffdc256ecbd9adf68bc25fcb6c5857e58c9cdd0
1 /*
2 * Copyright (c) 2002-2003, Darren Hiebert
4 * This source code is released for free distribution under the terms of the
5 * GNU General Public License version 2 or (at your option) any later version.
7 * This module contains a lose assortment of shared functions.
8 */
11 * INCLUDE FILES
13 #include "general.h" /* must always come first */
15 #include <glib.h>
16 #include <glib/gstdio.h>
18 #include <errno.h>
20 #ifdef HAVE_STDLIB_H
21 # include <stdlib.h> /* to declare malloc (), realloc () */
22 #endif
23 #include <ctype.h>
24 #include <string.h>
25 #include <stdio.h> /* to declare tempnam(), and SEEK_SET (hopefully) */
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h> /* to declare O_RDWR, O_CREAT, O_EXCL */
29 #endif
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h> /* to declare mkstemp () */
32 #endif
34 #ifdef HAVE_LIMITS_H
35 # include <limits.h> /* to declare MB_LEN_MAX */
36 #endif
37 #ifndef MB_LEN_MAX
38 # define MB_LEN_MAX 6
39 #endif
41 /* To declare "struct stat" and stat ().
43 #if defined (HAVE_SYS_TYPES_H)
44 # include <sys/types.h>
45 #else
46 # if defined (HAVE_TYPES_H)
47 # include <types.h>
48 # endif
49 #endif
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 #else
53 # ifdef HAVE_STAT_H
54 # include <stat.h>
55 # endif
56 #endif
58 #ifdef HAVE_DIRECT_H
59 # include <direct.h> /* to _getcwd */
60 #endif
61 #ifdef HAVE_DIR_H
62 # include <dir.h> /* to declare findfirst() and findnext() */
63 #endif
64 #ifdef HAVE_IO_H
65 # include <io.h> /* to declare open() */
66 #endif
67 #include "debug.h"
68 #include "routines.h"
69 #ifdef HAVE_ICONV
70 # include "mbcs.h"
71 #endif
72 #ifdef HAVE_ERRNO_H
73 # include <errno.h>
74 #endif
76 #include "options.h"
79 * MACROS
81 #ifndef TMPDIR
82 # define TMPDIR "/tmp"
83 #endif
85 /* File type tests.
87 #ifndef S_ISREG
88 # if defined (S_IFREG)
89 # define S_ISREG(mode) ((mode) & S_IFREG)
90 # endif
91 #endif
93 #ifndef S_ISLNK
94 # ifdef S_IFLNK
95 # define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
96 # else
97 # define S_ISLNK(mode) false /* assume no soft links */
98 # endif
99 #endif
101 #ifndef S_ISDIR
102 # ifdef S_IFDIR
103 # define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
104 # else
105 # define S_ISDIR(mode) false /* assume no soft links */
106 # endif
107 #endif
109 #ifndef S_IFMT
110 # define S_IFMT 0
111 #endif
113 #ifndef S_IXUSR
114 # define S_IXUSR 0
115 #endif
116 #ifndef S_IXGRP
117 # define S_IXGRP 0
118 #endif
119 #ifndef S_IXOTH
120 # define S_IXOTH 0
121 #endif
123 #ifndef S_IRUSR
124 # define S_IRUSR 0400
125 #endif
126 #ifndef S_IWUSR
127 # define S_IWUSR 0200
128 #endif
130 #ifndef S_ISUID
131 # define S_ISUID 0
132 #endif
134 #ifndef S_ISGID
135 # define S_ISGID 0
136 #endif
138 /* Hack for ridiculous practice of Microsoft Visual C++.
140 #if defined (WIN32)
141 # if defined (_MSC_VER)
142 # define stat _stat
143 # define getcwd _getcwd
144 # define PATH_MAX _MAX_PATH
145 # endif
146 #endif
148 #ifndef PATH_MAX
149 # define PATH_MAX 256
150 #endif
153 * Miscellaneous macros
156 #define selected(var,feature) (((int)(var) & (int)(feature)) == (int)feature)
160 * DATA DEFINITIONS
162 #if defined (MSDOS_STYLE_PATH)
163 const char *const PathDelimiters = ":/\\";
164 #endif
166 char *CurrentDirectory;
168 static const char *ExecutableProgram = NULL;
169 static const char *ExecutableName = "geany";
172 * FUNCTION PROTOTYPES
174 #ifdef NEED_PROTO_STAT
175 extern int stat (const char *, struct stat *);
176 #endif
177 #ifdef NEED_PROTO_LSTAT
178 extern int lstat (const char *, struct stat *);
179 #endif
183 * FUNCTION DEFINITIONS
187 extern void setExecutableName (const char *const path)
189 ExecutableProgram = path;
190 ExecutableName = baseFilename (path);
193 extern const char *getExecutableName (void)
195 return ExecutableName;
199 extern void *eMalloc (const size_t size)
201 void *buffer = g_malloc (size);
203 if (buffer == NULL)
204 error (FATAL, "out of memory");
206 return buffer;
209 extern void *eCalloc (const size_t count, const size_t size)
211 void *buffer = calloc (count, size);
213 if (buffer == NULL)
214 error (FATAL, "out of memory");
216 return buffer;
219 extern void *eRealloc (void *const ptr, const size_t size)
221 void *buffer;
222 if (ptr == NULL)
223 buffer = eMalloc (size);
224 else
226 buffer = g_realloc (ptr, size);
227 if (buffer == NULL)
228 error (FATAL, "out of memory");
230 return buffer;
233 extern void eFree (void *const ptr)
235 if (ptr != NULL)
236 free (ptr);
239 #ifndef HAVE_STRSTR
240 extern char* strstr (const char *str, const char *substr)
242 const size_t length = strlen (substr);
243 const char *match = NULL;
244 const char *p;
246 for (p = str ; *p != '\0' && match == NULL ; ++p)
247 if (strncmp (p, substr, length) == 0)
248 match = p;
249 return (char*) match;
251 #endif
253 extern char* eStrdup (const char* str)
255 char* result = xMalloc (strlen (str) + 1, char);
256 strcpy (result, str);
257 return result;
260 extern void toLowerString (char* str)
262 while (*str != '\0')
264 *str = tolower ((int) *str);
265 ++str;
269 extern void toUpperString (char* str)
271 while (*str != '\0')
273 *str = toupper ((int) *str);
274 ++str;
278 /* Newly allocated string containing lower case conversion of a string.
280 extern char* newLowerString (const char* str)
282 char* const result = xMalloc (strlen (str) + 1, char);
283 int i = 0;
285 result [i] = tolower ((int) str [i]);
286 while (str [i++] != '\0');
287 return result;
290 /* Newly allocated string containing upper case conversion of a string.
292 extern char* newUpperString (const char* str)
294 char* const result = xMalloc (strlen (str) + 1, char);
295 int i = 0;
297 result [i] = toupper ((int) str [i]);
298 while (str [i++] != '\0');
299 return result;
303 #if 0
304 static void setCurrentDirectory (void)
306 char* const cwd = getcwd (NULL, PATH_MAX);
307 CurrentDirectory = xMalloc (strlen (cwd) + 2, char);
308 if (cwd [strlen (cwd) - (size_t) 1] == PATH_SEPARATOR)
309 strcpy (CurrentDirectory, cwd);
310 else
311 sprintf (CurrentDirectory, "%s%c", cwd, OUTPUT_PATH_SEPARATOR);
312 free (cwd);
314 #endif
317 extern bool doesFileExist (const char *const fileName)
319 GStatBuf fileStatus;
321 return (bool) (g_stat (fileName, &fileStatus) == 0);
324 extern bool isRecursiveLink (const char* const dirName)
326 bool result = false;
327 char* const path = absoluteFilename (dirName);
328 while (path [strlen (path) - 1] == PATH_SEPARATOR)
329 path [strlen (path) - 1] = '\0';
330 while (! result && strlen (path) > (size_t) 1)
332 char *const separator = strrchr (path, PATH_SEPARATOR);
333 if (separator == NULL)
334 break;
335 else if (separator == path) /* backed up to root directory */
336 *(separator + 1) = '\0';
337 else
338 *separator = '\0';
339 result = isSameFile (path, dirName);
341 eFree (path);
342 return result;
345 extern bool isSameFile (const char *const name1, const char *const name2)
347 bool result = false;
348 #ifdef HAVE_STAT_ST_INO
349 GStatBuf stat1, stat2;
351 if (g_stat (name1, &stat1) == 0 && g_stat (name2, &stat2) == 0)
352 result = (bool) (stat1.st_ino == stat2.st_ino);
353 #endif
354 return result;
358 * Pathname manipulation (O/S dependent!!!)
361 extern const char *baseFilename (const char *const filePath)
363 #if defined (MSDOS_STYLE_PATH)
364 const char *tail = NULL;
365 unsigned int i;
367 /* Find whichever of the path delimiters is last.
369 for (i = 0 ; i < strlen (PathDelimiters) ; ++i)
371 const char *sep = strrchr (filePath, PathDelimiters [i]);
373 if (sep > tail)
374 tail = sep;
376 #else
377 const char *tail = strrchr (filePath, PATH_SEPARATOR);
378 #endif
379 if (tail == NULL)
380 tail = filePath;
381 else
382 ++tail; /* step past last delimiter */
384 return tail;
388 * File extension and language mapping
390 extern const char *fileExtension (const char *const fileName)
392 const char *extension;
393 const char *pDelimiter = NULL;
395 pDelimiter = strrchr (fileName, '.');
397 if (pDelimiter == NULL)
398 extension = "";
399 else
400 extension = pDelimiter + 1; /* skip to first char of extension */
402 return extension;
405 extern bool isAbsolutePath (const char *const path)
407 bool result = false;
408 #if defined (MSDOS_STYLE_PATH)
409 if (strchr (PathDelimiters, path [0]) != NULL)
410 result = true;
411 else if (isalpha (path [0]) && path [1] == ':')
413 if (strchr (PathDelimiters, path [2]) != NULL)
414 result = true;
415 else
416 /* We don't support non-absolute file names with a drive
417 * letter, like `d:NAME' (it's too much hassle).
419 error (FATAL,
420 "%s: relative file names with drive letters not supported",
421 path);
423 #else
424 result = (bool) (path [0] == PATH_SEPARATOR);
425 #endif
426 return result;
429 extern vString *combinePathAndFile (const char *const path,
430 const char *const file)
432 vString *const filePath = vStringNew ();
433 const int lastChar = path [strlen (path) - 1];
434 # ifdef MSDOS_STYLE_PATH
435 bool terminated = (bool) (strchr (PathDelimiters, lastChar) != NULL);
436 # else
437 bool terminated = (bool) (lastChar == PATH_SEPARATOR);
438 # endif
440 vStringCopyS (filePath, path);
441 if (! terminated)
442 vStringPut (filePath, OUTPUT_PATH_SEPARATOR);
443 vStringCatS (filePath, file);
445 return filePath;
448 /* Return a newly-allocated string whose contents concatenate those of
449 * s1, s2, s3.
450 * Routine adapted from Gnu etags.
452 static char* concat (const char *s1, const char *s2, const char *s3)
454 int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
455 char *result = xMalloc (len1 + len2 + len3 + 1, char);
457 strcpy (result, s1);
458 strcpy (result + len1, s2);
459 strcpy (result + len1 + len2, s3);
460 result [len1 + len2 + len3] = '\0';
462 return result;
465 /* Return a newly allocated string containing the absolute file name of FILE
466 * given CWD (which should end with a slash).
467 * Routine adapted from Gnu etags.
469 extern char* absoluteFilename (const char *file)
471 char *slashp, *cp;
472 char *res = NULL;
473 if (isAbsolutePath (file))
474 res = eStrdup (file);
475 else
476 res = concat (CurrentDirectory, file, "");
478 /* Delete the "/dirname/.." and "/." substrings. */
479 slashp = strchr (res, '/');
480 while (slashp != NULL && slashp [0] != '\0')
482 if (slashp[1] == '.')
484 if (slashp [2] == '.' && (slashp [3] == '/' || slashp [3] == '\0'))
486 cp = slashp;
488 cp--;
489 while (cp >= res && ! isAbsolutePath (cp));
490 if (cp < res)
491 cp = slashp;/* the absolute name begins with "/.." */
492 #ifdef MSDOS_STYLE_PATH
493 /* Under MSDOS and NT we get `d:/NAME' as absolute file name,
494 * so the luser could say `d:/../NAME'. We silently treat this
495 * as `d:/NAME'.
497 else if (cp [0] != '/')
498 cp = slashp;
499 #endif
500 memmove (cp, slashp + 3, strlen (slashp + 3) + 1);
501 slashp = cp;
502 continue;
504 else if (slashp [2] == '/' || slashp [2] == '\0')
506 memmove (slashp, slashp + 2, strlen (slashp + 2) + 1);
507 continue;
510 slashp = strchr (slashp + 1, '/');
513 if (res [0] == '\0')
514 return eStrdup ("/");
515 else
517 #ifdef MSDOS_STYLE_PATH
518 /* Canonicalize drive letter case. */
519 if (res [1] == ':' && islower (res [0]))
520 res [0] = toupper (res [0]);
521 #endif
523 return res;
527 /* Return a newly allocated string containing the absolute file name of dir
528 * where FILE resides given CWD (which should end with a slash).
529 * Routine adapted from Gnu etags.
531 extern char* absoluteDirname (char *file)
533 char *slashp, *res;
534 char save;
535 #ifdef MSDOS_STYLE_PATH
536 char *p;
537 for (p = file ; *p != '\0' ; p++)
538 if (*p == '\\')
539 *p = '/';
540 #endif
541 slashp = strrchr (file, '/');
542 if (slashp == NULL)
543 res = eStrdup (CurrentDirectory);
544 else
546 save = slashp [1];
547 slashp [1] = '\0';
548 res = absoluteFilename (file);
549 slashp [1] = save;
551 return res;
554 /* Return a newly allocated string containing the file name of FILE relative
555 * to the absolute directory DIR (which should end with a slash).
556 * Routine adapted from Gnu etags.
558 extern char* relativeFilename (const char *file, const char *dir)
560 const char *fp, *dp;
561 char *absdir, *res;
562 int i;
564 /* Find the common root of file and dir (with a trailing slash). */
565 absdir = absoluteFilename (file);
566 fp = absdir;
567 dp = dir;
568 while (*fp++ == *dp++)
569 continue;
570 fp--;
571 dp--; /* back to the first differing char */
573 { /* look at the equal chars until '/' */
574 if (fp == absdir)
575 return absdir; /* first char differs, give up */
576 fp--;
577 dp--;
578 } while (*fp != '/');
580 /* Build a sequence of "../" strings for the resulting relative file name.
582 i = 0;
583 while ((dp = strchr (dp + 1, '/')) != NULL)
584 i += 1;
585 res = xMalloc (3 * i + strlen (fp + 1) + 1, char);
586 res [0] = '\0';
587 while (i-- > 0)
588 strcat (res, "../");
590 /* Add the file name relative to the common root of file and dir. */
591 strcat (res, fp + 1);
592 free (absdir);
594 return res;
597 extern long unsigned int getFileSize (const char *const name)
599 GStatBuf fileStatus;
600 unsigned long size = 0;
602 if (g_stat (name, &fileStatus) == 0)
603 size = fileStatus.st_size;
605 return size;
608 #if 0
609 static bool isSymbolicLink (const char *const name)
611 #if defined (WIN32)
612 return false;
613 #else
614 GStatBuf fileStatus;
615 bool result = false;
617 if (g_lstat (name, &fileStatus) == 0)
618 result = (bool) (S_ISLNK (fileStatus.st_mode));
620 return result;
621 #endif
624 static bool isNormalFile (const char *const name)
626 GStatBuf fileStatus;
627 bool result = false;
629 if (g_stat (name, &fileStatus) == 0)
630 result = (bool) (S_ISREG (fileStatus.st_mode));
632 return result;
634 #endif
636 extern bool isExecutable (const char *const name)
638 GStatBuf fileStatus;
639 bool result = false;
641 if (g_stat (name, &fileStatus) == 0)
642 result = (bool) ((fileStatus.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) != 0);
644 return result;
647 #ifdef HAVE_MKSTEMP
649 static bool isSetUID (const char *const name)
651 #if defined (WIN32)
652 return false;
653 #else
654 GStatBuf fileStatus;
655 bool result = false;
657 if (g_stat (name, &fileStatus) == 0)
658 result = (bool) ((fileStatus.st_mode & S_ISUID) != 0);
660 return result;
661 #endif
664 #endif
666 #if 0
667 static bool isDirectory (const char *const name)
669 bool result = false;
670 GStatBuf fileStatus;
672 if (g_stat (name, &fileStatus) == 0)
673 result = (bool) S_ISDIR (fileStatus.st_mode);
674 return result;
676 #endif
678 /*#ifndef HAVE_FGETPOS*/
680 extern int fgetpos ( stream, pos )
681 FILE *const stream;
682 fpos_t *const pos;
684 int result = 0;
686 *pos = ftell (stream);
687 if (*pos == -1L)
688 result = -1;
690 return result;
693 extern int fsetpos ( stream, pos )
694 FILE *const stream;
695 fpos_t *const pos;
697 return fseek (stream, *pos, SEEK_SET);
700 /*#endif*/
702 extern FILE *tempFile (const char *const mode, char **const pName)
704 char *name;
705 FILE *fp;
706 int fd;
707 #ifdef HAVE_MKSTEMP
708 const char *const template = "tags.XXXXXX";
709 const char *tmpdir = NULL;
710 if (! isSetUID (ExecutableProgram))
711 tmpdir = getenv ("TMPDIR");
712 if (tmpdir == NULL)
713 tmpdir = TMPDIR;
714 name = xMalloc (strlen (tmpdir) + 1 + strlen (template) + 1, char);
715 sprintf (name, "%s%c%s", tmpdir, OUTPUT_PATH_SEPARATOR, template);
716 fd = mkstemp(name);
717 #else
718 name = xMalloc (L_tmpnam, char);
719 if (tmpnam (name) != name)
720 error (FATAL | PERROR, "cannot assign temporary file name");
721 fd = open (name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
722 #endif
723 if (fd == -1)
724 error (FATAL | PERROR, "cannot open temporary file");
725 fp = fdopen (fd, mode);
726 if (fp == NULL)
727 error (FATAL | PERROR, "cannot open temporary file");
728 DebugStatement (
729 debugPrintf (DEBUG_STATUS, "opened temporary file %s\n", name); )
730 Assert (*pName == NULL);
731 *pName = name;
732 return fp;
735 extern void error (const errorSelection selection,
736 const char *const format, ...)
738 va_list ap;
740 va_start (ap, format);
741 fprintf (errout, "%s: %s", getExecutableName (),
742 selected (selection, WARNING) ? "Warning: " : "");
743 vfprintf (errout, format, ap);
744 if (selected (selection, PERROR))
745 fprintf (errout, " : %s", g_strerror (errno));
746 fputs ("\n", errout);
747 va_end (ap);
748 if (selected (selection, FATAL))
749 exit (1);
752 #ifndef HAVE_STRICMP
753 extern int stricmp (const char *s1, const char *s2)
755 int result;
758 result = toupper ((int) *s1) - toupper ((int) *s2);
759 } while (result == 0 && *s1++ != '\0' && *s2++ != '\0');
760 return result;
762 #endif
764 #ifndef HAVE_STRNICMP
765 extern int strnicmp (const char *s1, const char *s2, size_t n)
767 int result;
770 result = toupper ((int) *s1) - toupper ((int) *s2);
771 } while (result == 0 && --n > 0 && *s1++ != '\0' && *s2++ != '\0');
772 return result;
774 #endif