Skip to content

fix(data-transfer): improve file path handling in setting helper#722

Merged
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
pppanghu77:master
Apr 22, 2026
Merged

fix(data-transfer): improve file path handling in setting helper#722
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
pppanghu77:master

Conversation

@pppanghu77
Copy link
Copy Markdown
Contributor

@pppanghu77 pppanghu77 commented Apr 22, 2026

  • Extract only the filename part from the full path to support both relative and absolute path formats
  • Use QFileInfo to properly handle path separators across different platforms
  • Replace complex string manipulation with more robust file name extraction logic

Summary by Sourcery

Improve data transfer setting helper path handling and cleanup behavior.

Bug Fixes:

  • Handle JSON configuration path construction using QDir::filePath to avoid manual path concatenation issues with separators and formats.
  • Remove only the transfer.json file instead of recursively deleting the entire directory after processing.
  • Correct file name extraction in setFile to support both relative and absolute input paths using QFileInfo.

Enhancements:

  • Add SPDX copyright and license header to the setting helper implementation file.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 22, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Refines how data transfer settings resolve and clean up file paths by using Qt path utilities for platform-safe JSON file handling and more robust filename extraction, while also adding SPDX licensing headers.

Sequence diagram for updated handleDataConfiguration file handling

sequenceDiagram
    participant SettingHelper
    participant QDir
    participant ParseJson
    participant QFile
    participant Logger

    SettingHelper->>QDir: QDir(path)
    QDir-->>SettingHelper: absolutePath()
    SettingHelper->>QDir: QDir(filepath)
    QDir-->>SettingHelper: filePath(transfer.json)
    SettingHelper->>ParseJson: ParseJson(transfer_json_path)
    ParseJson-->>SettingHelper: QJsonObject jsonObj
    SettingHelper->>SettingHelper: validate jsonObj
    alt jsonObj is empty
        SettingHelper->>SettingHelper: addTaskcounter(-1)
        SettingHelper->>Logger: log transfer.json is invaild
        SettingHelper-->>SettingHelper: return false
    else jsonObj valid
        SettingHelper->>SettingHelper: process jsonObj
        SettingHelper->>SettingHelper: addTaskcounter(-1)
        SettingHelper->>QDir: QDir(filepath)
        QDir-->>SettingHelper: filePath(transfer.json)
        SettingHelper->>QFile: remove(jsonFile)
        alt remove fails
            SettingHelper->>Logger: log Failed to remove transfer.json
        end
        SettingHelper-->>SettingHelper: return true
    end
Loading

Updated class diagram for SettingHelper path handling methods

classDiagram
    class SettingHelper {
        +bool handleDataConfiguration(QString path)
        +bool setFile(QJsonObject jsonObj, QString filepath)
        -void addTaskcounter(int delta)
    }

    class QDir {
        +QDir(QString path)
        +QString absolutePath()
        +QString filePath(QString fileName)
        +bool exists()
    }

    class QFileInfo {
        +QFileInfo(QString file)
        +QString fileName()
        +QDir dir()
    }

    class QFile {
        +static bool remove(QString fileName)
    }

    class QJsonObject {
    }

    class QJsonArray {
    }

    class QFilePathUsage {
        +QString filepath
        +QString jsonFile
        +QString filename
        +QString file
        +QString targetFile
    }

    SettingHelper ..> QDir : uses
    SettingHelper ..> QFileInfo : uses
    SettingHelper ..> QFile : uses
    SettingHelper ..> QJsonObject : uses
    SettingHelper ..> QJsonArray : uses

    QFilePathUsage <.. SettingHelper : local variables

    %% setFile logic (conceptual structure)
    class SettingHelper {
        +bool setFile(QJsonObject jsonObj, QString filepath)
    }

    class SetFileLogic {
        +void iterateUserFileArray(QJsonArray userFileArray, QString filepath)
        +QString extractFileName(QString filename)
        +QString buildSourcePath(QString filepath, QString baseName)
        +QString buildTargetPath(QString homePath, QString filename)
        +bool ensureTargetDirExists(QFileInfo info)
    }

    SettingHelper ..> SetFileLogic : uses
    SetFileLogic ..> QFileInfo : uses
    SetFileLogic ..> QDir : uses
