Skip to content

fix: Fix fail to get device info#162

Merged
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
wangrong1069:pr0729
Jul 29, 2025
Merged

fix: Fix fail to get device info#162
deepin-bot[bot] merged 1 commit intolinuxdeepin:masterfrom
wangrong1069:pr0729

Conversation

@wangrong1069
Copy link
Contributor

@wangrong1069 wangrong1069 commented Jul 29, 2025

  • Refactor command execution code to use a unified API with separated program name and parameter list.
  • Update .gitignore to include additional files and directories.
  • Remove unused watcher class and related code to streamline the service.

Log: Fix fail to get device info
Bug: https://pms.uniontech.com/bug-view-303363.html

Summary by Sourcery

Refactor shell command execution to use a unified Utils::executCmd API with argument parsing and error handling; replace direct QProcess calls throughout the service and application, add detailed logging, remove the unused Watcher component, and update .gitignore.

Enhancements:

  • Introduce parseCombinedArgString and extend Utils::executCmd to split commands into program and arguments and capture stderr
  • Replace direct QProcess usage in DeviceStorage, PartedCore, WorkThread, FixThread, and application code with Utils::executCmd and add error checks
  • Enhance debug logging in PartedCore::getDeviceHardInfo and command error cases
  • Simplify dbus-send invocations by passing program and argument list to startDetached

Build:

  • Update .gitignore to include additional files and directories

Chores:

  • Remove unused Watcher class and related code in service

- Refactor command execution code to use a unified API with separated program name and parameter list.
- Update .gitignore to include additional files and directories.
- Remove unused watcher class and related code to streamline the service.

Log: Fix fail to get device info
Bug: https://pms.uniontech.com/bug-view-303363.html
@github-actions
Copy link

TAG Bot

TAG: 6.0.10
EXISTED: no
DISTRIBUTION: unstable

@deepin-ci-robot
Copy link

deepin pr auto review

代码审查意见:

  1. .gitignore 文件新增了 .vscode 目录的忽略规则,这是一个好的实践,可以帮助避免将 IDE 的配置文件提交到版本控制中。

  2. main.cpp 文件中,executCmd 函数的修改提高了代码的健壮性,通过检查 args 是否为空来避免潜在的空指针异常。

  3. main.cpp 文件中,executCmd 函数的修改也提高了代码的可读性,通过将命令行参数解析和执行分离,使得代码更加清晰。

  4. mainwindow.cpputils.cpp 文件中,executCmd 函数的修改与 main.cpp 文件中的修改类似,提高了代码的健壮性和可读性。

  5. basestruct/utils.cpp 文件中新增的 parseCombinedArgString 函数是一个好的实践,它处理了命令行参数中的引号问题,使得函数能够正确解析包含空格和引号的命令行参数。

  6. service/diskoperation/DeviceStorage.cpp 文件中,executCmd 函数的修改提高了代码的健壮性,通过检查 Utils::executCmd 的返回值来处理命令执行失败的情况。

  7. service/diskoperation/partedcore.cpp 文件中,executCmd 函数的修改与 DeviceStorage.cpp 文件中的修改类似,提高了代码的健壮性。

  8. service/diskoperation/thread.cpp 文件中,executCmd 函数的修改与 DeviceStorage.cpp 文件中的修改类似,提高了代码的健壮性。

  9. service/main.cpp 文件中删除了 Watcher 类的引用和实现,这是一个好的实践,因为它简化了代码并移除了不再需要的功能。

  10. service/watcher.cppservice/watcher.h 文件被删除,这是一个好的实践,因为它移除了不再需要的代码,并保持了代码的整洁。

总体来说,这些修改提高了代码的健壮性、可读性和可维护性,是一个积极的改进。

@sourcery-ai
Copy link

sourcery-ai bot commented Jul 29, 2025

Reviewer's Guide

Refactors external process handling to use a unified Utils API with error handling and argument parsing, removes unused Watcher code, updates D-Bus invocations, enhances logging and safety checks, and updates .gitignore.

Sequence diagram for unified external command execution via Utils::executCmd

sequenceDiagram
    participant Caller
    participant Utils
    participant QProcess
    Caller->>Utils: executCmd(strCmd, outPut, error)
    Utils->>Utils: parseCombinedArgString(strCmd)
    Utils->>QProcess: start(prog, args)
    QProcess-->>Utils: process output/error
    Utils-->>Caller: exit code, outPut, error
Loading

Sequence diagram for MainWindow closing and D-Bus quit signal

