Avoid using any globals in language detection.

This commit is contained in:
Érico Rolim 2021-02-22 04:57:40 -03:00
parent 81c7f243a7
commit 14cb4cbed4
3 changed files with 24 additions and 14 deletions

18
ep.c
View File

@ -4,7 +4,7 @@
* configuring existing ones.
*
* Liberties taken:
* - will crash with segfault if allocations fail; NULL is special only when meaningful beyond allocation
* - might crash with segfault if some allocations fail; NULL is special only when meaningful beyond allocation
* - assumes stdio is reasonably buffered, so multiple fputs calls aren't expensive
*/
@ -78,9 +78,19 @@ int main(int argc, char **argv)
print_git();
/* programming languages */
pthread_join(pwd_lang_handle, NULL);
if (root_lang_task.launched) pthread_join(root_lang_task.handle, NULL);
print_lang();
uint64_t pwd_langs = 0, root_langs = 0;
void *tmp_mask;
pthread_join(pwd_lang_handle, &tmp_mask);
/* if thread returned NULL, assume no language */
#define read_mask() (tmp_mask ? *(uint64_t *)tmp_mask : 0)
pwd_langs = read_mask();
/* safe to check for launched here because we joined git_handle above */
if (root_lang_task.launched) {
pthread_join(root_lang_task.handle, &tmp_mask);
root_langs = read_mask();
}
#undef read_mask
print_lang(pwd_langs | root_langs);
/* print currently active shell jobs */
if (shell_jobs) {

3
ep.h
View File

@ -2,6 +2,7 @@
#define EP_H
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <signal.h>
@ -32,6 +33,6 @@ void print_git(void);
/* from lang.c */
void *lang_thread(void *);
void print_lang(void);
void print_lang(uint64_t);
#endif

17
lang.c
View File

@ -1,4 +1,5 @@
#include <dirent.h>
#include <stdlib.h>
#include <stdint.h>
#include <fnmatch.h>
@ -18,16 +19,12 @@ struct lang_check {
char display[8];
};
struct lang_check l[] = {
const struct lang_check l[] = {
[c_lang] = { .check = c_lang_check, .display = " C" },
};
/* bitmap of 1<<lang_index */
static uint64_t pwd_langs, root_langs;
void print_lang(void) {
uint64_t mask = pwd_langs | root_langs;
void print_lang(uint64_t mask) {
for (int i = 0; i < lang_index_n; i++) {
if (mask & (1 << i)) {
p(l[i].display);
@ -37,9 +34,11 @@ void print_lang(void) {
void *lang_thread(void *arg)
{
/* scan current dir or received root of project */
/* scan current dir if arg is NULL */
char *path = arg ? arg : ".";
uint64_t *mask = arg ? &root_langs : &pwd_langs;
uint64_t *mask = calloc(1, sizeof(mask));
if (!mask)
return NULL;
DIR *d = opendir(path);
if (!d)
@ -56,7 +55,7 @@ void *lang_thread(void *arg)
}
}
return NULL;
return mask;
}
static inline int isfile(unsigned char t) { return t & (DT_REG | DT_LNK); }