Skip to content

feat: enhance filename index status handling and pinyin output - #408

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
Johnson-zs:Johnson-zs/master-anything
Oct 8, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:masterfrom
Johnson-zs:Johnson-zs/master-anything

Conversation

@Johnson-zs

@Johnson-zs Johnson-zs commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Extended filename search capabilities with improved index status
evaluation and pinyin metadata support. Updated index status handling to
better distinguish between scanning/monitoring states, ensuring search
reliability during various index operations. Added pinyin and pinyin
acronym fields to search results when available from the filename index.

Changes:

  1. Enhanced index status evaluation with new logic focusing on
    createInProgress and updateInProgress flags
  2. Renamed status.json to index_status.json and updated path to use
    QStandardPaths
  3. Added pinyin and pinyin acronym getters/setters to FileNameResultAPI
  4. Updated indexed strategy to extract pinyin data from Lucene documents
  5. Enhanced JSON and text output formats to include pinyin metadata
    when available
  6. Added comprehensive test cases for pinyin output and index status
    mapping

Log: Added pinyin metadata to search results and improved index status
reliability detection

Influence:

  1. Test search results with Chinese filenames to verify pinyin metadata
    appears in JSON/text output
  2. Verify pinyin fields only appear when detailed results are enabled
  3. Test that plain filename results without pinyin do not output empty
    pinyin keys
  4. Verify index status accurately reflects scanning vs monitoring states
    during index operations
  5. Test search behavior during index creation/recovery operations to
    ensure proper fallback
  6. Validate that index status unavailable warning appears when no local
    index exists

feat: 增强文件名索引状态处理和拼音输出

扩展了文件名搜索功能,改进了索引状态评估和拼音元数据支持。更新了索引状态
处理逻辑,更好地区分扫描/监控状态,确保在各种索引操作期间的搜索可靠性。
当文件名索引中可用时,搜索结果中添加拼音和拼音首字母字段。

变更内容:

  1. 增强索引状态评估逻辑,重点关注 createInProgress 和 updateInProgress
    标志
  2. 将 status.json 重命名为 index_status.json 并使用 QStandardPaths 更新
    路径
  3. 为 FileNameResultAPI 添加拼音和拼音首字母的getter/setter方法
  4. 更新索引策略以从Lucene文档中提取拼音数据
  5. 增强JSON和文本输出格式,当可用时包含拼音元数据
  6. 为拼音输出和索引状态映射添加全面的测试用例

Log: 在搜索结果中添加拼音元数据并改进索引状态可靠性检测

Influence:

  1. 测试包含中文文件名的搜索结果,验证拼音元数据是否出现在JSON/文本输出中
  2. 验证拼音字段仅在详细结果启用时出现
  3. 测试没有拼音的普通文件名结果不会输出空的拼音键
  4. 验证索引状态在索引操作期间准确反映扫描与监控状态
  5. 测试索引创建/恢复操作期间的搜索行为,确保正确的回退机制
  6. 验证当没有本地索引时会出现索引状态不可用警告

Summary by Sourcery

Improve filename index reliability and include available pinyin metadata in detailed search results.

New Features:

  • Expose filename-index pinyin and pinyin acronym metadata through the search result API and JSON/text outputs when available.

Bug Fixes:

  • Improve filename index readiness and status detection during creation, recovery, rebuilding, and event-backlog processing so searches fall back appropriately when the index is not trustworthy.

Enhancements:

  • Move filename index storage to the standard application data location and use index_status.json with updated status mappings for scanning, updating, and monitoring states.

Tests:

  • Add coverage for pinyin metadata output, omission of empty pinyin fields, and filename index status mapping across valid and invalid status data.

Extended filename search capabilities with improved index status
evaluation and pinyin metadata support. Updated index status handling to
better distinguish between scanning/monitoring states, ensuring search
reliability during various index operations. Added pinyin and pinyin
acronym fields to search results when available from the filename index.