Loading

File-Level Changes

Change Details Files
Use QDir/QFile/QFileInfo-based path handling for transfer.json instead of manual string concatenation and directory deletion.
  • Build the transfer.json path using QDir(filePath).filePath("transfer.json") before parsing JSON, rather than concatenating with a trailing slash and filename.
  • Replace recursive removal of the entire path directory with targeted removal of transfer.json using QFile::remove, logging a warning on failure.
  • Retain creation of an absolute directory path via QDir(path) but avoid assuming directory structure semantics when cleaning up files.
src/lib/data-transfer/core/utils/settinghepler.cpp
Improve filename extraction when setting files to support both relative and absolute paths.
  • Extract only the filename portion from each entry using QFileInfo(value.toString()).fileName() to be robust against different path formats and separators.
  • Construct the source file path with filepath + extracted file name, instead of performing manual substring operations based on the first slash.
  • Keep target path resolution via QDir::homePath() + "/" + filename to preserve existing behavior for where files are written.
src/lib/data-transfer/core/utils/settinghepler.cpp
Add SPDX license header to the settings helper implementation file.
  • Insert SPDX-FileCopyrightText and SPDX-License-Identifier comments at the top of the implementation file.
src/lib/data-transfer/core/utils/settinghepler.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

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • When constructing file in setFile, concatenating filepath with QFileInfo(filename).fileName() may omit a path separator if filepath doesn’t end with one; consider using QDir(filepath).filePath(QFileInfo(filename).fileName()) instead of raw string concatenation.
  • In handleDataConfiguration, you now only delete transfer.json instead of removing the whole directory; if the intention is still to clean up temporary directories, consider whether additional directory removal is needed or explicitly documenting that only the JSON file is cleaned up.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- When constructing `file` in `setFile`, concatenating `filepath` with `QFileInfo(filename).fileName()` may omit a path separator if `filepath` doesn’t end with one; consider using `QDir(filepath).filePath(QFileInfo(filename).fileName())` instead of raw string concatenation.
- In `handleDataConfiguration`, you now only delete `transfer.json` instead of removing the whole directory; if the intention is still to clean up temporary directories, consider whether additional directory removal is needed or explicitly documenting that only the JSON file is cleaned up.

## Individual Comments

### Comment 1
<location path="src/lib/data-transfer/core/utils/settinghepler.cpp" line_range="78-81" />
<code_context>
     QDir pdir(path);
     QString filepath = pdir.absolutePath() + "/";
