Skip to content

Commit 86d85f2

Browse files
committed
fix: clean up unnecessary f-strings and grpc generator formatting
1 parent bbd1dfb commit 86d85f2

17 files changed

Lines changed: 73 additions & 71 deletions

contrib/api/generate-python-docs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@
116116

117117
def generate_docs(output_dir: Path, repo_root: Path):
118118
"""Generate documentation for all packages."""
119-
print(f"Generating Python documentation for all workspace packages...")
119+
print("Generating Python documentation for all workspace packages...")
120120
print(f"Output directory: {output_dir}")
121121

122122
# Clean and create output directory

contrib/msggen/msggen/gen/grpc/convert.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -65,14 +65,14 @@ def generate_composite(self, prefix, field: CompositeField, override=None):
6565
# The inner conversion applied to each element in the
6666
# array. The current item is called `i`
6767
mapping = {
68-
"hex": f"hex::decode(i).unwrap()",
69-
"secret": f"i.to_vec()",
70-
"hash": f"<Sha256 as AsRef<[u8]>>::as_ref(&i).to_vec()",
71-
"short_channel_id": f"i.to_string()",
72-
"short_channel_id_dir": f"i.to_string()",
73-
"pubkey": f"i.serialize().to_vec()",
74-
"txid": f"hex::decode(i).unwrap()",
75-
}.get(typ, f"i.into()")
68+
"hex": "hex::decode(i).unwrap()",
69+
"secret": "i.to_vec()",
70+
"hash": "<Sha256 as AsRef<[u8]>>::as_ref(&i).to_vec()",
71+
"short_channel_id": "i.to_string()",
72+
"short_channel_id_dir": "i.to_string()",
73+
"pubkey": "i.serialize().to_vec()",
74+
"txid": "hex::decode(i).unwrap()",
75+
}.get(typ, "i.into()")
7676

7777
self.write(f"// Field: {f.path}\n", numindent=3)
7878
if not f.optional:
@@ -138,7 +138,7 @@ def generate_composite(self, prefix, field: CompositeField, override=None):
138138
)
139139

140140
if f.deprecated:
141-
self.write(f"#[allow(deprecated)]\n", numindent=3)
141+
self.write("#[allow(deprecated)]\n", numindent=3)
142142
self.write(f"{name}: {rhs}, // Rule #2 for type {typ}\n", numindent=3)
143143

144144
elif isinstance(f, CompositeField):
@@ -149,10 +149,10 @@ def generate_composite(self, prefix, field: CompositeField, override=None):
149149
rhs = f"c.{name}.map(|v| v.into())"
150150
self.write(f"{name}: {rhs},\n", numindent=3)
151151
self.write(
152-
f"""\
153-
}}
154-
}}
155-
}}
152+
"""\
153+
}
154+
}
155+
}
156156
157157
"""
158158
)

contrib/msggen/msggen/gen/grpc/proto.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def generate_service(self, service: Service) -> None:
158158
)
159159

160160
self.write(
161-
f"""}}
161+
"""}
162162
"""
163163
)
164164

@@ -228,7 +228,7 @@ def generate_message(self, message: CompositeField, typename_override=None):
228228

