1
+ use std:: path:: Path ;
2
+
3
+ use anyhow:: Result ;
4
+ use log:: debug;
5
+ use rustpython_parser:: lexer:: LexResult ;
6
+
7
+ use crate :: autofix:: fixer:: Mode ;
8
+ use crate :: linter:: { check_path, tokenize} ;
9
+ use crate :: message:: Message ;
10
+ use crate :: settings:: Settings ;
11
+
1
12
mod ast;
2
13
mod autofix;
3
14
pub mod cache;
@@ -13,3 +24,49 @@ pub mod printer;
13
24
pub mod pyproject;
14
25
mod python;
15
26
pub mod settings;
27
+
28
+ /// Run ruff over Python source code directly.
29
+ pub fn check ( path : & Path , contents : & str ) -> Result < Vec < Message > > {
30
+ // Find the project root and pyproject.toml.
31
+ let project_root = pyproject:: find_project_root ( & [ path. to_path_buf ( ) ] ) ;
32
+ match & project_root {
33
+ Some ( path) => debug ! ( "Found project root at: {:?}" , path) ,
34
+ None => debug ! ( "Unable to identify project root; assuming current directory..." ) ,
35
+ } ;
36
+ let pyproject = pyproject:: find_pyproject_toml ( & project_root) ;
37
+ match & pyproject {
38
+ Some ( path) => debug ! ( "Found pyproject.toml at: {:?}" , path) ,
39
+ None => debug ! ( "Unable to find pyproject.toml; using default settings..." ) ,
40
+ } ;
41
+
42
+ let settings = Settings :: from_pyproject ( pyproject, project_root) ?;
43
+
44
+ // Tokenize once.
45
+ let tokens: Vec < LexResult > = tokenize ( contents) ;
46
+
47
+ // Determine the noqa line for every line in the source.
48
+ let noqa_line_for = noqa:: extract_noqa_line_for ( & tokens) ;
49
+
50
+ // Generate checks.
51
+ let checks = check_path (
52
+ path,
53
+ contents,
54
+ tokens,
55
+ & noqa_line_for,
56
+ & settings,
57
+ & Mode :: None ,
58
+ ) ?;
59
+
60
+ // Convert to messages.
61
+ let messages: Vec < Message > = checks
62
+ . into_iter ( )
63
+ . map ( |check| Message {
64
+ kind : check. kind ,
65
+ fixed : check. fix . map ( |fix| fix. applied ) . unwrap_or_default ( ) ,
66
+ location : check. location ,
67
+ filename : path. to_string_lossy ( ) . to_string ( ) ,
68
+ } )
69
+ . collect ( ) ;
70
+
71
+ Ok ( messages)
72
+ }
0 commit comments