feat(公司tab): 店铺管理与数据权限分组按成员集筛, 凭据按 id 补读闸门
Task 11: ShopManageController.page / listGroups 接 DataReadScope.readScope, 把 company_id 算出的成员集当参数传给 service(controller 层收口, service 手上 只有 operatorId+布尔); ShopManageGroupService.list 增加 companyMemberIds 腿。 凭据 getCredentialById 的闸门用与 page() 同形的尺子(created_by_id IN creators OR group_id IN groups),不是账号集合 —— 后者表达不了分组那一腿, 会把列表看得见 的行读凭据时 403 掉, 那是把正当访问静默删掉。 新增 testutil/SourceScan 供源码扫描式护栏取文(找不到方法必须抛, 不许返回空串恒绿)。 前端两页接 tab: companyId 取 companyTab.requestCompanyId, 并 watch activeId 重载; G1 登记表给 admin_shop_manage 钉两条发送点(白名单 builder 故意不收 companyId)。 写侧入口一律不收 company_id, 由 ShopManageServiceTest 逐方法反向钉住。
This commit is contained in:
+25
-17
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
|
||||
@@ -35,6 +36,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@@ -45,6 +48,7 @@ public class ShopManageController {
|
||||
private final ShopManageService shopManageService;
|
||||
private final ShopManageGroupService shopManageGroupService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
/** 解析当前操作者(JWT 或内部令牌通道),数据范围一律以该身份为准,不信任调用方传入的 operatorId/superAdmin。 */
|
||||
private AdminUserEntity requireOperator(HttpServletRequest request) {
|
||||
@@ -56,7 +60,8 @@ public class ShopManageController {
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选")
|
||||
@Operation(summary = "分页查询店铺", description = "支持按分组、店铺名、当前操作者可见范围筛选;"
|
||||
+ "company_id 只收窄可见集、不放大,跨公司查看仅超管")
|
||||
@ApiResponses({
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(
|
||||
responseCode = "200",
|
||||
@@ -68,15 +73,16 @@ public class ShopManageController {
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId,
|
||||
@Parameter(description = "店铺名称") @RequestParam(required = false) String shopName) {
|
||||
@Parameter(description = "店铺名称") @RequestParam(required = false) String shopName,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireOperator(request);
|
||||
return ApiResponse.success(shopManageService.page(
|
||||
page,
|
||||
pageSize,
|
||||
groupId,
|
||||
shopName,
|
||||
operator.getId(),
|
||||
isSuper(operator)));
|
||||
Long operatorId = operator.getId();
|
||||
boolean superAdmin = isSuper(operator);
|
||||
// 公司 tab 只对超管收窄:非超管的可见集里含「靠分组可见」的行,而分组行没有账号列可推公司,
|
||||
// 给它叠 created_by_id IN (成员) 会把那批行从每一个 tab 里静默删掉(不报错、不 403)。
|
||||
List<Long> memberIds = superAdmin ? dataReadScope.readScope(operator, companyId).userIdsOr(null) : null;
|
||||
ShopManagePageVo vo = shopManageService.page(page, pageSize, groupId, shopName, operatorId, superAdmin, memberIds);
|
||||
return ApiResponse.success(vo);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@@ -111,15 +117,19 @@ public class ShopManageController {
|
||||
}
|
||||
|
||||
@GetMapping("/groups")
|
||||
@Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部")
|
||||
@Operation(summary = "查询分组列表", description = "普通管理员返回当前可访问的分组,超级管理员返回全部;"
|
||||
+ "company_id 只收窄可见集、不放大,跨公司查看仅超管")
|
||||
public ApiResponse<java.util.List<ShopManageGroupItemVo>> listGroups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById) {
|
||||
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireOperator(request);
|
||||
if (isSuper(operator)) {
|
||||
return ApiResponse.success(shopManageGroupService.list(createdById));
|
||||
List<Long> memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null);
|
||||
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds));
|
||||
}
|
||||
return ApiResponse.success(shopManageGroupService.listAccessible(operator.getId(), false));
|
||||
Long operatorId = operator.getId();
|
||||
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false));
|
||||
}
|
||||
|
||||
@PostMapping("/groups")
|
||||
@@ -175,10 +185,8 @@ public class ShopManageController {
|
||||
public ApiResponse<ShopManageCredentialVo> adminCredential(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "店铺主键 ID") @PathVariable Long id) {
|
||||
requireOperator(request);
|
||||
// 2026-09 修复:此前忽略路径 id、改用请求参数 shop_name 查询,
|
||||
// 会出现「路径声明的店铺」与「实际读取凭据的店铺」不一致
|
||||
return ApiResponse.success(shopManageService.getCredentialById(id));
|
||||
AdminUserEntity operator = requireOperator(request);
|
||||
return ApiResponse.success(shopManageService.getCredentialById(id, operator.getId(), isSuper(operator)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+22
-5
@@ -45,14 +45,31 @@ public class ShopManageGroupService {
|
||||
private final AdminUserMapper adminUserMapper;
|
||||
|
||||
public List<ShopManageGroupItemVo> list() {
|
||||
return list(null);
|
||||
return list(null, null);
|
||||
}
|
||||
|
||||
public List<ShopManageGroupItemVo> list(Long createdById) {
|
||||
return toVoList(groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.eq(createdById != null && createdById > 0, ShopManageGroupEntity::getCreatedById, createdById)
|
||||
.or(createdById != null && createdById > 0, wrapper -> wrapper.eq(ShopManageGroupEntity::getUserId, createdById))
|
||||
.orderByAsc(ShopManageGroupEntity::getId)));
|
||||
return list(createdById, null);
|
||||
}
|
||||
|
||||
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds) {
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.orderByAsc(ShopManageGroupEntity::getId);
|
||||
if (createdById != null && createdById > 0) {
|
||||
// 这两条原本是平铺的 .eq(...).or(...):MP 的 normal 段按顺序拼 AND/OR,MySQL 里 AND 优先,
|
||||
// 外面再叠一条公司条件时 created_by_id = ? 那半边会整块逃出筛选(多放行、不报错)⇒ 必须收进 and()。
|
||||
qw.and(w -> w.eq(ShopManageGroupEntity::getCreatedById, createdById)
|
||||
.or(x -> x.eq(ShopManageGroupEntity::getUserId, createdById)));
|
||||
}
|
||||
if (companyMemberIds != null) {
|
||||
if (companyMemberIds.isEmpty()) {
|
||||
qw.eq(ShopManageGroupEntity::getId, -1L);
|
||||
} else {
|
||||
// 公司条件同样自成一组(G2 护栏钉的是 AND (…) 这个形状;平铺 IN 与它在语义上等价)。
|
||||
qw.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds));
|
||||
}
|
||||
}
|
||||
return toVoList(groupMapper.selectList(qw));
|
||||
}
|
||||
|
||||
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin) {
|
||||
|
||||
+25
-2
@@ -28,7 +28,8 @@ public class ShopManageService {
|
||||
private final ShopCredentialCryptoService shopCredentialCryptoService;
|
||||
private final ZiniaoShopIndexRefreshTrigger ziniaoShopIndexRefreshTrigger;
|
||||
|
||||
public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId, boolean superAdmin) {
|
||||
public ShopManagePageVo page(long page, long pageSize, Long groupId, String shopName, Long operatorId,
|
||||
boolean superAdmin, List<Long> companyMemberIds) {
|
||||
long safePage = Math.max(page, 1);
|
||||
long safePageSize = Math.min(Math.max(pageSize, 1), 100);
|
||||
String safeShopName = shopName == null ? "" : shopName.trim();
|
||||
@@ -60,6 +61,16 @@ public class ShopManageService {
|
||||
}
|
||||
}
|
||||
|
||||
// companyMemberIds 由 controller 算好传进来(service 手上只有 operatorId + 一个布尔,
|
||||
// 而 readScope 要 AdminUserEntity)。null = 不筛,与"超管没选公司"的今天逐字一致。
|
||||
if (companyMemberIds != null) {
|
||||
if (companyMemberIds.isEmpty()) {
|
||||
query.eq(ShopManageEntity::getId, -1L);
|
||||
} else {
|
||||
query.in(ShopManageEntity::getCreatedById, companyMemberIds);
|
||||
}
|
||||
}
|
||||
|
||||
Long total = shopManageMapper.selectCount(query);
|
||||
List<ShopManageEntity> rows = shopManageMapper
|
||||
.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));
|
||||
@@ -152,7 +163,7 @@ public class ShopManageService {
|
||||
* <p>管理端 {@code GET /{id}/credential} 此前忽略路径里的 id、改用 shop_name 查询——
|
||||
* 路径声明的对象与实际读取的对象可能不一致(同名的第一条被读写,审计日志却记成另一个 id)。
|
||||
*/
|
||||
public ShopManageCredentialVo getCredentialById(Long id) {
|
||||
public ShopManageCredentialVo getCredentialById(Long id, Long operatorId, boolean superAdmin) {
|
||||
if (id == null || id <= 0) {
|
||||
throw new BusinessException("店铺 ID 不合法");
|
||||
}
|
||||
@@ -160,6 +171,18 @@ public class ShopManageService {
|
||||
if (entity == null) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
// 尺子必须与 page() 那一条同形:created_by_id IN creators OR group_id IN groups。
|
||||
// 账号集合表达不了分组那一腿(店铺建在我可访问的分组里、创建人却不在我的账号集),
|
||||
// 拿它当闸门会把列表看得见的行读凭据时 403 掉——那是把正当访问静默删掉。
|
||||
if (!superAdmin) {
|
||||
Set<Long> creators = shopManageGroupService.listAccessibleCreatorUserIds(operatorId, false);
|
||||
Set<Long> groups = shopManageGroupService.listAccessibleGroupIds(operatorId, false);
|
||||
boolean visible = (entity.getCreatedById() != null && creators.contains(entity.getCreatedById()))
|
||||
|| (entity.getGroupId() != null && groups.contains(entity.getGroupId()));
|
||||
if (!visible) {
|
||||
throw new BusinessException(403, "无权查看该店铺的凭据");
|
||||
}
|
||||
}
|
||||
return toCredentialVo(entity);
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.controller;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageCredentialVo;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
@@ -30,10 +31,11 @@ class ShopManageCredentialAuthTest {
|
||||
private final ShopManageService shopManageService = mock(ShopManageService.class);
|
||||
private final ShopManageGroupService shopManageGroupService = mock(ShopManageGroupService.class);
|
||||
private final AdminAuthSupport adminAuthSupport = mock(AdminAuthSupport.class);
|
||||
private final DataReadScope dataReadScope = mock(DataReadScope.class);
|
||||
private final HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
|
||||
private ShopManageController newController() {
|
||||
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport);
|
||||
return new ShopManageController(shopManageService, shopManageGroupService, adminAuthSupport, dataReadScope);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+94
@@ -1,19 +1,35 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity;
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -29,6 +45,15 @@ class ShopManageServiceTest {
|
||||
@InjectMocks
|
||||
private ShopManageService service;
|
||||
|
||||
/** getSqlSegment() 解析 lambda 靠 TableInfo 缓存,单测没有 Spring 容器去建它,不初始化就抛 "can not find lambda cache"。 */
|
||||
@BeforeEach
|
||||
void initTableInfo() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageEntity.class);
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requireShopByNameReturnsManagedShop() {
|
||||
ShopManageEntity entity = new ShopManageEntity();
|
||||
@@ -47,4 +72,73 @@ class ShopManageServiceTest {
|
||||
|
||||
assertEquals("后台店铺管理中未找到店铺:缺失店铺,请先添加店铺信息", exception.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("读:超管选了公司 ⇒ created_by_id 落进成员集;非超管不叠这一条")
|
||||
void superAdminPageNarrowsToCompanyMembers() {
|
||||
when(shopManageMapper.selectCount(any())).thenReturn(1L);
|
||||
when(shopManageMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.page(1L, 15L, null, null, 1L, true, List.of(11L, 12L));
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<ShopManageEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(shopManageMapper).selectCount(captor.capture());
|
||||
// 值在 paramNameValuePairs 里,segment 里只有 MPGENVAL 占位 ⇒ 结构从 segment 读、值从 pairs 读。
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("created_by_id").contains("IN (");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(11L, 12L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:非超管读「创建人不认识、分组也不认识」的行 ⇒ 403(§6.1 列表筛了按 id 照读)")
|
||||
void credentialByIdRejectsRowOutsideBothVisibleSets() {
|
||||
when(shopManageMapper.selectById(77L)).thenReturn(shop(77L, 999L, 7L));
|
||||
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L, 12L));
|
||||
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of());
|
||||
|
||||
assertThatThrownBy(() -> service.getCredentialById(77L, 2L, false))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasFieldOrPropertyWithValue("code", 403);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:店铺建在可访问分组里、创建人却不在我的账号集 ⇒ 必须 200(闸门用列表那把尺子,不是账号集合)")
|
||||
void credentialByIdKeepsGroupVisibleRowsReadable() {
|
||||
when(shopManageMapper.selectById(78L)).thenReturn(shop(78L, 999L, 5L));
|
||||
when(shopManageGroupService.listAccessibleCreatorUserIds(2L, false)).thenReturn(Set.of(11L));
|
||||
when(shopManageGroupService.listAccessibleGroupIds(2L, false)).thenReturn(Set.of(5L));
|
||||
|
||||
// 这一支是防误伤的正样本:把它删掉,下一轮"改成按账号集合卡"就没有任何尺子看得见。
|
||||
assertThatCode(() -> service.getCredentialById(78L, 2L, false)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("凭据:超管不查可见集(今天不筛、tab 也不是安全边界;短路写了就红在 NPE 上)")
|
||||
void credentialByIdStaysUnfilteredForSuperAdmin() {
|
||||
when(shopManageMapper.selectById(79L)).thenReturn(shop(79L, 999L, 7L));
|
||||
|
||||
assertThatCode(() -> service.getCredentialById(79L, 1L, true)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
private static ShopManageEntity shop(long id, Long createdById, Long groupId) {
|
||||
ShopManageEntity entity = new ShopManageEntity();
|
||||
entity.setId(id);
|
||||
entity.setCreatedById(createdById);
|
||||
entity.setGroupId(groupId);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("写:店铺与分组的写入口一律不收 company_id——归属不从界面注入(§6.2,未批的界面暴露)")
|
||||
void writeEntryPointsCarryNoCompanyId() {
|
||||
String text = SourceScan.sourceText("ShopManageController.java");
|
||||
// 必须逐方法体判:page 这个读入口这轮就要加 company_id,全文 doesNotContain 会被自己弄红。
|
||||
for (String writer : List.of("create", "update", "delete", "createGroup", "updateGroup", "deleteGroup")) {
|
||||
assertThat(SourceScan.methodBody(text, writer))
|
||||
.as("写入口「" + writer + "」一旦出现 company_id,等于把公司维度端回界面(未批)")
|
||||
.doesNotContain("company_id")
|
||||
.doesNotContain("companyId");
|
||||
}
|
||||
assertThat(SourceScan.methodBody(text, "page")).contains("company_id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.nanri.aiimage.testutil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** 源码扫描式护栏的取文助手。<b>路径解析照抄 {@code common/security/InternalTokenSingleOutletTest} 的
|
||||
* moduleRoot()/mainSources() 两支</b>——surefire 的 cwd 是模块目录,从仓库根或 IDE 跑时要退到 backend-java/,
|
||||
* 定位不到必须 fail 而不是静默跳过(静默跳过 = 整支护栏恒绿)。 */
|
||||
public final class SourceScan {
|
||||
|
||||
private SourceScan() {
|
||||
}
|
||||
|
||||
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
|
||||
* ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事,
|
||||
* 别指望复用它的——那个是 private。 */
|
||||
public static String sourceText(String fileName) {
|
||||
return mainSources().stream()
|
||||
.filter(p -> p.getFileName().toString().equals(fileName))
|
||||
.findFirst()
|
||||
.map(SourceScan::read)
|
||||
.orElseThrow(() -> new IllegalStateException(
|
||||
"src/main/java 下找不到 " + fileName + " —— 文件改名/挪目录了,护栏要红在这里"));
|
||||
}
|
||||
|
||||
/** 大括号配平切出「某个方法」的源码:<b>从它的签名行往前一直含到注解</b>,到方法收尾的 `}` 为止。
|
||||
*
|
||||
* <p>两条它必须自己防住的坑,都写在用例里过:</p>
|
||||
* <ul>
|
||||
* <li><b>名字必须是完整词</b>:{@code delete} 是 {@code deleteGroup} 的前缀。用 {@code indexOf(name)}
|
||||
* 会先撞上那个更长的方法 ⇒ "切出来的是隔壁",而断言仍然绿。所以下面用 {@code (?<![A-Za-z0-9_])} 卡左边界,
|
||||
* 并且要求紧跟 {@code (}(构造器/局部变量名同前缀也不算方法)。</li>
|
||||
* <li><b>找不到必须抛</b>,不许返回空串:返回 "" 的话 {@code doesNotContain("company_id")} 恒真,
|
||||
* 反向钉会因为方法被改名而悄悄失效(memory「字符串断言必须排他、解析断言必须可匹配」)。
|
||||
* 配套要求:每个用它的反向钉都要带一条"该做的确实做了"的取样自检。</li>
|
||||
* </ul>
|
||||
*/
|
||||
public static String methodBody(String source, String methodName) {
|
||||
var matcher = java.util.regex.Pattern
|
||||
.compile("(?<![A-Za-z0-9_])" + java.util.regex.Pattern.quote(methodName) + "\\s*\\(")
|
||||
.matcher(source);
|
||||
while (matcher.find()) {
|
||||
int open = matcher.end() - 1;
|
||||
int signatureStart = findSignatureStart(source, matcher.start());
|
||||
int bodyEnd = matchBraces(source, nextBrace(source, open));
|
||||
if (bodyEnd < 0) {
|
||||
continue;
|
||||
}
|
||||
return source.substring(signatureStart, bodyEnd + 1);
|
||||
}
|
||||
throw new AssertionError("源码里没有方法「" + methodName + "」——它被改名或删掉了。"
|
||||
+ "反向钉宁可红在这里,也不许因为切不到方法而恒绿。");
|
||||
}
|
||||
|
||||
/** 从签名的左括号往前退到上一条 `{`/`}`/`;` 之后,再退回到第一行注解的起始(注解属于这个方法,必须含进来)。 */
|
||||
private static int findSignatureStart(String source, int nameStart) {
|
||||
int boundary = 0;
|
||||
for (int i = nameStart; i-- > 0; ) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '{' || c == '}' || c == ';') {
|
||||
boundary = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
String head = source.substring(boundary, nameStart);
|
||||
int firstMeaningful = head.length();
|
||||
for (String raw : head.split("\n", -1)) {
|
||||
if (!raw.isBlank()) {
|
||||
firstMeaningful = head.indexOf(raw.stripLeading());
|
||||
break;
|
||||
}
|
||||
}
|
||||
return boundary + firstMeaningful;
|
||||
}
|
||||
|
||||
private static int nextBrace(String source, int from) {
|
||||
for (int i = from; i < source.length(); i++) {
|
||||
if (source.charAt(i) == '{') {
|
||||
return i;
|
||||
}
|
||||
if (source.charAt(i) == ';') {
|
||||
return -1; // 抽象方法/接口声明,不是我们要切的东西
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** 朴素配平:源码里的 `{` 与 `}` 若出现在字符串字面量里会算错。本仓库 controller 没有这种写法,
|
||||
* 但这条限制必须写在脸上——将来有人往方法体里塞一段带花括号的字符串,这个助手会悄悄切短。 */
|
||||
private static int matchBraces(String source, int open) {
|
||||
if (open < 0) {
|
||||
return -1;
|
||||
}
|
||||
int depth = 0;
|
||||
for (int i = open; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '{') {
|
||||
depth++;
|
||||
} else if (c == '}') {
|
||||
if (--depth == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
// 定位不到必须抛,不许静默返回空表:返回空 ⇒ sourceText 那支护栏扫不到任何文件而恒绿。
|
||||
throw new IllegalStateException("遍历 " + root + " 失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here;
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested;
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
|
||||
private static String read(Path file) {
|
||||
try {
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读取失败: " + file, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user