229229
def generate(self, service: Service) -> None:
230230
"""Generate the GRPC protobuf file and write to `dest`"""
231-
self.write(f"""syntax = "proto3";\npackage cln;\n""")
231+
self.write("""syntax = "proto3";\npackage cln;\n""")
232232
self.write(
233233
"""
234234
// This file was automatically derived from the JSON-RPC schemas in

contrib/msggen/msggen/gen/grpc/server.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def write(self, text: str, numindent: Optional[int] = None):
2828

2929
def generate(self, service: Service) -> None:
3030
self.write(
31-
f"""\
31+
"""\
3232
use crate::pb::node_server::Node;
3333
use crate::pb;
3434
use cln_rpc::{{Request, Response, ClnRpc}};
@@ -113,7 +113,8 @@ def generate(self, service: Service) -> None:
113113
#[tonic::async_trait]
114114
impl Node for Server
115115
{{
116-
""",
116+
"""
117+
.replace("{{", "{").replace("}}", "}"),
117118
numindent=0,
118119
)
119120

contrib/msggen/msggen/gen/grpc/unconvert.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,21 +49,21 @@ def generate_composite(self, prefix, field: CompositeField, override=None) -> No
4949
if isinstance(f, ArrayField):
5050
typ = f.itemtype.typename
5151
mapping = {
52-
"hex": f"hex::encode(s)",
53-
"u32": f"s",
54-
"secret": f"s.try_into().unwrap()",
55-
"hash": f"Sha256::from_slice(&s).unwrap()",
56-
"short_channel_id": f"cln_rpc::primitives::ShortChannelId::from_str(&s).unwrap()",
57-
"short_channel_id_dir": f"cln_rpc::primitives::ShortChannelIdDir::from_str(&s).unwrap()",
58-
"pubkey": f"PublicKey::from_slice(&s).unwrap()",
59-
"txid": f"hex::encode(s)",
60-
}.get(typ, f"s.into()")
52+
"hex": "hex::encode(s)",
53+
"u32": "s",
54+
"secret": "s.try_into().unwrap()",
55+
"hash": "Sha256::from_slice(&s).unwrap()",
56+
"short_channel_id": "cln_rpc::primitives::ShortChannelId::from_str(&s).unwrap()",
57+
"short_channel_id_dir": "cln_rpc::primitives::ShortChannelIdDir::from_str(&s).unwrap()",
58+
"pubkey": "PublicKey::from_slice(&s).unwrap()",
59+
"txid": "hex::encode(s)",
60+
}.get(typ, "s.into()")
6161

6262
# TODO fix properly
6363
if typ in ["ListtransactionsTransactionsType"]:
6464
continue
6565
if name == "state_changes":
66-
self.write(f" state_changes: None,")
66+
self.write(" state_changes: None,")
6767
continue
6868

6969
if not f.optional:
@@ -147,10 +147,10 @@ def generate_composite(self, prefix, field: CompositeField, override=None) -> No
147147
self.write(f"{name}: {rhs},\n", numindent=3)
148148

149149
self.write(
150-
f"""\
151-
}}
152-
}}
153-
}}
150+
"""\
151+
}
152+
}
153+
}
154154
155155
"""
156156
)

contrib/msggen/msggen/gen/grpc2py.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def {converter_name}(m):
207207
cleanup=False,
208208
)
209209

210-
self.write(f" }})\n", cleanup=False)
210+
self.write(" }})\n", cleanup=False)
211211

212212
# Add ourselves to the converters so if we were generated as a
213213
# dependency for a composite they can find us again. We have

contrib/msggen/msggen/gen/rpc/rust.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -179,10 +179,10 @@ def gen_enum(e, meta, override):
179179
norm = v.normalized()
180180
decl += f' {typename}::{norm} => "{norm}",\n'
181181
decl += dedent(
182-
f"""\
183-
}}.to_string()
184-
}}
185-
}}
182+
"""\
183+
}.to_string()
184+
}
185+
}
186186
187187
"""
188188
)
@@ -196,7 +196,7 @@ def gen_enum(e, meta, override):
196196
defi += rename_if_necessary(str(e.name), e.name.normalized())
197197
defi += f" pub {e.name.normalized()}: {typename},\n"
198198
else:
199-
defi = f' #[serde(skip_serializing_if = "Option::is_none")]\n'
199+
defi = ' #[serde(skip_serializing_if = "Option::is_none")]\n'
200200
defi += f" pub {e.name.normalized()}: Option<{typename}>,\n"
201201

202202
return defi, decl
@@ -223,7 +223,7 @@ def rename_if_necessary(original, name):
223223
if str(original) != str(name):
224224
return f" #[serde(rename = \"{original}\")]\n"
225225
else:
226-
return f""
226+
return ""
227227

228228

229229
def gen_array(a, meta, override=None):
@@ -390,14 +390,15 @@ def generate_response_trait_impl(self, method: Method):
390390
def generate_enums(self, service: Service):
391391
"""The Request and Response enums serve as parsing primitives."""
392392
self.write(
393-
f"""\
393+
"""\
394394
use serde::{{Deserialize, Serialize}};
395395
396396
#[derive(Clone, Debug, Serialize, Deserialize)]
397397
#[serde(tag = "method", content = "params")]
398398
#[serde(rename_all = "lowercase")]
399399
pub enum Request {{
400400
"""
401+
.replace("{{", "{").replace("}}", "}"),
401402
)
402403

403404
for method in service.methods:
@@ -410,13 +411,13 @@ def generate_enums(self, service: Service):
410411
)
411412

