/
libprojectroot.c
93 lines (81 loc) · 1.85 KB
/
libprojectroot.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <dirent.h>
#include <glob.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "libprojectroot.h"
int weight_mode_on = 0;
int verbose_on = 0;
static const char* const candidates[] = {
".git",
".hg",
".fslckout",
".bzr",
"_darcs",
".svn",
"CVS",
"rebar.config",
"project.clj",
"SConstruct",
"pom.xml",
"build.sbt",
"build.gradle",
"Gemfile",
"requirements.txt",
"tox.ini",
"package.json",
"node_modules",
"gulpfile.js",
"Gruntfile.js",
"bower.json",
"composer.json",
"Cargo.toml",
"stack.yaml",
".cabal-sandbox",
"*.cabal",
"mix.exs",
"dub.json",
};
int is_project_root(char* cdt) {
char pattern[BUFFER_SIZE];
glob_t res;
size_t cdt_size = strlen(cdt);
strncpy(pattern, cdt, BUFFER_SIZE);
pattern[BUFFER_SIZE-1] = '\0';
strcat(pattern, "/");
for(int i = 0; i < N_CANDIDATES; i++) {
strcat(pattern, candidates[i]);
if(verbose_on) fprintf(stderr, "Matching: %s ~= %s\n", cdt, pattern);
if(glob(pattern, GLOB_NOSORT, NULL, &res) == 0) {
if(verbose_on) fprintf(stderr, "--> Matched (weight %d)\n", N_CANDIDATES - i + 1);
return N_CANDIDATES - i + 1;
}
pattern[cdt_size + 1] = 0;
}
return 0;
}
char* find_project_root_weighted(char* cwd) {
char* cdt = cwd;
char* best_cdt = malloc(sizeof(char) * BUFFER_SIZE);
int best_cdt_weight = 0;
int cdt_weight;
while(strcmp(cdt, "/") != 0) {
if((cdt_weight = is_project_root(cdt)) && cdt_weight > best_cdt_weight) {
best_cdt_weight = cdt_weight;
strncpy(best_cdt, cdt, BUFFER_SIZE);
best_cdt[BUFFER_SIZE-1] = '\0';
}
cdt = dirname(cdt);
}
return best_cdt;
}
char* find_project_root(char* cwd) {
char* cdt = cwd;
while(strcmp(cdt, "/") != 0) {
if(is_project_root(cdt)) return cdt;
cdt = dirname(cdt);
}
return NULL;
}