-
Notifications
You must be signed in to change notification settings - Fork 10
/
add_requests_timeouts.py
55 lines (49 loc) · 1.84 KB
/
add_requests_timeouts.py
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
from codemodder.codemods.libcst_transformer import (
LibcstResultTransformer,
LibcstTransformerPipeline,
)
from codemodder.codemods.semgrep import SemgrepRuleDetector
from core_codemods.api import CoreCodemod, Metadata, Reference, ReviewGuidance
class TransformAddRequestsTimeouts(LibcstResultTransformer):
# Sets an arbitrary default timeout for all requests
DEFAULT_TIMEOUT = 60
change_description = "Add timeout to `requests` call"
def on_result_found(self, original_node, updated_node):
del original_node
return self.add_arg_to_call(updated_node, "timeout", self.DEFAULT_TIMEOUT)
# This codemod uses the lower level codemod and transformer APIs for the sake of example.
AddRequestsTimeouts = CoreCodemod(
metadata=Metadata(
name="add-requests-timeouts",
summary="Add timeout to `requests` calls",
review_guidance=ReviewGuidance.MERGE_AFTER_CURSORY_REVIEW,
references=[
Reference(
url="https://docs.python-requests.org/en/master/user/quickstart/#timeouts"
),
],
),
detector=SemgrepRuleDetector(
"""
- patterns:
- pattern-inside: |
import requests
...
- pattern: requests.$CALL(...)
- pattern-not: requests.$CALL(..., timeout=$TIMEOUT, ...)
- metavariable-pattern:
metavariable: $CALL
patterns:
- pattern-either:
- pattern: get
- pattern: post
- pattern: put
- pattern: delete
- pattern: head
- pattern: options
- pattern: patch
- pattern: request
"""
),
transformer=LibcstTransformerPipeline(TransformAddRequestsTimeouts),
)