Skip to content

Commit

Permalink
feat: SP-1988 Remove results watcher, do not reload the app after sca…
Browse files Browse the repository at this point in the history
…n is completed, better error handling
  • Loading branch information
matiasdaloia committed Dec 27, 2024
1 parent 88dd1d9 commit c9f7ce3
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 94 deletions.
3 changes: 0 additions & 3 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,15 +210,12 @@ func (a *App) GetScanSettingsFilePath() (string, error) {

func (a *App) SetScanRoot(path string) {
config.GetInstance().SetScanRoot(path)
runtime.WindowReloadApp(a.ctx)
}

func (a *App) SetResultFilePath(path string) {
config.GetInstance().SetResultFilePath(path)
runtime.WindowReloadApp(a.ctx)
}

func (a *App) SetScanSettingsFilePath(path string) {
config.GetInstance().SetScanSettingsFilePath(path)
runtime.WindowReloadApp(a.ctx)
}
1 change: 0 additions & 1 deletion backend/service/result_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ import (
type ResultService interface {
GetAll(dto *entities.RequestResultDTO) ([]entities.ResultDTO, error)
SetContext(ctx context.Context)
WatchResults()
}
42 changes: 0 additions & 42 deletions backend/service/result_service_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ import (
"github.com/scanoss/scanoss.lui/backend/entities"
"github.com/scanoss/scanoss.lui/backend/mappers"
"github.com/scanoss/scanoss.lui/backend/repository"
"github.com/scanoss/scanoss.lui/internal/config"
"github.com/scanoss/scanoss.lui/internal/utils"
"github.com/wailsapp/wails/v2/pkg/runtime"
)

type ResultServiceImpl struct {
Expand Down Expand Up @@ -57,43 +55,3 @@ func (s *ResultServiceImpl) GetAll(dto *entities.RequestResultDTO) ([]entities.R
func (s *ResultServiceImpl) SetContext(ctx context.Context) {
s.ctx = ctx
}

func (s *ResultServiceImpl) WatchResults() {
if s.watcher == nil {
return
}

err := s.watcher.Add(config.GetInstance().ResultFilePath)
if err != nil {
log.Error().Err(err).Msg("Error watching results file")
return
}

log.Debug().Msgf("Watching %s for changes...", config.GetInstance().ResultFilePath)

go func() {
for {
select {
case event, ok := <-s.watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
runtime.WindowReloadApp(s.ctx)
}
if event.Op&fsnotify.Remove == fsnotify.Remove {
runtime.WindowReloadApp(s.ctx)
}

case err, ok := <-s.watcher.Errors:
if !ok {
return
}
log.Error().Err(err).Msg("Error watching results file")
case <-s.ctx.Done():
s.watcher.Close()
return
}
}
}()
}
6 changes: 2 additions & 4 deletions frontend/src/components/FilterComponentActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ export default function FilterComponentActions() {
asyncFn: async (args: OnFilterComponentArgs) => {
await onFilterComponent(args);
},
onError: (error) => {
console.error(error);
onError: () => {
toast({
title: 'Error',
description: 'An error occurred while filtering the component. Please try again.',
Expand All @@ -38,8 +37,7 @@ export default function FilterComponentActions() {
await handleFilterComponent(args);
setShowReplaceComponentDialog(false);
},
onError: (error) => {
console.error(error);
onError: () => {
toast({
title: 'Error',
description: 'An error occurred while replacing the component. Please try again.',
Expand Down
13 changes: 7 additions & 6 deletions frontend/src/components/ScanDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
import { Input } from '@/components/ui/input';
import { withErrorHandling } from '@/lib/errors';
import useResultsStore from '@/modules/results/stores/useResultsStore';
import useConfigStore from '@/stores/useConfigStore';

import { GetWorkingDir, SelectDirectory, SetScanRoot } from '../../wailsjs/go/main/App';
import { GetWorkingDir, SelectDirectory } from '../../wailsjs/go/main/App';
import { GetDefaultScanArgs, ScanStream } from '../../wailsjs/go/service/ScanServicePythonImpl';
import { EventsOn } from '../../wailsjs/runtime/runtime';
import Link from './Link';
Expand All @@ -31,6 +32,8 @@ interface ScanDialogProps {
export default function ScanDialog({ onOpenChange, withOptions }: ScanDialogProps) {
const { toast } = useToast();

const setScanRoot = useConfigStore((state) => state.setScanRoot);

const [directory, setDirectory] = useState('');
const [args, setArgs] = useState<string>('');
const [output, setOutput] = useState<OutputLine[]>([]);
Expand All @@ -45,8 +48,7 @@ export default function ScanDialog({ onOpenChange, withOptions }: ScanDialogProp
setDirectory(selectedDir);
}
},
onError: (error) => {
console.error('Error selecting directory:', error);
onError: () => {
toast({
title: 'Error',
description: 'An error occurred while selecting the directory. Please try again.',
Expand All @@ -60,11 +62,10 @@ export default function ScanDialog({ onOpenChange, withOptions }: ScanDialogProp
setScanStatus('scanning');
setOutput([]);
await ScanStream([directory, ...args.split(' ')]);
await SetScanRoot(directory);
await setScanRoot(directory);
await fetchResults();
},
onError: (error) => {
console.error('Error scanning:', error);
onError: () => {
toast({
title: 'Error',
description: 'An error occurred while scanning. Please try again.',
Expand Down
60 changes: 32 additions & 28 deletions frontend/src/components/StatusBar.tsx
Original file line number Diff line number Diff line change
@@ -1,34 +1,42 @@
import { useQueryClient } from '@tanstack/react-query';
import { File, FolderOpen } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useEffect } from 'react';

import useSelectedResult from '@/hooks/useSelectedResult';
import { withErrorHandling } from '@/lib/errors';
import useResultsStore from '@/modules/results/stores/useResultsStore';
import useConfigStore from '@/stores/useConfigStore';

import {
GetResultFilePath,
GetScanRoot,
GetScanSettingsFilePath,
SelectDirectory,
SelectFile,
SetResultFilePath,
SetScanRoot,
SetScanSettingsFilePath,
} from '../../wailsjs/go/main/App';
import { SelectDirectory, SelectFile } from '../../wailsjs/go/main/App';
import { toast } from './ui/use-toast';

export default function StatusBar() {
const [scanRoot, setScanRoot] = useState<string>('');
const [resultsFile, setResultsFile] = useState<string>('');
const [settingsFile, setSettingsFile] = useState<string>('');
const queryClient = useQueryClient();
const selectedResult = useSelectedResult();

const fetchResults = useResultsStore((state) => state.fetchResults);

const scanRoot = useConfigStore((state) => state.scanRoot);
const resultsFile = useConfigStore((state) => state.resultsFile);
const settingsFile = useConfigStore((state) => state.settingsFile);

const setScanRoot = useConfigStore((state) => state.setScanRoot);
const setResultsFile = useConfigStore((state) => state.setResultsFile);
const setSettingsFile = useConfigStore((state) => state.setSettingsFile);

const getInitialConfig = useConfigStore((state) => state.getInitialConfig);

const handleSelectScanRoot = withErrorHandling({
asyncFn: async () => {
const selectedDir = await SelectDirectory(scanRoot ?? '.');
if (selectedDir) {
await SetScanRoot(selectedDir);
await setScanRoot(selectedDir);
await queryClient.invalidateQueries({
queryKey: ['localFileContent', selectedResult?.path],
});
}
},
onError: (error) => {
console.error('Error selecting scan root:', error);
onError: () => {
toast({
variant: 'destructive',
title: 'Error',
Expand All @@ -41,11 +49,11 @@ export default function StatusBar() {
asyncFn: async () => {
const file = await SelectFile(scanRoot ?? '.');
if (file) {
await SetResultFilePath(file);
await setResultsFile(file);
await fetchResults();
}
},
onError: (error) => {
console.error('Error selecting results file:', error);
onError: () => {
toast({
variant: 'destructive',
title: 'Error',
Expand All @@ -58,11 +66,11 @@ export default function StatusBar() {
asyncFn: async () => {
const file = await SelectFile(scanRoot ?? '.');
if (file) {
await SetScanSettingsFilePath(file);
await setSettingsFile(file);
await fetchResults();
}
},
onError: (error) => {
console.error('Error selecting settings file:', error);
onError: () => {
toast({
variant: 'destructive',
title: 'Error',
Expand All @@ -72,11 +80,7 @@ export default function StatusBar() {
});

useEffect(() => {
GetScanRoot().then(setScanRoot);

GetResultFilePath().then(setResultsFile);

GetScanSettingsFilePath().then(setSettingsFile);
getInitialConfig();
}, []);

return (
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ interface WithErrorHandlingParams {
asyncFn: (...args: any[]) => Promise<void>;
onError: (error: unknown) => void;
onFinish?: () => void;
onSuccess?: () => Promise<void>;
}

export const withErrorHandling = ({ asyncFn, onError, onFinish }: WithErrorHandlingParams) => {
export const withErrorHandling = ({ asyncFn, onError, onFinish, onSuccess }: WithErrorHandlingParams) => {
return async (...args: any[]) => {
try {
await asyncFn(...args);
await onSuccess?.();
} catch (error) {
onError(error);
} finally {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/modules/results/stores/useResultsStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ const useResultsStore = create<ResultsStore>()(
set({
error: error instanceof Error ? error.message : 'An error occurred while fetching results',
});
throw error;
} finally {
set({ isLoading: false }, false, 'FETCH_RESULTS');
}
Expand Down
56 changes: 56 additions & 0 deletions frontend/src/stores/useConfigStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

import {
GetResultFilePath,
GetScanRoot,
GetScanSettingsFilePath,
SetResultFilePath,
SetScanRoot,
SetScanSettingsFilePath,
} from '../../wailsjs/go/main/App';

interface ResultsState {
scanRoot: string;
resultsFile: string;
settingsFile: string;
}

interface ResultsActions {
setScanRoot: (scanRoot: string) => Promise<void>;
setResultsFile: (resultsFile: string) => Promise<void>;
setSettingsFile: (settingsFile: string) => Promise<void>;

getInitialConfig: () => Promise<void>;
}

type ConfigStore = ResultsState & ResultsActions;

export default create<ConfigStore>()(
devtools((set) => ({
scanRoot: '',
resultsFile: '',
settingsFile: '',

setScanRoot: async (scanRoot: string) => {
await SetScanRoot(scanRoot);
set({ scanRoot });
},
setResultsFile: async (resultsFile: string) => {
await SetResultFilePath(resultsFile);
console.log(resultsFile);
set({ resultsFile });
},
setSettingsFile: async (settingsFile: string) => {
await SetScanSettingsFilePath(settingsFile);
set({ settingsFile });
},

getInitialConfig: async () => {
const scanRoot = await GetScanRoot();
const resultsFile = await GetResultFilePath();
const settingsFile = await GetScanSettingsFilePath();
set({ scanRoot, resultsFile, settingsFile });
},
}))
);
2 changes: 0 additions & 2 deletions frontend/wailsjs/go/service/ResultServiceImpl.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,3 @@ import {context} from '../models';
export function GetAll(arg1:entities.RequestResultDTO):Promise<Array<entities.ResultDTO>>;

export function SetContext(arg1:context.Context):Promise<void>;

export function WatchResults():Promise<void>;
4 changes: 0 additions & 4 deletions frontend/wailsjs/go/service/ResultServiceImpl.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,3 @@ export function GetAll(arg1) {
export function SetContext(arg1) {
return window['go']['service']['ResultServiceImpl']['SetContext'](arg1);
}

export function WatchResults() {
return window['go']['service']['ResultServiceImpl']['WatchResults']();
}
3 changes: 0 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,6 @@ func run() error {
app.Init(ctx, scanossSettingsService, keyboardService)
scanService.SetContext(ctx)
resultService.SetContext(ctx)

// Add watchers
go resultService.WatchResults()
},
OnBeforeClose: func(ctx context.Context) (prevent bool) {
return app.BeforeClose(ctx)
Expand Down

0 comments on commit c9f7ce3

Please sign in to comment.