Skip to content

Commit 7734569

Browse files
authored
Merge pull request #109 from Nibba2018/library_c
Extracts libraries used in C source files
2 parents 0009fc8 + d4e5858 commit 7734569

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

src/language/C.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import re
2+
3+
def extract_libraries(files):
4+
"""Extracts a list of imports that were used in the files
5+
6+
Parameters
7+
----------
8+
files : []string
9+
Full paths to files that need to be analysed
10+
11+
Returns
12+
-------
13+
dict
14+
imports that were used in the provided files, mapped against the language
15+
"""
16+
17+
res = []
18+
19+
# regex to find imports like #include<stdio.h> or #include "foo.h"
20+
regex = re.compile(r"#include\s?[<\"]([/a-zA-Z0-9.-]+)[\">]", re.IGNORECASE)
21+
22+
for f in files:
23+
with open(file=f, mode='r', errors='ignore') as fr:
24+
25+
contents = ' '.join(fr.readlines())
26+
matches = regex.findall(contents)
27+
28+
if matches:
29+
res.extend(matches)
30+
return {"C": res}

test/fixtures/C.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#include<assert.h>
2+
#include "complex.h"
3+
#include <ctype.h>
4+
#include "stdio.h"
5+
#include<float.h>
6+
#include"string.h"
7+
#include "hey/sup/iomanip.h"
8+
#include<Hey/ssup/math.h>
9+
#include"hello/how/stdlib.h"
10+
#include <great/wchar.h>
11+
#include"stdbool.h"
12+
#include<stdint.h>
13+
#include "hello12"
14+
#include<WsSup34>
15+
#include <heyYo3-lol>

test/test_C.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import os
2+
from language.C import extract_libraries
3+
4+
def test_extract_libraries():
5+
dir_path = os.path.dirname(os.path.realpath(__file__))
6+
files = ['fixtures/C.c']
7+
fq_files = [os.path.join(dir_path, f) for f in files]
8+
libs = extract_libraries(fq_files)
9+
assert len(libs) == 1
10+
11+
assert libs['C'] == [
12+
"assert.h",
13+
"complex.h",
14+
"ctype.h",
15+
"stdio.h",
16+
"float.h",
17+
"string.h",
18+
"hey/sup/iomanip.h",
19+
"Hey/ssup/math.h",
20+
"hello/how/stdlib.h",
21+
"great/wchar.h",
22+
"stdbool.h",
23+
"stdint.h",
24+
"hello12",
25+
"WsSup34",
26+
"heyYo3-lol"
27+
]

0 commit comments

Comments
 (0)