This repository was archived by the owner on Mar 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpython.ts
More file actions
63 lines (55 loc) · 2.26 KB
/
python.ts
File metadata and controls
63 lines (55 loc) · 2.26 KB
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
import * as path from 'path'
import { pythonStyleComment } from './comments'
import { FilterContext, LanguageSpec, Result } from './spec'
import { extractFromLines, filterResultsByImports, removeExtension } from './util'
/**
* Filter a list of candidate definitions to select those likely to be valid
* cross-references for a definition in this file. Accept candidates whose
* path matches an absolute or relative (to the current file) import.
*
* If no candidates match, fall back to the raw (unfiltered) results so that
* the user doesn't get an empty response unless there really is nothing.
*/
function filterDefinitions<T extends Result>(results: T[], { filePath, fileContent }: FilterContext): T[] {
const importPaths = extractFromLines(fileContent, /^import ([\w.]*)/, /^from ([\w.]*)/)
return filterResultsByImports(results, importPaths, ({ file }, importPath) => {
const relativePath = relativeImportPath(filePath, importPath)
if (relativePath) {
// Match results imported relatively
return relativePath === removeExtension(file)
}
// Match results imported absolutely
return file.includes(absoluteImportPath(importPath))
})
}
/**
* Converts an absolute Python import path into a file path.
*
* @param importPath The absolute Python import path.
*/
function absoluteImportPath(importPath: string): string {
return importPath.replace(/\./g, '/')
}
/**
* Converts a Python import path into a file path relative to the
* given source path. If the import path is not relative, method
* function returns undefined.
*
* @param sourcePath The source file path relative to the repository root.
* @param importPath The relative or absolute Python import path (`.a.b`, `a.b.c`).
*/
export function relativeImportPath(sourcePath: string, importPath: string): string | undefined {
const match = /^\.(\.*)(.*)/.exec(importPath)
if (!match) {
return undefined
}
const [, parentDots, rest] = match
return path.join(path.dirname(sourcePath), '../'.repeat(parentDots.length), rest.replace(/\./g, '/'))
}
export const pythonSpec: LanguageSpec = {
languageID: 'python',
stylized: 'Python',
fileExts: ['py'],
commentStyles: [pythonStyleComment],
filterDefinitions,
}