Changes:
1. Enhanced index status evaluation with new logic focusing on
createInProgress and updateInProgress flags
2. Renamed status.json to index_status.json and updated path to use
QStandardPaths
3. Added pinyin and pinyin acronym getters/setters to FileNameResultAPI
4. Updated indexed strategy to extract pinyin data from Lucene documents
5. Enhanced JSON and text output formats to include pinyin metadata
when available
6. Added comprehensive test cases for pinyin output and index status
mapping

Log: Added pinyin metadata to search results and improved index status
reliability detection

Influence:
1. Test search results with Chinese filenames to verify pinyin metadata
appears in JSON/text output
2. Verify pinyin fields only appear when detailed results are enabled
3. Test that plain filename results without pinyin do not output empty
pinyin keys
4. Verify index status accurately reflects scanning vs monitoring states
during index operations
5. Test search behavior during index creation/recovery operations to
ensure proper fallback
6. Validate that index status unavailable warning appears when no local
index exists

feat: 增强文件名索引状态处理和拼音输出

扩展了文件名搜索功能,改进了索引状态评估和拼音元数据支持。更新了索引状态
处理逻辑,更好地区分扫描/监控状态,确保在各种索引操作期间的搜索可靠性。
当文件名索引中可用时,搜索结果中添加拼音和拼音首字母字段。

变更内容:
1. 增强索引状态评估逻辑,重点关注 createInProgress 和 updateInProgress
标志
2. 将 status.json 重命名为 index_status.json 并使用 QStandardPaths 更新
路径
3. 为 FileNameResultAPI 添加拼音和拼音首字母的getter/setter方法
4. 更新索引策略以从Lucene文档中提取拼音数据
5. 增强JSON和文本输出格式,当可用时包含拼音元数据
6. 为拼音输出和索引状态映射添加全面的测试用例

Log: 在搜索结果中添加拼音元数据并改进索引状态可靠性检测

Influence:
1. 测试包含中文文件名的搜索结果,验证拼音元数据是否出现在JSON/文本输出中
2. 验证拼音字段仅在详细结果启用时出现
3. 测试没有拼音的普通文件名结果不会输出空的拼音键
4. 验证索引状态在索引操作期间准确反映扫描与监控状态
5. 测试索引创建/恢复操作期间的搜索行为,确保正确的回退机制
6. 验证当没有本地索引时会出现索引状态不可用警告
@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Johnson-zs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR makes filename-index reliability decisions from the new persisted status schema, including safer fallback behavior during creation, recovery, and backlog processing, while carrying indexed pinyin metadata through the result API into detailed JSON and text output with focused tests.

Sequence diagram for filename search with index readiness and pinyin output

sequenceDiagram
    participant Client
    participant SearchUtility
    participant FilenameIndex
    participant Output

    Client->>SearchUtility: isFileNameIndexReadyForSearch()
    SearchUtility->>FilenameIndex: readFileNameIndexStatusFile()
    FilenameIndex-->>SearchUtility: index_status.json
    SearchUtility-->>Client: ready or fallback to realtime search
    Client->>FilenameIndex: processDetailedSearchResult()
    FilenameIndex-->>Client: SearchResult with pinyin and pinyinAcronym
    Client->>Output: resultToJson() or printSearchResult()
    Output-->>Client: detailed output with non-empty pinyin fields
Loading

State diagram for filename index status mapping

stateDiagram-v2
    [*] --> Unavailable
    Unavailable --> Scanning: invalid or missing status JSON
    StatusLoaded --> Scanning: createInProgress or updateInProgress
    StatusLoaded --> Updating: backlogExceeded
    StatusLoaded --> Monitoring: lastUpdateTime present and no blocking flags
    StatusLoaded --> Scanning: lastUpdateTime empty
    Monitoring --> Ready: index directory exists
    Scanning --> RealtimeFallback: index not trustworthy
    Updating --> RealtimeFallback: index severely lagged

    state StatusLoaded
    state Monitoring
    state Scanning
    state Updating
    state Unavailable
Loading

File-Level Changes