-    QJsonObject jsonObj = ParseJson(filepath + "transfer.json");
+    QJsonObject jsonObj = ParseJson(QDir(filepath).filePath("transfer.json"));
     if (jsonObj.isEmpty()) {
         addTaskcounter(-1);
</code_context>
<issue_to_address>
**suggestion:** Avoid mixing manual path concatenation with QDir, and consider using QDir consistently for `filepath` as well.

`filepath` is built with `pdir.absolutePath() + "/"` and then immediately re-wrapped in `QDir(filepath)` just to resolve `transfer.json`. This is redundant and can be simplified by using `pdir.filePath("transfer.json")` directly, which also avoids any trailing-slash handling.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/lib/data-transfer/core/utils/settinghepler.cpp Outdated
- Extract only the filename part from the full path to support both
  relative and absolute path formats
- Use QFileInfo to properly handle path separators across different
  platforms
- Replace complex string manipulation with more robust file name
  extraction logic
@deepin-ci-robot
Copy link
Copy Markdown

deepin pr auto review

这段代码的 diff 主要包含版权声明更新、路径处理优化以及文件删除逻辑的修改。以下是对代码的详细审查意见:


1. 版权声明(新增部分)

// SPDX-FileCopyrightText: 2023 - 2026 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later

改进意见:

  • 合规性:使用 SPDX 标识符声明版权和许可证,符合开源规范。
  • 可维护性:明确版权归属和许可证类型,便于后续维护。

2. 路径处理优化

修改前:

QString filepath = pdir.absolutePath() + "/";
QJsonObject jsonObj = ParseJson(filepath + "transfer.json");

修改后:

QJsonObject jsonObj = ParseJson(pdir.filePath("transfer.json"));

改进意见:

  • 可读性:使用 QDir::filePath() 替代字符串拼接,更符合 Qt 的风格。
  • 安全性:避免手动拼接路径,减少路径分隔符错误的风险(如 // 或缺少 /)。
  • 跨平台兼容性QDir::filePath() 会自动处理不同操作系统的路径分隔符。

3. 文件删除逻辑优化

修改前:

// remove dir
pdir.removeRecursively();

修改后:

// remove transfer.json
const QString jsonFile = pdir.filePath("transfer.json");
if (!QFile::remove(jsonFile))
    WLOG << "Failed to remove transfer.json: " << jsonFile.toStdString();

改进意见:

  • 逻辑更精确:原代码删除整个目录,而实际需求是仅删除 transfer.json,避免误删其他文件。
  • 错误处理:增加了删除失败的日志记录,便于调试。
  • ⚠️ 潜在问题:如果 transfer.json 所在目录为空,是否需要删除目录?如果需要,可以补充逻辑:
    if (QFile::remove(jsonFile)) {
        QDir dir = QFileInfo(jsonFile).dir();
        if (dir.isEmpty()) {
            dir.rmdir(dir.absolutePath());
        }
    }

4. 文件名处理优化

修改前:

QString targetFile = QDir::homePath() + "/" + filename;
QString file = filepath + filename.mid(filename.indexOf('/') + 1);

修改后:

// 只保留文件名部分,兼容相对路径和绝对路径格式
QString file = filepath + QFileInfo(filename).fileName();

改进意见:

  • 健壮性:使用 QFileInfo::fileName() 提取文件名,避免手动处理字符串(如 mid(filename.indexOf('/') + 1))。
  • 兼容性:支持相对路径和绝对路径格式,减少路径解析错误。
  • ⚠️ 潜在问题:如果 filename 是空字符串或无效路径,QFileInfo::fileName() 会返回空字符串,建议增加校验:
    if (filename.isEmpty()) {
        WLOG << "Filename is empty!";
        continue;
    }
    QString file = filepath + QFileInfo(filename).fileName();

5. 日志记录优化

修改前:

WLOG << "transfer.json is invaild";

修改后:

WLOG << "Failed to remove transfer.json: " << jsonFile.toStdString();

改进意见:

  • 信息更详细:日志中包含文件路径,便于定位问题。
  • ⚠️ 拼写修正:原日志中的 invaild 应改为 invalid(虽然未在 diff 中修改,建议一并修复)。

6. 其他建议

  1. 代码风格

    • 变量命名 jsonFilefile 可以更明确,例如 jsonFilePathsourceFilePath
    • 使用 const 修饰不变的变量(如 const QString jsonFile 已做到)。
  2. 性能优化

    • 如果 transfer.json 文件较大,可以考虑使用 QFile 直接读取并解析,而非依赖 ParseJson 的实现。
  3. 安全性

    • 如果 path 来自外部输入,建议增加路径合法性校验,防止路径遍历攻击(如 ../../../etc/passwd)。

总结

  • 优点:路径处理更安全,删除逻辑更精确,文件名解析更健壮。
  • ⚠️ 建议:补充路径校验、空文件名处理,并修复日志拼写错误。

改进后的代码整体质量较高,符合 Qt 的最佳实践。

@deepin-ci-robot
Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: pppanghu77, re2zero

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

@pppanghu77
Copy link
Copy Markdown
Contributor Author

/forcemerge

@deepin-bot
Copy link
Copy Markdown

deepin-bot Bot commented Apr 22, 2026

This pr force merged! (status: unstable)

@deepin-bot deepin-bot Bot merged commit 930da60 into linuxdeepin:master Apr 22, 2026
19 of 21 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.

3 participants