sequenceDiagram
    actor User
    participant MainWindow
    participant QProcess
    User->>MainWindow: closeEvent()
    MainWindow->>QProcess: startDetached("/usr/bin/dbus-send", argList)
    QProcess-->>MainWindow: (detached)
    MainWindow-->>User: window closes
Loading

Sequence diagram for PartedCore device info retrieval with error handling

sequenceDiagram
    participant PartedCore
    participant Utils
    participant QProcess
    PartedCore->>Utils: executCmd(cmd, outPut, error)
    Utils->>QProcess: start(prog, args)
    QProcess-->>Utils: process output/error
    Utils-->>PartedCore: exit code, outPut, error
    alt exit code != 0
        PartedCore->>PartedCore: log error, return early
    else exit code == 0
        PartedCore->>PartedCore: process output
    end
Loading

ER diagram for removal of Watcher entity

erDiagram
    WATCHER ||--o{ DISKMANAGERSERVICE : monitored_by
    %% The WATCHER entity and its relationships have been removed.
Loading

Class diagram for updated Utils process execution API

classDiagram
    class Utils {
        +static int executCmd(const QString &strCmd, QString &outPut, QString &error)
        +static int executCmd(const QString &strCmd)
        +static int executeCmdWithArtList(const QString &strCmd, const QStringList &strArgList, QString &outPut, QString &error)
        +static int executWithInputOutputCmd(const QString &strCmdArg, const QString *inPut, QString &outPut, QString &error)
        +static QString readContent(const QString &filename)
        +static QString findProgramInPath(const QString &proName)
    }

    Utils : +static QStringList parseCombinedArgString(const QString &program)
Loading

Class diagram for removed Watcher class

classDiagram
    class Watcher {
        +void start()
        +void exit()
    }
    %% Watcher class and its methods have been removed from the codebase.
Loading

File-Level Changes

Change Details Files
Unified external command execution via Utils::executCmd
  • Replaced raw QProcess start/wait calls with Utils::executCmd
  • Captured and logged stderr via error string parameter
  • Handled non-zero exit codes to return failure
  • Removed QProcess variables and direct output reads
  • Updated D-Bus startDetached invocations to separate program and args
service/diskoperation/DeviceStorage.cpp
service/diskoperation/partedcore.cpp
service/diskoperation/thread.cpp
application/main.cpp
application/widgets/mainwindow.cpp
service/main.cpp
Introduce robust argument parsing in Utils
  • Added parseCombinedArgString to split quoted args
  • Refactored executCmd and executWithInputOutputCmd to use parsed args
  • Removed legacy QProcess-based command code and deprecated overload
basestruct/utils.cpp
Remove unused Watcher class and references
  • Deleted watcher.cpp and watcher.h
  • Removed Watcher instantiation and comments in service main
service/watcher.cpp
service/watcher.h
service/main.cpp
Enhance detailed logging in PartedCore
  • Added qDebug outputs for each HardDiskInfo field
service/diskoperation/partedcore.cpp
Add safety check for device path parsing
  • Validated deviceList.size() before using its elements to avoid out-of-bounds
  • Logged and returned "UnKnow" on invalid input
service/diskoperation/DeviceStorage.cpp
Update .gitignore entries
  • Extended ignore rules to cover new files and directories
.gitignore

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

@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 @wangrong1069 - I've reviewed your changes - here's some feedback:

  • In main.cpp the custom executCmd still uses naive strCmd.split(" ") instead of the new parseCombinedArgString logic—consider unifying argument parsing across all executCmd uses for consistent quoted‐arg handling.
  • There’s a recurring pattern of calling Utils::executCmd then checking exit codes and logging errors in many methods—extracting that into a small wrapper helper would reduce boilerplate and improve maintainability.
  • The literal "UnKnow" return value in getDiskInfoMediaType looks like a typo and a magic string; consider using a constant or enum (e.g. "Unknown") to ensure consistency and avoid mistakes.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In main.cpp the custom executCmd still uses naive strCmd.split(" ") instead of the new parseCombinedArgString logic—consider unifying argument parsing across all executCmd uses for consistent quoted‐arg handling.
- There’s a recurring pattern of calling Utils::executCmd then checking exit codes and logging errors in many methods—extracting that into a small wrapper helper would reduce boilerplate and improve maintainability.
- The literal "UnKnow" return value in getDiskInfoMediaType looks like a typo and a magic string; consider using a constant or enum (e.g. "Unknown") to ensure consistency and avoid mistakes.

## Individual Comments

### Comment 1
<location> `service/diskoperation/DeviceStorage.cpp:666` </location>
<code_context>
-    QString outPut = proc.readAllStandardOutput().trimmed();
-    value = outPut;
+    QString rotational_file = QString("/sys/block/%1/queue/rotational").arg(device);
+    QString value = Utils::readContent(rotational_file).trimmed();

     if ("1" == value) {
</code_context>

<issue_to_address>
No error handling for readContent failures.

Explicitly check for file read errors to avoid ambiguity between an unreadable file and valid values.
</issue_to_address>

### Comment 2
<location> `service/diskoperation/partedcore.cpp:174` </location>
<code_context>
     }

-    // qDebug() << __FUNCTION__ << "Get Device Hard Info end";
+    qDebug() << "Get device hard info for " << devicepath;
+    qDebug() << "Model: " << hdinfo.m_model;
+    qDebug() << "Vendor: " << hdinfo.m_vendor;
</code_context>

<issue_to_address>
Consider adding a toString() or QDebug operator<< to HardDiskInfo and replacing multiple qDebug() statements with a single call.

```cpp
// 1) Add a toString() (or QDebug operator<<) to HardDiskInfo:
class HardDiskInfo {
public:
    // ...
    QString toString() const {
        return QStringLiteral(
            "Model: %1, Vendor: %2, MediaType: %3, Size: %4, RotationRate: %5, "
            "Interface: %6, SerialNumber: %7, Version: %8, Capabilities: %9, "
            "Description: %10, PowerOnHours: %11, PowerCycleCount: %12, "
            "FirmwareVersion: %13, Speed: %14")
            .arg(m_model, m_vendor, m_mediaType, m_size, m_rotationRate,
                 m_interface, m_serialNumber, m_version, m_capabilities,
                 m_description, QString::number(m_powerOnHours),
                 QString::number(m_powerCycleCount),
                 m_firmwareVersion, m_speed);
    }
};

// (Optional) If you prefer streaming directly to QDebug:
inline QDebug operator<<(QDebug dbg, const HardDiskInfo &info) {
    dbg.nospace() << info.toString();
    return dbg.space();
}

// 2) Replace the 15+ qDebug() calls in getDeviceHardInfo with a single line:
HardDiskInfo PartedCore::getDeviceHardInfo(const QString &devicepath) {
    // ... populate hdinfo ...
    qDebug() << "GetDeviceHardInfo for" << devicepath << ":" << hdinfo;
    return hdinfo;
}
```
</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.

qDebug() << "value is 1";
cmd = QString("smartctl -i %1").arg(devicePath);
proc.start(cmd);
proc.waitForFinished(-1);
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): No error handling for readContent failures.