Change Details Files
Reworked filename-index status parsing and readiness decisions around persisted operation flags and completion metadata.
  • Read the renamed index_status.json from the QStandardPaths-based index directory.
  • Map create/update operations, backlog conditions, and missing completion timestamps to scanning, updating, or monitoring states.
  • Require a physically available index, a completed update timestamp, and no active degradation flags before indexed search is considered reliable.
  • Expose JSON-based mapping/readiness helpers and add coverage for valid, invalid, and overlapping status conditions.
include/dfm-search/dfm-search/dsearch_global.h
src/dfm-search/dfm-search-lib/utils/searchutility.cpp
src/dfm-search/dfm-search-lib/utils/searchutility.h
autotests/dfm-search-tests/tst_search_utils.cpp
Added pinyin metadata to filename search result data and populated it from indexed documents.
  • Added pinyin and pinyin-acronym accessors backed by SearchResult custom attributes.
  • Extracted both Lucene fields during detailed indexed filename searches.
include/dfm-search/dfm-search/filenamesearchapi.h
src/dfm-search/dfm-search-lib/filenamesearch/filenamesearchapi.cpp
src/dfm-search/dfm-search-lib/filenamesearch/filenamestrategies/indexedstrategy.cpp
Extended detailed search serialization to emit available pinyin metadata without adding empty fields.
  • Included pinyin and pinyinAcronym conditionally in JSON output.
  • Included labeled pinyin fields in verbose text output.
  • Added contracts for populated and plain filename results.
src/dfm-search/dfm-search-client/output/json_output.cpp
src/dfm-search/dfm-search-client/output/text_output.cpp
autotests/dfm-search-tests/tst_search_output.cpp

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/dfm-search/dfm-search-lib/utils/searchutility.cpp" line_range="762-764" />
<code_context>
-    }
+    const QJsonObject root = doc.object();
+    fields.parsed = true;
+    fields.createInProgress = root.value("createInProgress").toBool(false);
+    fields.updateInProgress = root.value("updateInProgress").toBool(false);
+    fields.backlogExceeded = root.value("backlogExceeded").toBool(false);
+    fields.lastUpdateTime = root.value("lastUpdateTime").toString();
+    return fields;
</code_context>
<issue_to_address>
**Malformed status trusts an updating index**

When a status JSON object has a non-boolean progress flag and a non-empty `lastUpdateTime`, `parseFileNameIndexStatusJson()` converts the malformed flag to `false` with `toBool(false)`, so `fileNameIndexReadyForSearchFromJson()` can authorize searches against an index whose status is untrustworthy. Callers can receive stale or incomplete results.

Validate the JSON types of the progress flags and `lastUpdateTime`, and reject the status object when any field has the wrong type.
</issue_to_address>

### Comment 2
<location path="src/dfm-search/dfm-search-lib/utils/searchutility.cpp" line_range="838-839" />
<code_context>
 QString fileNameIndexDirectory()
 {
-    return QString("/run/user/%1/deepin-anything-server").arg(getuid());
+    return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)
+        + "/deepin/dde-file-manager/filename-index";
 }

</code_context>
<issue_to_address>
**Existing filename indexes disappear**

When an installation or older producer still uses `/run/user/<uid>/deepin-anything-server` and the new directory has not been populated, `fileNameIndexDirectory()` and its readers look only in the new data location, so they miss the legacy index and status file. Indexed filename searches become unavailable or lose existing results, and semantic searches fall back to slower realtime traversal.

Migrate the legacy index and status file or keep a fallback that reads the legacy location until the new location is populated.

Also at `src/dfm-search/dfm-search-lib/utils/searchutility.cpp:840`.
</issue_to_address>

