Skip to content

Commit

Permalink
Merge pull request #25 from ozkeisar/add-servers-logs
Browse files Browse the repository at this point in the history
Add servers logs
  • Loading branch information
ozkeisar authored Sep 15, 2024
2 parents c2fc558 + 8eff0cd commit 315d8cb
Show file tree
Hide file tree
Showing 14 changed files with 745 additions and 99 deletions.
420 changes: 418 additions & 2 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"axios": "^1.7.2",
"chokidar": "^3.6.0",
"common-tags": "^1.8.2",
"console-feed": "^3.6.0",
"cors": "^2.8.5",
"defekt": "^9.3.1",
"electron-debug": "^3.2.0",
Expand Down
4 changes: 2 additions & 2 deletions src/backend/managers/projectsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { migrateProjectData } from '../utils/migrations';
import { listToHashmap } from '../utils/utils';
import { ProjectDataNew } from '../../types';
import {
checkIsGitInit,
isGitRepository,
getBranches,
getCurrentBranch,
hasUncommittedChanges,
Expand Down Expand Up @@ -99,7 +99,7 @@ class ProjectsManager {
}

private async readProjectData(projectName: string): Promise<void> {
const isGitInit = await checkIsGitInit(projectName);
const isGitInit = await isGitRepository(projectName);
const currentBranch = await getCurrentBranch(projectName);
const branches = (await getBranches(projectName)) as string[];
const hasDiffs = await hasUncommittedChanges(projectName);
Expand Down
79 changes: 73 additions & 6 deletions src/backend/server/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
import { getGraphqlSchemaFromJsonSchema } from '../../utils/jsonToSchema';
import { updateLog } from './logger';
import { mergeObjects } from '../../utils/utils';
import { emitGlobalSocketMessage } from '../socket';
import { EVENT_KEYS } from '../../types/events';

const expressPlayground =
require('graphql-playground-middleware-express').default;
Expand Down Expand Up @@ -163,13 +165,78 @@ export const getSelectedRoute = (
return selectedRoute || null;
};

export const reviveFunctions = (value: any) => {

const customConsole = {
log: (serverName: string) => (...args: any) => {
emitGlobalSocketMessage(EVENT_KEYS.SERVERS_CONSOLE, {method: 'log', data:[`${serverName}:`, ...args]})
},
error: (serverName: string) => (...args: any) => {
emitGlobalSocketMessage(EVENT_KEYS.SERVERS_CONSOLE, {method: 'error', data:[`${serverName}:`, ...args]})
},
warn: (serverName: string) => (...args: any) => {
emitGlobalSocketMessage(EVENT_KEYS.SERVERS_CONSOLE, {method: 'warn', data:[`${serverName}:`, ...args]})
},
info: (serverName: string) => (...args: any) => {
emitGlobalSocketMessage(EVENT_KEYS.SERVERS_CONSOLE, {method: 'info', data:[`${serverName}:`, ...args]})
},
debug: (serverName: string) => (...args: any) => {
emitGlobalSocketMessage(EVENT_KEYS.SERVERS_CONSOLE, {method: 'debug', data:[`${serverName}:`, ...args]})
},
// Add other methods as needed
};

export const reviveFunctionRest = (serverName: string, fnString: string) => {
try {
const script = `
(req, res) => {
const console = {
log: customConsole.log(serverName),
error: customConsole.error(serverName),
warn: customConsole.warn(serverName),
info: customConsole.info(serverName),
debug: customConsole.debug(serverName),
};
const func = (${fnString.trim()})
func(req, res)
}
`;

// eslint-disable-next-line no-eval
const func = eval(`(${value.trim()})`);
return func;
const func = eval(`(${script.trim()})`);

return func
} catch (error) {
throw new Error('fail to revive function rest');
}
};

export const reviveFunctionGraphql = (serverName: string, fnString: string) => {
try {
const script = `
(args, context, info) => {
const console = {
log: customConsole.log(serverName),
error: customConsole.error(serverName),
warn: customConsole.warn(serverName),
info: customConsole.info(serverName),
debug: customConsole.debug(serverName),
};
const func = (${fnString.trim()})
return func(args, context, info)
}
`;

// eslint-disable-next-line no-eval
const func = eval(`(${script.trim()})`);

return func
} catch (error) {
throw new Error('fail to revive function');
throw new Error('fail to revive function graphql');
}
};

Expand Down Expand Up @@ -247,7 +314,7 @@ export const handleResponse = async ({
return;
}
if (response.type === 'func' && !!response.exec) {
const func = reviveFunctions(response.exec);
const func = reviveFunctionRest(serverName, response.exec);
updateLog((req as any).id, { logType: 'local', serverName });

func(req, res);
Expand Down Expand Up @@ -337,7 +404,7 @@ export const handleGraphqlResponse = (
try {
const response = route.responsesHash?.[route.activeResponseId];
if (response?.type === 'func') {
const func = reviveFunctions(response?.exec);
const func = reviveFunctionGraphql(serverName, response?.exec || '');
updateLog(req.id, { logType: 'local', serverName });

return func(args, context, info);
Expand Down
4 changes: 2 additions & 2 deletions src/backend/utils/events.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Socket, Server as SocketIOServer } from 'socket.io';
import { SUPPORTED_PROJECT_DATA_VERSION } from '../../consts';
import {
checkIsGitInit,
isGitRepository,
getBranches,
getCurrentBranch,
hasUncommittedChanges,
Expand All @@ -20,7 +20,7 @@ export const updateClientProjectData = async (
) => {
emitSocketMessage(socket, EVENT_KEYS.IS_LOADING_DATA, {});
try {
const isGitInit = await checkIsGitInit(projectName);
const isGitInit = await isGitRepository(projectName);
const currentBranch = await getCurrentBranch(projectName);
const branches = (await getBranches(projectName)) as string[];
const hasDiffs = await hasUncommittedChanges(projectName);
Expand Down
20 changes: 1 addition & 19 deletions src/backend/utils/general.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os from 'os';
import jwt from 'jsonwebtoken';
import { SECRET_KEY, DEFAULT_SERVER_SETTINGS } from '../../consts';
import { DEFAULT_SERVER_SETTINGS } from '../../consts';
import {
getProjectPath,
getProjectServersNameList,
Expand Down Expand Up @@ -146,24 +146,6 @@ const verifyJWT = (jwtToken: string, username: string, secretKey: string) => {
}
};

export const activateProgram = async (key: string) => {
const { username } = os.userInfo();

const isValid = verifyJWT(key, username, SECRET_KEY);

if (isValid) {
const appSettings = await readAppSettings();

await updateAppSettings({
...appSettings,
activationKey: key,
});

return true;
}
return false;
};

export const getActiveProjectName = async () => {
const appSettings = await readAppSettings();

Expand Down
75 changes: 38 additions & 37 deletions src/backend/utils/git.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
import simpleGit, { SimpleGit, SimpleGitOptions } from 'simple-git';
import { getProjectPath } from './files';

export const isGitInstalled = async () => {
async function isGitInstalled(): Promise<boolean> {
try {
// Attempt to execute a Git command
await simpleGit().listRemote(['--get-url']);
// If the command executed successfully, Git is installed
// Initialize simple-git with the default options
const git: SimpleGit = simpleGit();
await git.version(); // This will throw an error if Git is not installed
return true;
} catch (error) {
// If an error occurs, Git is not installed or not properly configured
return false;
}
};

export async function checkGitConnection(projectName: string) {
const currentRepoFolderPath = await getProjectPath(projectName);

const git = simpleGit(currentRepoFolderPath);

try {
await git.listRemote(['--get-url']);
console.log('Connection to Git server established.');
return true;
} catch (error) {
console.error('Error connecting to Git server:', error);
console.error('Git is not installed:', error);
return false;
}
}

export const checkIsGitInit = async (projectName: string) => {
export const isGitRepository = async (projectName: string) => {
try {
if(!await isGitInstalled()){
return false
}
const currentRepoFolderPath = await getProjectPath(projectName);

// Specify the path to the folder
Expand All @@ -40,13 +28,34 @@ export const checkIsGitInit = async (projectName: string) => {

return isRepo;
} catch (error) {
console.log('======checkIsGitInit error', error);
console.error('isGitRepository error', error);

// If an error occurs, the folder is not a Git repository or Git is not properly configured
return false;
}
};


export async function checkGitConnection(projectName: string) {
const currentRepoFolderPath = await getProjectPath(projectName);

if(!await isGitRepository(projectName)){
return false
}
const git = simpleGit(currentRepoFolderPath);

try {
await git.listRemote(['--get-url']);
console.log('Connection to Git server established.');
return true;
} catch (error) {
console.error('Error connecting to Git server:', error);
return false;
}
}



export const isCurrentBranchWithoutRemote = async (projectName: string) => {
try {
const currentRepoFolderPath = await getProjectPath(projectName);
Expand All @@ -69,6 +78,9 @@ export const isCurrentBranchWithoutRemote = async (projectName: string) => {

export const hasUncommittedChanges = async (projectName: string) => {
try {
if(!await isGitRepository(projectName)){
return false
}
const currentRepoFolderPath = await getProjectPath(projectName);

// Specify the path to your Git repository
Expand Down Expand Up @@ -158,8 +170,12 @@ export const checkoutToBranch = async (
throw error;
}
};

export const getCurrentBranch = async (projectName: string) => {
try {
if(!await isGitRepository(projectName)){
return null
}
const currentRepoFolderPath = await getProjectPath(projectName);

const options: Partial<SimpleGitOptions> = {
Expand Down Expand Up @@ -237,21 +253,6 @@ export const commitAndPushChanges = async (
await git.push(['--force']);
};

export const getRemoteRepositoryUrl = async (projectName: string) => {
try {
const currentRepoFolderPath = await getProjectPath(projectName);
const git = simpleGit(currentRepoFolderPath);

// Get the URL of the remote repository named 'origin'
const remoteUrl = await git.remote(['get-url', 'origin']);

return remoteUrl?.trim();
} catch (error) {
console.error('Error getting remote repository URL:', error);
throw error;
}
};

export const pushChanges = async (projectName: string) => {
try {
const currentRepoFolderPath = await getProjectPath(projectName);
Expand Down
2 changes: 0 additions & 2 deletions src/consts/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ export const appSettingsFolder = `${mainFolderPath}settings/`;

export const SUPPORTED_PROJECT_DATA_VERSION = '0.0.9';

export const SECRET_KEY = 'verysecretkey';

export const DEFAULT_APP_SETTINGS: AppSettings = Object.freeze({
userApproveAnalytics: false,
serverDisabledUntil: null,
Expand Down
32 changes: 27 additions & 5 deletions src/renderer/components/devTools/devTools.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useRef, useState } from 'react';
import { useLoggerStore } from '../../state/logger';
import { Console } from './console';
import { CommandsTerminal } from './terminal/terminal';
Expand All @@ -7,8 +7,9 @@ import styles from './devTools.module.css';
import { ConsoleDialog } from '../dialogs/consoleDialog';
import { reportButtonClick } from '../../utils';
import { BUTTONS } from '../../../consts/analytics';
import { ServersLogs } from './serversLogs';

type TabIds = 'console' | 'terminal';
type TabIds = 'console' | 'terminal' | 'serversLogs';

interface Tab {
id: TabIds;
Expand All @@ -27,13 +28,19 @@ function DevTools({ onMinimize, onCenter, onMaximize, devToolsHeight }: Props) {
const { resetLoggerState, serverLogs } = useLoggerStore();
const [openConsoleDialog, setOpenConsoleDialog] = useState(false);
const [search, setSearch] = useState('');
const serversLogsRef = useRef<{ clear: () => void } | null>(null)

const [selectedId, setSelectedId] = useState<TabIds>('console');
const isConsole = selectedId === 'console';
const showClear = [ 'console', 'serversLogs'].includes(selectedId);
const isConsole = 'console' === selectedId

const handleClear = () => {
reportButtonClick(BUTTONS.CONSOLE_CLEAR);
resetLoggerState();
if(selectedId === 'console'){
resetLoggerState();
}else if(selectedId === 'serversLogs' && serversLogsRef.current?.clear){
serversLogsRef.current.clear()
}
};

const tabs: Tab[] = [
Expand All @@ -47,6 +54,11 @@ function DevTools({ onMinimize, onCenter, onMaximize, devToolsHeight }: Props) {
title: 'terminal',
counter: 0,
},
{
id: 'serversLogs',
title: 'servers logs',
counter: 0,
},
];

return (
Expand Down Expand Up @@ -82,7 +94,7 @@ function DevTools({ onMinimize, onCenter, onMaximize, devToolsHeight }: Props) {
showMinimize={devToolsHeight !== 40}
showCenter={devToolsHeight !== '50%'}
showFullScreen={isConsole}
showClear={isConsole}
showClear={showClear}
showSearch={isConsole}
/>
</div>
Expand All @@ -95,7 +107,17 @@ function DevTools({ onMinimize, onCenter, onMaximize, devToolsHeight }: Props) {
>
<CommandsTerminal />
</div>

<div
style={
selectedId === 'serversLogs' ? { height: '100%' } : { display: 'none' }
}
>
<ServersLogs ref={serversLogsRef}/>
</div>

{selectedId === 'console' && <Console search={search} />}

{/* {selectedId === 2 && <div>Logger Component</div>} */}
</div>
{openConsoleDialog && (
Expand Down
Loading

0 comments on commit 315d8cb

Please sign in to comment.