Explicitly check for file read errors to avoid ambiguity between an unreadable file and valid values.

}

// qDebug() << __FUNCTION__ << "Get Device Hard Info end";
qDebug() << "Get device hard info for " << devicepath;
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider adding a toString() or QDebug operator<< to HardDiskInfo and replacing multiple qDebug() statements with a single call.

// 1) Add a toString() (or QDebug operator<<) to HardDiskInfo:
class HardDiskInfo {
public:
    // ...
    QString toString() const {
        return QStringLiteral(
            "Model: %1, Vendor: %2, MediaType: %3, Size: %4, RotationRate: %5, "
            "Interface: %6, SerialNumber: %7, Version: %8, Capabilities: %9, "
            "Description: %10, PowerOnHours: %11, PowerCycleCount: %12, "
            "FirmwareVersion: %13, Speed: %14")
            .arg(m_model, m_vendor, m_mediaType, m_size, m_rotationRate,
                 m_interface, m_serialNumber, m_version, m_capabilities,
                 m_description, QString::number(m_powerOnHours),
                 QString::number(m_powerCycleCount),
                 m_firmwareVersion, m_speed);
    }
};

// (Optional) If you prefer streaming directly to QDebug:
inline QDebug operator<<(QDebug dbg, const HardDiskInfo &info) {
    dbg.nospace() << info.toString();
    return dbg.space();
}

// 2) Replace the 15+ qDebug() calls in getDeviceHardInfo with a single line:
HardDiskInfo PartedCore::getDeviceHardInfo(const QString &devicepath) {
    // ... populate hdinfo ...
    qDebug() << "GetDeviceHardInfo for" << devicepath << ":" << hdinfo;
    return hdinfo;
}

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: lzwind, wangrong1069

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

@wangrong1069
Copy link
Contributor Author

/merge

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