### Comment 3
<location path="src/dfm-search/dfm-search-lib/utils/searchutility.cpp" line_range="828-830" />
<code_context>
+
+std::optional<QString> fileNameIndexStatusFromJson(const QByteArray &jsonContent)
 {
-    if (!isFileNameIndexDirectoryAvailable()) {
-        qWarning() << "Index directory not available";
+    const FileNameIndexStatusFields fields = parseFileNameIndexStatusJson(jsonContent);
+    if (!fields.parsed)
         return std::nullopt;
-    }

</code_context>
<issue_to_address>
**In-progress status appears unavailable**

When the status JSON reports creation or an update before Lucene has a committed index, `fileNameIndexStatus()` checks index availability before reading the status file, so it returns `nullopt` even when the file reports an in-progress state. Callers see status unavailable instead of `scanning`.

Read and map the status file before requiring a readable Lucene index.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +762 to +764
fields.createInProgress = root.value("createInProgress").toBool(false);
fields.updateInProgress = root.value("updateInProgress").toBool(false);
fields.backlogExceeded = root.value("backlogExceeded").toBool(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Malformed status trusts an updating index

When a status JSON object has a non-boolean progress flag and a non-empty lastUpdateTime, parseFileNameIndexStatusJson() converts the malformed flag to false with toBool(false), so fileNameIndexReadyForSearchFromJson() can authorize searches against an index whose status is untrustworthy. Callers can receive stale or incomplete results.

Validate the JSON types of the progress flags and lastUpdateTime, and reject the status object when any field has the wrong type.

Prompt for AI agents
In `src/dfm-search/dfm-search-lib/utils/searchutility.cpp` at lines 762-764:

**Malformed status trusts an updating index**

When a status JSON object has a non-boolean progress flag and a non-empty `lastUpdateTime`, `parseFileNameIndexStatusJson()` converts the malformed flag to `false` with `toBool(false)`, so `fileNameIndexReadyForSearchFromJson()` can authorize searches against an index whose status is untrustworthy. Callers can receive stale or incomplete results.

Validate the JSON types of the progress flags and `lastUpdateTime`, and reject the status object when any field has the wrong type.

Comment on lines +838 to +839
return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)
+ "/deepin/dde-file-manager/filename-index";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Existing filename indexes disappear

When an installation or older producer still uses /run/user/<uid>/deepin-anything-server and the new directory has not been populated, fileNameIndexDirectory() and its readers look only in the new data location, so they miss the legacy index and status file. Indexed filename searches become unavailable or lose existing results, and semantic searches fall back to slower realtime traversal.

Migrate the legacy index and status file or keep a fallback that reads the legacy location until the new location is populated.

Also at src/dfm-search/dfm-search-lib/utils/searchutility.cpp:840.

Prompt for AI agents
In `src/dfm-search/dfm-search-lib/utils/searchutility.cpp` at lines 838-839:

**Existing filename indexes disappear**

When an installation or older producer still uses `/run/user/<uid>/deepin-anything-server` and the new directory has not been populated, `fileNameIndexDirectory()` and its readers look only in the new data location, so they miss the legacy index and status file. Indexed filename searches become unavailable or lose existing results, and semantic searches fall back to slower realtime traversal.

Migrate the legacy index and status file or keep a fallback that reads the legacy location until the new location is populated.

Also at `src/dfm-search/dfm-search-lib/utils/searchutility.cpp:840`.

Comment on lines +828 to 830
if (!isFileNameIndexDirectoryAvailable()) {
qWarning() << "Index directory not available";
return std::nullopt;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · In-progress status appears unavailable

When the status JSON reports creation or an update before Lucene has a committed index, fileNameIndexStatus() checks index availability before reading the status file, so it returns nullopt even when the file reports an in-progress state. Callers see status unavailable instead of scanning.

Read and map the status file before requiring a readable Lucene index.

Prompt for AI agents
In `src/dfm-search/dfm-search-lib/utils/searchutility.cpp` at lines 828-830:

**In-progress status appears unavailable**

When the status JSON reports creation or an update before Lucene has a committed index, `fileNameIndexStatus()` checks index availability before reading the status file, so it returns `nullopt` even when the file reports an in-progress state. Callers see status unavailable instead of `scanning`.

Read and map the status file before requiring a readable Lucene index.

@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 96 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 代码变更增强文件名索引状态处理和拼音输出功能,结构清晰,注释完整,无安全漏洞。存在少量可维护性改进建议(诊断日志缺失、文件未显式关闭),但不影响功能正确性。

🔍 详细分析

1. 语法逻辑 ✅

评价: 优秀 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: 1.索引状态优先级逻辑(createInProgress > updateInProgress > backlogExceeded > state)设计合理,边界条件处理完善
2.测试用例覆盖全面,包含双标志同时置位、无效JSON、空内容等边缘场景


2. 代码质量 ✅

评价: 良好 ✅ 通过

潜在问题:

  1. src/dfm-search/dfm-search-lib/utils/searchutility.cpp:769-776 - 诊断日志丢失:readFileNameIndexStatusFile 函数在文件不存在或无法打开时静默返回空值,旧代码有详细的 qWarning() 日志输出。生产环境中无法通过日志诊断索引状态文件缺失原因。
  2. src/dfm-search/dfm-search-lib/utils/searchutility.cpp:755-758 - JSON 解析错误被静默吞没:parseFileNameIndexStatusJson 在 JSON 解析失败时未记录错误日志,旧代码记录了详细的解析错误信息。
  3. src/dfm-search/dfm-search-lib/utils/searchutility.cpp:773-775 - QFile 未显式关闭:readFileNameIndexStatusFile 中文件打开后未显式调用 close(),旧代码有明确的 statusFile.close() 调用。

建议: 1.parseFileNameIndexStatusJson 提取为共享辅助函数,有效避免代码重复
2.注释完整,详细解释了状态映射逻辑和优先级顺序
3.拼音 getter/setter 实现与现有模式一致,风格统一


3. 代码性能 ✅

评价: 优秀 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: 1.拼音数据提取使用 Lucene doc->get() 为 O(1) 查找,无性能影响
2.JSON/文本输出中拼音字段仅在非空时添加,避免不必要的字符串操作
3.QString 隐式共享机制下无不必要的内存拷贝


4. 代码安全 🔒

存在0个安全漏洞

评价: 优秀 ✅ 通过

🔐 发现 0 个安全漏洞
漏洞对比统计:新增漏洞 0 个,减少漏洞 0 个,持平 0 个

安全漏洞详情:
✅ 未发现安全漏洞

建议: 1.文件路径使用 QStandardPaths 系统标准路径,非用户输入,无路径遍历风险
2.JSON 解析使用 QJsonDocument 并有错误检查,无注入风险
3.拼音数据来源于 Lucene 索引文档,非用户直接输入
4.无硬编码密钥、敏感信息泄露或命令注入风险


💡 改进建议代码示例

// 修复建议:恢复诊断日志并显式关闭文件
QByteArray readFileNameIndexStatusFile()
{
    const QString &statusFilePath = QDir(fileNameIndexDirectory()).filePath("index_status.json");
    QFile statusFile(statusFilePath);
    if (!statusFile.exists()) {
        qWarning() << "Status file does not exist:" << statusFilePath;
        return {};
    }
    if (!statusFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open status file:" << statusFile.errorString();
        return {};
    }
    const QByteArray content = statusFile.readAll();
    statusFile.close();
    return content;
}

FileNameIndexStatusFields parseFileNameIndexStatusJson(const QByteArray &jsonContent)
{
    FileNameIndexStatusFields fields;

    QJsonParseError jsonError;
    const QJsonDocument doc = QJsonDocument::fromJson(jsonContent, &jsonError);
    if (jsonError.error != QJsonParseError::NoError || !doc.isObject()) {
        qWarning() << "Failed to parse index status JSON:" << jsonError.errorString();
        return fields;
    }
    // ... rest of parsing logic
}

本报告由 AI 代码审查工具自动生成

@Johnson-zs

Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot

deepin-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pr force merged! (status: blocked)

@deepin-bot
deepin-bot Bot merged commit 9ba362e into linuxdeepin:master Oct 8, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants