|
| 1 | +" Copyright 2017 Google Inc. All rights reserved. |
| 2 | +" |
| 3 | +" Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +" you may not use this file except in compliance with the License. |
| 5 | +" You may obtain a copy of the License at |
| 6 | +" |
| 7 | +" http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +" |
| 9 | +" Unless required by applicable law or agreed to in writing, software |
| 10 | +" distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +" See the License for the specific language governing permissions and |
| 13 | +" limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +let s:plugin = maktaba#plugin#Get('codefmt') |
| 17 | + |
| 18 | + |
| 19 | +function! s:FormatWithArgs(args) abort |
| 20 | + let l:executable = s:plugin.Flag('ruff_executable') |
| 21 | + let l:lines = getline(1, line('$')) |
| 22 | + let l:cmd = [l:executable, 'format'] + a:args |
| 23 | + if !empty(@%) |
| 24 | + let l:cmd += ['--stdin-filename=' . @%] |
| 25 | + endif |
| 26 | + let l:input = join(l:lines, "\n") |
| 27 | + let l:result = maktaba#syscall#Create(l:cmd).WithStdin(l:input).Call(0) |
| 28 | + if v:shell_error |
| 29 | + call maktaba#error#Shout('Error formatting file: %s', l:result.stderr) |
| 30 | + return |
| 31 | + endif |
| 32 | + let l:formatted = split(l:result.stdout, "\n") |
| 33 | + |
| 34 | + call maktaba#buffer#Overwrite(1, line('$'), l:formatted) |
| 35 | +endfunction |
| 36 | + |
| 37 | + |
| 38 | +"" |
| 39 | +" @private |
| 40 | +" Formatter: ruff |
| 41 | +function! codefmt#ruff#GetFormatter() abort |
| 42 | + let l:formatter = { |
| 43 | + \ 'name': 'ruff', |
| 44 | + \ 'setup_instructions': 'Install ruff ' . |
| 45 | + \ '(https://docs.astral.sh/ruff/).'} |
| 46 | + |
| 47 | + function l:formatter.IsAvailable() abort |
| 48 | + return executable(s:plugin.Flag('ruff_executable')) |
| 49 | + endfunction |
| 50 | + |
| 51 | + function l:formatter.AppliesToBuffer() abort |
| 52 | + return codefmt#formatterhelpers#FiletypeMatches(&filetype, 'python') |
| 53 | + endfunction |
| 54 | + |
| 55 | + function l:formatter.Format() abort |
| 56 | + call s:FormatWithArgs([]) |
| 57 | + endfunction |
| 58 | + |
| 59 | + "" |
| 60 | + " Reformat the current buffer with ruff or the binary named in |
| 61 | + " @flag(ruff_executable), only targeting the range between {startline} and |
| 62 | + " {endline}. |
| 63 | + " @throws ShellError |
| 64 | + function l:formatter.FormatRange(startline, endline) abort |
| 65 | + call maktaba#ensure#IsNumber(a:startline) |
| 66 | + call maktaba#ensure#IsNumber(a:endline) |
| 67 | + call s:FormatWithArgs(['--range=' . a:startline . ':' . a:endline]) |
| 68 | + endfunction |
| 69 | + |
| 70 | + return l:formatter |
| 71 | +endfunction |
0 commit comments