1 /*
2 * Copyright (c) 2014, 2015, 2017
3 * Tama Communications Corporation
4 *
5 * This file is part of GNU GLOBAL.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 #include <stdio.h>
24 #ifdef HAVE_STRING_H
25 #include <string.h>
26 #else
27 #include <strings.h>
28 #endif
29 #ifdef STDC_HEADERS
30 #include <stdlib.h>
31 #endif
32
33 #include "getdbpath.h"
34 #include "gparam.h"
35 #include "path.h"
36 #include "locatestring.h"
37 #include "test.h"
38 #include "nearsort.h"
39
40 static char nearbase[MAXPATHLEN];
41
42 const char *
set_nearbase_path(const char * path)43 set_nearbase_path(const char *path)
44 {
45 char real[MAXPATHLEN];
46 const char *root = get_root();
47 char *slash = "/";
48
49 if (root[0] == '\0' || realpath(path, real) == NULL)
50 return NULL;
51 #ifdef DEBUG
52 fprintf(stderr, "realpath = %s\n", real);
53 #endif
54 if (locatestring(real, root, MATCH_AT_FIRST) == NULL)
55 return NULL;
56 /*
57 * A slash should be added to the end of the directory.
58 * Avoid the following cases.
59 * .//, ./aaa.c/
60 */
61 if (*(real + strlen(root)) == 0 || test("f", real))
62 slash = "";
63 snprintf(nearbase, sizeof(nearbase), "./%s%s", real + strlen(root) + 1, slash);
64 #ifdef DEBUG
65 fprintf(stderr, "nearbase = %s\n", nearbase);
66 #endif
67 return nearbase;
68 }
69 const char *
get_nearbase_path(void)70 get_nearbase_path(void)
71 {
72 return nearbase[0] ? (const char *)nearbase : NULL;
73 }
74 int
get_nearness(const char * p1,const char * p2)75 get_nearness(const char *p1, const char *p2)
76 {
77 int parts = 0;
78 #ifdef DEBUG
79 fprintf(stderr, "get_nearness(%s, %s)", p1, p2);
80 #endif
81 for (; *p1 && *p2; p1++, p2++) {
82 if (*p1 != *p2)
83 break;
84 if (*p1 == '/')
85 parts++;
86 }
87 /*
88 * When the argument of --nearness option is a file,
89 * the file is given the highest priority.
90 */
91 if (*p1 == 0 && *p2 == 0 && *(p1 - 1) != '/')
92 parts++;
93 #ifdef DEBUG
94 fprintf(stderr, " => %d\n", parts);
95
96 #endif
97 return parts;
98 }
99