Skip to content
Clone

style(rust): apply clippy fixes and format the workspace

cargo clippy --fix collapsed nested if-let chains into let-chains, replaced or_insert_with(Vec::new) with or_default, dropped redundant to_string() on &str error constructors and a no-op struct update; the two remaining lints (the needless update in runs.rs and the example's field-reassign) were fixed by hand. cargo fmt --all reflowed the pre-existing diffs in lib/agents and lib/pulls. clippy --workspace --all-targets --all-features is now warning-free and fmt --check passes.
ZhenYi committed
parent 2f5d35e commit ddd7529 Browse files

17 files changed

+140 −143

File tree 17
Modified app/runner/src/main.rs View app/runner/src/main.rs
@@ -114,10 +114,10 @@
114114 let mut jobs = tokio::task::JoinSet::new();
115115 loop {
116116 while jobs.len() >= cfg.capacity.max(1) as usize {
117 if let Some(result) = jobs.join_next().await {
118 if let Err(error) = result {
119 warn!(%error,"runner job task failed");
120 }
117 if let Some(result) = jobs.join_next().await
118 && let Err(error) = result
119 {
120 warn!(%error,"runner job task failed");
121121 }
122122 }
123123 let payload = match client.claim(&ClaimRequest { wait_secs: None }).await {
Modified lib/agents/src/handlers/avatar.rs View lib/agents/src/handlers/avatar.rs
@@ -76,4 +76,4 @@
7676 .agent_avatar_url(uid, &path.space_name, path.collection_id, path.agent_id)
7777 .await?;
7878 Ok(Redirect::temporary(&url))
79}
No newline at end of file
79}
Modified lib/agents/src/handlers/builder.rs View lib/agents/src/handlers/builder.rs
@@ -33,4 +33,4 @@
3333 .builder_chat(uid, &path.space_name, path.collection_id, cmd)
3434 .await?;
3535 Ok(AppResponseData::ok(result))
36}
No newline at end of file
36}
Modified lib/agents/src/services/agents.rs View lib/agents/src/services/agents.rs
@@ -218,7 +218,8 @@
218218 collection_id: Uuid,
219219 q: ListAgentQuery,
220220 ) -> Result<AgentPage, AgentError> {
221 let (space, collection) = collection_context(self, caller, space_name, collection_id).await?;
221 let (space, collection) =
222 collection_context(self, caller, space_name, collection_id).await?;
222223 let (limit, offset) = self.paginate(q.limit, q.offset);
223224
224225 let mut select =
@@ -263,7 +264,8 @@
263264 collection_id: Uuid,
264265 agent_id: Uuid,
265266 ) -> Result<AgentDto, AgentError> {
266 let (space, _, row) = agent_context(self, caller, space_name, collection_id, agent_id).await?;
267 let (space, _, row) =
268 agent_context(self, caller, space_name, collection_id, agent_id).await?;
267269 let users = self.load_user_briefs(&[row.author_id]).await?;
268270 let author = users.get(&row.author_id).cloned();
269271 Ok(Self::agent_dto(row, author, &space.lower_name))
Modified lib/agents/src/services/avatar.rs View lib/agents/src/services/avatar.rs
@@ -30,7 +30,8 @@
3030 content_type: &str,
3131 bytes: &[u8],
3232 ) -> Result<AgentDto, AgentError> {
33 let (space, _, row) = agent_context(self, caller, space_name, collection_id, agent_id).await?;
33 let (space, _, row) =
34 agent_context(self, caller, space_name, collection_id, agent_id).await?;
3435 require_collection_manage(self, &space, caller).await?;
3536 if bytes.is_empty() {
3637 return Err(AgentError::BadRequest("avatar image is empty".to_string()));
@@ -40,7 +41,12 @@
4041 "avatar image is larger than 2 MB".to_string(),
4142 ));
4243 }
43 let clean = content_type.split(';').next().unwrap_or(content_type).trim().to_lowercase();
44 let clean = content_type
45 .split(';')
46 .next()
47 .unwrap_or(content_type)
48 .trim()
49 .to_lowercase();
4450 let extension = match clean.as_str() {
4551 "image/jpeg" | "image/jpg" => "jpg",
4652 "image/png" => "png",
@@ -49,7 +55,7 @@
4955 _ => {
5056 return Err(AgentError::BadRequest(
5157 "unsupported avatar image type".to_string(),
52 ))
58 ));
5359 }
5460 };
5561 let key = format!("{AGENT_AVATAR_PREFIX}/{agent_id}.{extension}");
@@ -64,7 +70,9 @@
6470 am.avatar_url = Set(Some(format!("storage://{key}")));
6571 am.updated_at = Set(Some(OffsetDateTime::now_utc()));
6672 let updated = am.update(self.db().write()).await?;
67 if let Err(error) = export::redis::delete(&self.state.redis, &avatar_cache_key(agent_id)).await {
73 if let Err(error) =
74 export::redis::delete(&self.state.redis, &avatar_cache_key(agent_id)).await
75 {
6876 tracing::warn!(%error, "failed to drop cached agent avatar url");
6977 }
7078
@@ -115,4 +123,4 @@
115123 }
116124 Ok(url)
117125 }
118}
No newline at end of file
126}
Modified lib/agents/src/services/builder.rs View lib/agents/src/services/builder.rs
@@ -73,7 +73,11 @@
7373 require_collection_manage(self, &space, caller).await?;
7474 let _ = collection_context(self, caller, space_name, collection_id).await?;
7575
76 if cmd.messages.iter().all(|message| message.content.trim().is_empty()) {
76 if cmd
77 .messages
78 .iter()
79 .all(|message| message.content.trim().is_empty())
80 {
7781 return Err(AgentError::BadRequest(
7882 "builder conversation is empty".to_string(),
7983 ));
@@ -173,9 +177,7 @@
173177 agent::client::AgentError::NotConfigured(message) => {
174178 AgentError::RuntimeUnavailable(message)
175179 }
176 agent::client::AgentError::Rejected { .. } => {
177 AgentError::BadRequest(error.to_string())
178 }
180 agent::client::AgentError::Rejected { .. } => AgentError::BadRequest(error.to_string()),
179181 other => AgentError::Internal(other.to_string()),
180182 }
181}
No newline at end of file
183}
Modified lib/agents/src/services/chat.rs View lib/agents/src/services/chat.rs
@@ -379,7 +379,12 @@
379379 } else {
380380 Vec::new()
381381 };
382 let repo = match cmd.repo.as_deref().map(str::trim).filter(|repo| !repo.is_empty()) {
382 let repo = match cmd
383 .repo
384 .as_deref()
385 .map(str::trim)
386 .filter(|repo| !repo.is_empty())
387 {
383388 Some(repo) => Some(self.authorize_repo(&space, caller, repo).await?),
384389 None => None,
385390 };
@@ -444,9 +449,7 @@
444449 Ok(vec![proto::McpServerSpecMessage {
445450 name: "gitdata".to_string(),
446451 url: url.to_string(),
447 description: Some(
448 "GitData 平台工具:仓库、工单、合并请求、空间与用户信息".to_string(),
449 ),
452 description: Some("GitData 平台工具:仓库、工单、合并请求、空间与用户信息".to_string()),
450453 headers,
451454 tool_prefix: None,
452455 }])
@@ -681,4 +684,4 @@
681684 SpaceTokenError::BotNameConflict(message) => AgentError::Conflict(message),
682685 other => AgentError::Internal(other.to_string()),
683686 }
684}
No newline at end of file
687}
Modified lib/agents/src/share/authz.rs View lib/agents/src/share/authz.rs
@@ -26,20 +26,12 @@
2626/// Whether the caller may attach the platform MCP to an agent run: only space
2727/// owners or members with MANAGE_CHANNELS, and only while an MCP endpoint the
2828/// sandbox runtime can reach is configured.
29pub async fn can_enable_mcp(
30 service: &AgentsService,
31 space: &spaces::Model,
32 caller: Uuid,
33) -> bool {
29pub async fn can_enable_mcp(service: &AgentsService, space: &spaces::Model, caller: Uuid) -> bool {
3430 mcp_configured(service) && can_manage_mcp(service, space, caller).await
3531}
3632
3733/// Permission half of [`can_enable_mcp`], without the configuration check.
38pub async fn can_manage_mcp(
39 service: &AgentsService,
40 space: &spaces::Model,
41 caller: Uuid,
42) -> bool {
34pub async fn can_manage_mcp(service: &AgentsService, space: &spaces::Model, caller: Uuid) -> bool {
4335 if space.owner_id == caller {
4436 return true;
4537 }
Modified lib/ci/examples/actions_fixture.rs View lib/ci/examples/actions_fixture.rs
@@ -130,23 +130,25 @@
130130 }
131131 .insert(service.db_write())
132132 .await?;
133 let mut runner_config = config::runner::RunnerConfig::default();
134 runner_config.server_url = "http://127.0.0.1:43120".into();
135 runner_config.registration_token = token;
136 runner_config.name = "fixture-client".into();
137 runner_config.actions_engine_binary = service.config().ci.actions_engine_binary.clone();
138 runner_config.workspace_root = directory.join("workspaces").to_string_lossy().into_owned();
139 runner_config.actions_node_runtimes = BTreeMap::from([(
140 "node24".into(),
141 std::env::current_dir()?
142 .join("target/node24/bin/node")
133 let runner_config = config::runner::RunnerConfig {
134 server_url: "http://127.0.0.1:43120".into(),
135 registration_token: token,
136 name: "fixture-client".into(),
137 actions_engine_binary: service.config().ci.actions_engine_binary.clone(),
138 workspace_root: directory.join("workspaces").to_string_lossy().into_owned(),
139 actions_node_runtimes: BTreeMap::from([(
140 "node24".into(),
141 std::env::current_dir()?
142 .join("target/node24/bin/node")
143 .to_string_lossy()
144 .into_owned(),
145 )]),
146 actions_cache_dir: directory
147 .join("action-cache")
143148 .to_string_lossy()
144149 .into_owned(),
145 )]);
146 runner_config.actions_cache_dir = directory
147 .join("action-cache")
148 .to_string_lossy()
149 .into_owned();
150 ..Default::default()
151 };
150152 let client = runner::client::RunnerClient::new(&runner_config)?;
151153 let registration = client
152154 .register(&ci_protocol::runner::RegisterRequest {
Modified lib/ci/src/actions_payload.rs View lib/ci/src/actions_payload.rs
@@ -171,21 +171,20 @@
171171 request["secrets"] = json!(secrets);
172172 secrets = serde_json::from_value(self.actions_engine(request).await?)?;
173173 }
174 if let Some(environment) = &job.environment {
175 if let Some(environment) = self
174 if let Some(environment) = &job.environment
175 && let Some(environment) = self
176176 .find_actions_environment(job.space_id, job.repo_id, environment)
177177 .await?
178 {
179 let rows = models::ci::ci_secret::Entity::find()
180 .filter(models::ci::ci_secret::Column::EnvironmentId.eq(environment.id))
181 .all(self.db_write())
182 .await?;
183 for row in rows {
184 secrets.insert(
185 row.name,
186 crate::secrets::decrypt(self.encryption_key(), &row.value_ciphertext)?,
187 );
188 }
178 {
179 let rows = models::ci::ci_secret::Entity::find()
180 .filter(models::ci::ci_secret::Column::EnvironmentId.eq(environment.id))
181 .all(self.db_write())
182 .await?;
183 for row in rows {
184 secrets.insert(
185 row.name,
186 crate::secrets::decrypt(self.encryption_key(), &row.value_ciphertext)?,
187 );
189188 }
190189 }
191190 Ok(secrets)
Modified lib/ci/src/actions_scheduler.rs View lib/ci/src/actions_scheduler.rs
@@ -29,13 +29,12 @@
2929 .and_then(|value| serde_json::from_value(value.clone()).ok())
3030 .unwrap_or_default();
3131 let context = job.actions_context.as_ref().unwrap_or(&Value::Null);
32 if let Some(group) = context["instance"]["group"].as_str() {
33 if !capabilities
32 if let Some(group) = context["instance"]["group"].as_str()
33 && !capabilities
3434 .iter()
3535 .any(|cap| cap == &format!("runner-group:{group}"))
36 {
37 return Ok(false);
38 }
36 {
37 return Ok(false);
3938 }
4039 let definition =
4140 &context["workflow"]["document"]["jobs"][context["job"].as_str().unwrap_or_default()];
@@ -54,16 +53,15 @@
5453 {
5554 return Ok(false);
5655 }
57 if let Some(environment) = job.environment.as_deref() {
58 if let Some(environment) = self
56 if let Some(environment) = job.environment.as_deref()
57 && let Some(environment) = self
5958 .find_actions_environment(job.space_id, job.repo_id, environment)
6059 .await?
61 {
62 let required: Vec<String> =
63 serde_json::from_value(environment.required_labels).unwrap_or_default();
64 if required.iter().any(|label| !labels.contains(label)) {
65 return Ok(false);
66 }
60 {
61 let required: Vec<String> =
62 serde_json::from_value(environment.required_labels).unwrap_or_default();
63 if required.iter().any(|label| !labels.contains(label)) {
64 return Ok(false);
6765 }
6866 }
6967 let txn = self.db_write().begin().await?;
@@ -386,13 +384,13 @@
386384 let mut groups = BTreeMap::<(Uuid, String), Vec<workflow_run::Model>>::new();
387385 let mut changed = 0;
388386 for run in runs {
389 if ci_protocol::actions::from_snapshot(&run.definition).is_some() {
390 if let Some(group) = &run.concurrency_group {
391 groups
392 .entry((run.repo_id, group.to_lowercase()))
393 .or_default()
394 .push(run);
395 }
387 if ci_protocol::actions::from_snapshot(&run.definition).is_some()
388 && let Some(group) = &run.concurrency_group
389 {
390 groups
391 .entry((run.repo_id, group.to_lowercase()))
392 .or_default()
393 .push(run);
396394 }
397395 }
398396 for (_, mut runs) in groups {
@@ -432,16 +430,14 @@
432430 .actions_context
433431 .as_ref()
434432 .map(|ctx| &ctx["instance"]["concurrency"])
435 {
436 if let Some(group) = concurrency
433 && let Some(group) = concurrency
437434 .as_str()
438435 .or_else(|| concurrency["group"].as_str())
439 {
440 groups
441 .entry((job.repo_id, group.to_lowercase()))
442 .or_default()
443 .push(job);
444 }
436 {
437 groups
438 .entry((job.repo_id, group.to_lowercase()))
439 .or_default()
440 .push(job);
445441 }
446442 }
447443 for (_, mut jobs) in groups {
Modified lib/ci/src/runs.rs View lib/ci/src/runs.rs
@@ -186,16 +186,15 @@
186186 .event_payload
187187 .get("event_id")
188188 .map(|id| format!("{id}:{}:{}", workflow.file, seed.git_ref));
189 if let Some(key) = &event_key {
190 if let Some(existing) = workflow_run::Entity::find()
189 if let Some(key) = &event_key
190 && let Some(existing) = workflow_run::Entity::find()
191191 .filter(workflow_run::Column::EventKey.eq(key))
192192 .one(self.db_write())
193193 .await?
194 {
195 self.emit_actions_workflow_run(&existing, "requested")
196 .await?;
197 return Ok(existing.id);
198 }
194 {
195 self.emit_actions_workflow_run(&existing, "requested")
196 .await?;
197 return Ok(existing.id);
199198 }
200199 let concurrency_group = workflow
201200 .definition
@@ -210,14 +209,13 @@
210209 repo.id.as_u128() as i64
211210 ))
212211 .await?;
213 if let Some(key) = &event_key {
214 if let Some(existing) = workflow_run::Entity::find()
212 if let Some(key) = &event_key
213 && let Some(existing) = workflow_run::Entity::find()
215214 .filter(workflow_run::Column::EventKey.eq(key))
216215 .one(&txn)
217216 .await?
218 {
219 return Ok(existing.id);
220 }
217 {
218 return Ok(existing.id);
221219 }
222220 let actions_id = if workflow.actions.is_some() {
223221 Some(crate::actions::identity(&txn, run_id, "run").await?)
@@ -257,7 +255,6 @@
257255 finished_at: Set(None),
258256 created_at: Set(now),
259257 updated_at: Set(now),
260 ..Default::default()
261258 }
262259 .insert(&txn)
263260 .await?;
@@ -339,13 +336,12 @@
339336 }
340337
341338 txn.commit().await?;
342 if workflow.actions.is_some() {
343 if let Some(run) = workflow_run::Entity::find_by_id(run_id)
339 if workflow.actions.is_some()
340 && let Some(run) = workflow_run::Entity::find_by_id(run_id)
344341 .one(self.db_write())
345342 .await?
346 {
347 self.emit_actions_workflow_run(&run, "requested").await?;
348 }
343 {
344 self.emit_actions_workflow_run(&run, "requested").await?;
349345 }
350346 tracing::info!(
351347 run_id = %run_id,
Modified lib/ci/src/scheduler.rs View lib/ci/src/scheduler.rs
@@ -255,16 +255,15 @@
255255 if job.is_template {
256256 continue;
257257 }
258 if job.actions_context.is_some() {
259 if runner.protocol_version.unwrap_or(1) < 2
258 if job.actions_context.is_some()
259 && (runner.protocol_version.unwrap_or(1) < 2
260260 || !runner
261261 .capabilities
262262 .as_ref()
263263 .and_then(|v| v.as_array())
264 .is_some_and(|v| v.iter().any(|c| c.as_str() == Some("actions-v2")))
265 {
266 continue;
267 }
264 .is_some_and(|v| v.iter().any(|c| c.as_str() == Some("actions-v2"))))
265 {
266 continue;
268267 }
269268 let job_labels: Vec<String> =
270269 serde_json::from_value(job.runs_on.clone()).unwrap_or_default();
@@ -458,13 +457,12 @@
458457 .filter(workflow_run::Column::State.eq(WorkflowRunState::Queued))
459458 .exec(self.db_write())
460459 .await?;
461 if updated.rows_affected > 0 {
462 if let Some(run) = workflow_run::Entity::find_by_id(run_id)
460 if updated.rows_affected > 0
461 && let Some(run) = workflow_run::Entity::find_by_id(run_id)
463462 .one(self.db_write())
464463 .await?
465 {
466 self.emit_actions_workflow_run(&run, "in_progress").await?;
467 }
464 {
465 self.emit_actions_workflow_run(&run, "in_progress").await?;
468466 }
469467 Ok(())
470468 }
Modified lib/issues/src/services/boards.rs View lib/issues/src/services/boards.rs
@@ -212,12 +212,12 @@
212212 Some(raw) => self.normalize_board_prefix(raw)?,
213213 None => None,
214214 };
215 if let Some(ref prefix) = prefix {
216 if self.board_prefix_taken(space.id, prefix, None).await? {
217 return Err(IssueError::BadRequest(
218 "board prefix is already used by another board".to_string(),
219 ));
220 }
215 if let Some(ref prefix) = prefix
216 && self.board_prefix_taken(space.id, prefix, None).await?
217 {
218 return Err(IssueError::BadRequest(
219 "board prefix is already used by another board".to_string(),
220 ));
221221 }
222222
223223 if let Some(p) = cmd.parent_dir_id {
@@ -423,15 +423,14 @@
423423 Some(raw) => self.normalize_board_prefix(raw)?,
424424 None => None,
425425 };
426 if let Some(ref prefix) = prefix {
427 if self
426 if let Some(ref prefix) = prefix
427 && self
428428 .board_prefix_taken(space.id, prefix, Some(board_id))
429429 .await?
430 {
431 return Err(IssueError::BadRequest(
432 "board prefix is already used by another board".to_string(),
433 ));
434 }
430 {
431 return Err(IssueError::BadRequest(
432 "board prefix is already used by another board".to_string(),
433 ));
435434 }
436435 am.prefix = Set(prefix);
437436 }
Modified lib/issues/src/services/issues.rs View lib/issues/src/services/issues.rs
@@ -392,9 +392,7 @@
392392 .collect();
393393 for rel in rels {
394394 if let Some(label) = by_id.get(&rel.label_id) {
395 map.entry(rel.issue_id)
396 .or_insert_with(Vec::new)
397 .push(label.clone());
395 map.entry(rel.issue_id).or_default().push(label.clone());
398396 }
399397 }
400398 for rows in map.values_mut() {
Modified lib/pulls/src/services/relations.rs View lib/pulls/src/services/relations.rs
@@ -106,7 +106,11 @@
106106 "#{} {}{}",
107107 pull.autoincrement_id,
108108 clipped,
109 if title.chars().count() > 80 { "…" } else { "" }
109 if title.chars().count() > 80 {
110 "…"
111 } else {
112 ""
113 }
110114 );
111115 let linked = matches!(event_type, IssueEventType::PullLinked);
112116 issue_event_line::ActiveModel {
Modified lib/webapi/src/cleanup.rs View lib/webapi/src/cleanup.rs
@@ -456,7 +456,7 @@
456456 }
457457 _ => {
458458 return Err(ApiError::bad_request(
459 "visibility is not adjustable for this object type".to_string(),
459 "visibility is not adjustable for this object type",
460460 ));
461461 }
462462 }
@@ -485,9 +485,7 @@
485485 let uid = require_uid(&session)?;
486486 require_owner(&state, &space_name, uid).await?;
487487 if kind != "repo" {
488 return Err(ApiError::bad_request(
489 "only repositories support archiving".to_string(),
490 ));
488 return Err(ApiError::bad_request("only repositories support archiving"));
491489 }
492490 let repo = repo_row_by_dir(state.space.db().read(), object_id).await?;
493491 state
@@ -522,7 +520,7 @@
522520 match kind.as_str() {
523521 "repo" => {
524522 return Err(ApiError::bad_request(
525 "repositories cannot be deleted here; archive them instead".to_string(),
523 "repositories cannot be deleted here; archive them instead",
526524 ));
527525 }
528526 "board" => {
@@ -602,7 +600,7 @@
602600 > 0;
603601 if has_companion {
604602 return Err(ApiError::bad_request(
605 "this node holds an object; delete it from its own row instead".to_string(),
603 "this node holds an object; delete it from its own row instead",
606604 ));
607605 }
608606 let children = dirs::Entity::find()
@@ -633,7 +631,7 @@
633631 txn.commit().await.map_err(db_internal)?;
634632 }
635633 _ => {
636 return Err(ApiError::bad_request("unsupported object kind".to_string()));
634 return Err(ApiError::bad_request("unsupported object kind"));
637635 }
638636 }
639637 Ok(AppResponseData::empty())
@@ -663,7 +661,7 @@
663661 "dir" | "object" | "repo" | "board" | "collection"
664662 ) {
665663 return Err(ApiError::bad_request(
666 "visibility overwrites are stored on directory nodes only".to_string(),
664 "visibility overwrites are stored on directory nodes only",
667665 ));
668666 }
669667 let db = state.space.db();