Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions backend/app/api/v1/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,11 +410,20 @@ func (b *BaseApi) CheckFile(c *gin.Context) {
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if _, err := os.Stat(req.Path); err != nil {
helper.SuccessWithData(c, false)
fileOp := files.NewFileOp()
if fileOp.Stat(req.Path) {
helper.SuccessWithData(c, true)
return
}
if req.WithInit {
if err := fileOp.CreateDir(req.Path, 0644); err != nil {
helper.SuccessWithData(c, false)
return
}
helper.SuccessWithData(c, true)
return
}
helper.SuccessWithData(c, true)
helper.SuccessWithData(c, false)
}

// @Tags File
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The code appears to be designed for checking whether a file exists at the specified path or creating it if necessary. However, there are a few areas that could be improved:

  1. Simplify Error Handling: The error handling logic is somewhat repetitive. Instead of repeating helper.SuccessWithData(c, false) multiple times inside different branches of the conditional statements, consider consolidating those into a single call after detecting an error.

    if err := helper.CheckBindAndValidate(&req, c); err != nil {
        return
    }
    
    ...

2. **Use Consistent Function Calls**: Ensure consistent function calls across the codebase. For example, use the same method name (`Stat`), parameter list, and context parameters for operations like checking existence and directory creation.

   ```go
   fileOp := files.NewFileOp()
   
   ...
  1. Return Value Check: After attempting to perform operations, check the result before returning success or failure directly. This helps avoid unexpected behavior due to asynchronous operations or incomplete setup.
if !fileOp.Stat(req.Path) {
    // Handle specific cases where file does not exist
} else if err := fileOp.CreateDir(req.Path, 0644); err != nil {
    helper.SuccessWithData(c, false)
    // Additional logs or retry can be added here
}
  1. Logging for Debugging: Consider adding logging within error paths to help debug issues more easily. You can use Go's standard library log package or third-party libraries like zap.
import "log"

func (b *BaseApi) CheckFile(c *gin.Context) {
    // Existing code
}

...

log.Fatalf("Failed to create directory %s: %v", req.Path, err)

...
  1. Comments for Complex Logic: Add comments around complex sections of code that might not be immediately clear to others reading the code.

By making these improvements, the code will be clearer, maintainable, and less prone to errors.

Expand Down
3 changes: 2 additions & 1 deletion backend/app/dto/request/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ type FileRename struct {
}

type FilePathCheck struct {
Path string `json:"path" validate:"required"`
Path string `json:"path" validate:"required"`
WithInit bool `json:"withInit"`
}

type FilePathsCheck struct {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/api/modules/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ export const SaveFileContent = (params: File.FileEdit) => {
return http.post<File.File>('files/save', params);
};

export const CheckFile = (path: string) => {
return http.post<boolean>('files/check', { path: path });
export const CheckFile = (path: string, withInit: boolean) => {
return http.post<boolean>('files/check', { path: path, withInit: withInit });
};

export const BatchCheckFiles = (paths: string[]) => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The provided code contains a minor issue in the CheckFile function:

  1. Parameter Change: The CheckFile function now takes an additional parameter withInit. This appears to be intended as part of the request data being sent to the server, but there are no changes needed in the logic.

  2. Return Type: The response from both functions is expected to be either a boolean indicating success or failure (boolean). No other types should typically be returned unless they have specific meanings based on context.

Overall, the main difference is simply adding another attribute to one of the function parameters and not altering the return type or logic significantly.

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/upload/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ const onSubmit = async () => {
MsgError(i18n.global.t('commons.msg.fileNameErr'));
return;
}
const res = await CheckFile(baseDir.value + file.raw.name);
const res = await CheckFile(baseDir.value + file.raw.name, false);
if (res.data) {
MsgError(i18n.global.t('commons.msg.fileExist'));
return;
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1385,6 +1385,7 @@ const message = {
existFileHelper: 'The uploaded file contains a file with the same name, do you want to overwrite it?',
existFileSize: 'File size (new -> old)',
existFileDirHelper: 'The selected file/folder has a duplicate name. Please proceed with caution!',
noSuchFile: 'The file or directory was not found. Please check and try again.',
},
ssh: {
setting: 'Setting',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1363,6 +1363,7 @@ const message = {
existFileHelper: 'アップロードしたファイルに同じ名前のファイルが含まれています。上書きしますか?',
existFileSize: 'ファイルサイズ(新しい -> 古い)',
existFileDirHelper: '選択したファイル/フォルダーには同じ名前のものが既に存在します。慎重に操作してください!',
noSuchFile: 'ファイルまたはディレクトリが見つかりませんでした。確認して再試行してください。',
},
ssh: {
setting: '設定',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,7 @@ const message = {
existFileHelper: '업로드한 파일에 동일한 이름의 파일이 포함되어 있습니다. 덮어쓰시겠습니까?',
existFileSize: '파일 크기 (새로운 -> 오래된)',
existFileDirHelper: '선택한 파일/폴더에 동일한 이름이 이미 존재합니다. 신중하게 작업하세요!',
noSuchFile: '파일 또는 디렉터리를 찾을 수 없습니다. 확인 후 다시 시도하세요.',
},
ssh: {
setting: '설정',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/ms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,7 @@ const message = {
existFileHelper: 'Fail yang dimuat naik mengandungi fail dengan nama yang sama. Adakah anda mahu menimpanya?',
existFileSize: 'Saiz fail (baru -> lama)',
existFileDirHelper: 'Fail/folder yang dipilih mempunyai nama yang sama. Sila berhati-hati!',
noSuchFile: 'Fail atau direktori tidak ditemui. Sila periksa dan cuba lagi.',
},
ssh: {
setting: 'tetapan',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/pt-br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1393,6 +1393,7 @@ const message = {
existFileHelper: 'O arquivo enviado contém um arquivo com o mesmo nome. Deseja substituí-lo?',
existFileSize: 'Tamanho do arquivo (novo -> antigo)',
existFileDirHelper: 'O arquivo/pasta selecionado tem um nome duplicado. Por favor, prossiga com cautela!',
noSuchFile: 'O arquivo ou diretório não foi encontrado. Por favor, verifique e tente novamente.',
},
ssh: {
setting: 'configuração',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,7 @@ const message = {
existFileHelper: 'Загруженный файл содержит файл с таким же именем. Заменить его?',
existFileSize: 'Размер файла (новый -> старый)',
existFileDirHelper: 'Выбранный файл/папка имеет дублирующееся имя. Пожалуйста, действуйте осторожно!',
noSuchFile: 'Файл или каталог не найдены. Пожалуйста, проверьте и повторите попытку.',
},
ssh: {
setting: 'настройка',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/tw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,7 @@ const message = {
existFileHelper: '上傳的檔案存在同名檔案,是否覆蓋?',
existFileSize: '文件大小(新->舊)',
existFileDirHelper: '選擇的檔案/資料夾存在同名,請謹慎操作!',
noSuchFile: '找不到該檔案或目錄,請檢查後重試。',
},
ssh: {
setting: '設定',
Expand Down
1 change: 1 addition & 0 deletions frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,7 @@ const message = {
existFileHelper: '上传的文件存在同名文件,是否覆盖?',
existFileSize: '文件大小 (新 -> 旧)',
existFileDirHelper: '选择的文件/文件夹存在同名,请谨慎操作!',
noSuchFile: '未能找到该文件或目录,请检查后重试',
},
ssh: {
setting: '配置',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/views/host/file-management/move/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ const acceptParams = async (props: MoveProps) => {
type.value = props.type;
if (props.name && props.name != '') {
oldName.value = props.name;
const res = await CheckFile(props.path + '/' + props.name);
const res = await CheckFile(props.path + '/' + props.name, false);
if (res.data) {
changeName.value = true;
addForm.cover = false;
Expand Down
10 changes: 8 additions & 2 deletions frontend/src/views/setting/snapshot/import/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ import DrawerHeader from '@/components/drawer-header/index.vue';
import { snapshotImport } from '@/api/modules/setting';
import { getBackupList, getFilesFromBackup } from '@/api/modules/setting';
import { Rules } from '@/global/form-rules';
import { MsgSuccess } from '@/utils/message';
import { MsgError, MsgSuccess } from '@/utils/message';
import router from '@/routers';
import { CheckFile } from '@/api/modules/files';

const drawerVisible = ref(false);
const loading = ref();
Expand Down Expand Up @@ -109,7 +110,12 @@ const checkDisable = (val: string) => {
return false;
};
const toFolder = async () => {
router.push({ path: '/hosts/files', query: { path: backupPath.value } });
const res = await CheckFile(backupPath.value, true);
if (res.data) {
router.push({ path: '/hosts/files', query: { path: backupPath.value } });
} else {
MsgError(i18n.global.t('file.noSuchFile'));
}
};

const submitImport = async (formEl: FormInstance | undefined) => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

  1. The function toFolder now includes an asynchronous check before navigating to the files page. It calls the CheckFile API to verify if the file exists at the specified path. If the file does not exist, it displays a message error.

        const res = await CheckFile(backupPath.value, true);
        if (res.data) {
            router.push({ path: '/hosts/files', query: { path: backupPath.value } });
        } else {
            MsgError(i18n.global.t('file.noSuchFile'));
        }
  2. In the submitImport function, you should handle errors properly when using promises returned by the Axios request (snapshotImport). Use .catch() to catch the rejected promise and display appropriate messages if something goes wrong during the upload process. Additionally, ensure that all variables used within the .then() block are correctly scoped.

            snapshotImport(params).then(() => {
                // Handle success, e.g., hide dialog, clear fields, notify user
                drawerVisible.value = false;
                formRef.value?.resetFields();
            }).catch(error => {
                console.error("Upload failed:", error); // Log error for debugging purposes
                MsgError(i18n.global.t('upload.fail')); // Display error message
            });

These changes improve robustness of your application, ensuring better user experience in certain situations where there may be issues with the data being processed.

Expand Down
Loading