412413
self.write(
413-
f"""\
414-
}}
414+
"""\
415+
}
415416
416417
#[derive(Clone, Debug, Serialize, Deserialize)]
417418
#[serde(tag = "method", content = "result")]
418419
#[serde(rename_all = "lowercase")]
419-
pub enum Response {{
420+
pub enum Response {
420421
"""
421422
)
422423

@@ -430,8 +431,8 @@ def generate_enums(self, service: Service):
430431
)
431432

432433
self.write(
433-
f"""\
434-
}}
434+
"""\
435+
}
435436
436437
"""
437438
)

contrib/pyln-grpc-proto/pyln/grpc/node_pb2_grpc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
if _version_not_supported:
1919
raise RuntimeError(
2020
f'The grpc package installed is at version {GRPC_VERSION},'
21-
+ f' but the generated code in node_pb2_grpc.py depends on'
21+
+ ' but the generated code in node_pb2_grpc.py depends on'
2222
+ f' grpcio>={GRPC_GENERATED_VERSION}.'
2323
+ f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
2424
+ f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'

tests/autogenerate-rpc-examples.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ def update_examples_in_schema_files():
391391
with open(TEMP_EXAMPLES_FILE, 'w+', encoding='utf-8') as file:
392392
json.dump({'new_values_list': NEW_VALUES_LIST, 'replace_response_values': REPLACE_RESPONSE_VALUES[4:], 'examples_json': EXAMPLES_JSON, 'updated_examples_json': updated_examples}, file, indent=2, ensure_ascii=False)
393393

394-
logger.info(f'Updated All Examples in Schema Files!')
394+
logger.info('Updated All Examples in Schema Files!')
395395
return None
396396

397397

@@ -1138,12 +1138,12 @@ def generate_wait_examples(l1, l2, bitcoind, executor):
11381138
if curr_blockheight < 130:
11391139
bitcoind.generate_block(130 - curr_blockheight)
11401140
sync_blockheight(bitcoind, [l2])
1141-
update_example(node=l2, method='waitblockheight', params={'blockheight': 126}, description=[f'This will return immediately since the current blockheight exceeds the requested waitblockheight.'])
1141+
update_example(node=l2, method='waitblockheight', params={'blockheight': 126}, description=['This will return immediately since the current blockheight exceeds the requested waitblockheight.'])
11421142
wbh = executor.submit(l2.rpc.waitblockheight, curr_blockheight + 1, 600)
11431143
bitcoind.generate_block(1)
11441144
sync_blockheight(bitcoind, [l2])
11451145
wbhres = wbh.result(5)
1146-
update_example(node=l2, method='waitblockheight', params={'blockheight': curr_blockheight + 1, 'timeout': 600}, response=wbhres, description=[f'This will return after the next block is mined because requested waitblockheight is one block higher than the current blockheight.'])
1146+
update_example(node=l2, method='waitblockheight', params={'blockheight': curr_blockheight + 1, 'timeout': 600}, response=wbhres, description=['This will return after the next block is mined because requested waitblockheight is one block higher than the current blockheight.'])
11471147
REPLACE_RESPONSE_VALUES.extend([
11481148
{'data_keys': ['payment_hash'], 'original_value': wspc_res['details']['payment_hash'], 'new_value': NEW_VALUES_LIST['payment_hash_wspc_1']},
11491149
{'data_keys': ['paid_at'], 'original_value': waires['paid_at'], 'new_value': NEW_VALUES_LIST['time_at_850']},
@@ -1257,7 +1257,7 @@ def generate_utils_examples(l1, l2, l3, l4, l5, l6, c23_2, c34_2, inv_l11, inv_l
12571257

12581258
# SQL
12591259
update_example(node=l1, method='sql', params={'query': 'SELECT id FROM peers'}, description=['A simple peers selection query:'])
1260-
update_example(node=l1, method='sql', params=[f"SELECT label, description, status FROM invoices WHERE label='label inv_l12'"], description=["A statement containing `=` needs `-o` in shell:"])
1260+
update_example(node=l1, method='sql', params=["SELECT label, description, status FROM invoices WHERE label='label inv_l12'"], description=["A statement containing `=` needs `-o` in shell:"])
12611261
sql_res3 = l1.rpc.sql(f"SELECT nodeid FROM nodes WHERE nodeid != x'{l3.info['id']}'")
12621262
update_example(node=l1, method='sql', params=[f"SELECT nodeid FROM nodes WHERE nodeid != x'{NEW_VALUES_LIST['l3_id']}'"], description=['If you want to get specific nodeid values from the nodes table:'], response=sql_res3)
12631263
sql_res4 = l1.rpc.sql(f"SELECT nodeid FROM nodes WHERE nodeid IN (x'{l1.info['id']}', x'{l3.info['id']}')")
@@ -1524,7 +1524,7 @@ def generate_channels_examples(node_factory, bitcoind, l1, l3, l4, l5):
15241524
utxo = f"{outputs[0]['txid']}:{outputs[0]['output']}"
15251525
c41res = update_example(node=l4, method='fundchannel',
15261526
params={'id': l1.info['id'], 'amount': 'all', 'feerate': 'normal', 'push_msat': 100000, 'utxos': [utxo]},
1527-
description=[f'This example shows how to to open new channel with peer 1 from one whole utxo (you can use **listfunds** command to get txid and vout):'])
1527+
description=['This example shows how to to open new channel with peer 1 from one whole utxo (you can use **listfunds** command to get txid and vout):'])
15281528
# Close newly funded channels to bring the setup back to initial state
15291529
l3.rpc.close(c35res['channel_id'])
15301530
l4.rpc.close(c41res['channel_id'])
@@ -1593,7 +1593,7 @@ def generate_channels_examples(node_factory, bitcoind, l1, l3, l4, l5):
15931593
]
15941594
example_destinations_2 = [
15951595
{
1596-
'id': f'fakenodeid' + ('03' * 28) + '@127.0.0.1:19736',
1596+
'id': 'fakenodeid' + ('03' * 28) + '@127.0.0.1:19736',
15971597
'amount': 50000
15981598
},
15991599
{
@@ -1696,7 +1696,7 @@ def generate_autoclean_delete_examples(l1, l2, l3, l4, l5, c12, c23):
16961696
try:
16971697
logger.info('Auto-clean and Delete Start...')
16981698
l2.rpc.close(l5.info['id'])
1699-
dfc_res1 = update_example(node=l2, method='dev-forget-channel', params={'id': l5.info['id']}, description=[f'Forget a channel by peer pubkey when only one channel exists with the peer:'])
1699+
dfc_res1 = update_example(node=l2, method='dev-forget-channel', params={'id': l5.info['id']}, description=['Forget a channel by peer pubkey when only one channel exists with the peer:'])
17001700

17011701
# Create invoices for delpay and delinvoice examples
17021702
inv_l35 = l3.rpc.invoice('50000sat', 'lbl_l35', 'l35 description')
@@ -1741,7 +1741,7 @@ def generate_autoclean_delete_examples(l1, l2, l3, l4, l5, c12, c23):
17411741
update_example(node=l2, method='delforward', params={'in_channel': c12, 'in_htlc_id': local_failed_forwards[0]['in_htlc_id'], 'status': 'local_failed'})
17421742
if len(failed_forwards) > 0 and 'in_htlc_id' in failed_forwards[0]:
17431743
update_example(node=l2, method='delforward', params={'in_channel': c12, 'in_htlc_id': failed_forwards[0]['in_htlc_id'], 'status': 'failed'})
1744-
dfc_res2 = update_example(node=l2, method='dev-forget-channel', params={'id': l3.info['id'], 'short_channel_id': c23, 'force': True}, description=[f'Forget a channel by short channel id when peer has multiple channels:'])
1744+
dfc_res2 = update_example(node=l2, method='dev-forget-channel', params={'id': l3.info['id'], 'short_channel_id': c23, 'force': True}, description=['Forget a channel by short channel id when peer has multiple channels:'])
17451745

17461746
# Autoclean
17471747
update_example(node=l2, method='autoclean-once', params=['failedpays', 1])

tests/test_closing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4076,7 +4076,7 @@ def test_peer_anchor_push(node_factory, bitcoind, executor, chainparams):
40764076
assert len(bitcoind.rpc.getrawmempool()) == 2
40774077

40784078
# Feerate tops out at +1, so this is the same. This time we mine it!
4079-
l2.daemon.wait_for_log(fr"Worth fee [0-9]*sat for remote commit tx to get 100000000msat at block 125 \(\+1\) at feerate 15000perkw")
4079+
l2.daemon.wait_for_log(r"Worth fee [0-9]*sat for remote commit tx to get 100000000msat at block 125 \(\+1\) at feerate 15000perkw")
40804080
l2.daemon.wait_for_log("sendrawtx exit 0")
40814081

40824082
bitcoind.generate_block(1, needfeerate=15000)

0 commit comments

Comments
 (0)