Skip to content

Commit

Permalink
Code: fix working path issues, clean some code, Lang: fix missing pt-…
Browse files Browse the repository at this point in the history
…br line
  • Loading branch information
themitosan committed Dec 11, 2024
1 parent 6c16f8a commit d47d07b
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 59 deletions.
6 changes: 2 additions & 4 deletions Lang/pt-br.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,15 @@

"importRemoveStatus": "\nINFO - O processo de reparo incluiu %VAR_0% repositórios e removeu %VAR_1% itens no banco de dados com %VAR_2% erros.\n",
"importRemoveError": "==> Erros de inclusão / exclusão:",
"importRemoveDetails": "Repo: %VAR_0%\nDetails: %VAR_1%\n",
"importRemoveDetails": "Repo: %VAR_0%\nDetalhes: %VAR_1%\n",

"infoCheckMissingKeys": "INFO - Verificando possíveis chaves que não estão presentes nos repositórios do banco de dados...",
"infoAddMissingKey": "INFO - Adicionando chave \"%VAR_0%\" no %VAR_1%...",
"infoRemoveKey": "INFO - Removendo chave desnecessária de %VAR_0%: %VAR_1%",

"removePathFromKey": "INFO - Removendo caminho do item: \"%VAR_0%\"",

"infoAddRemoveKeys": "INFO - GRPP adicionou %VAR_0% chaves que estavam faltando e removeu %VAR_1% chaves desnecessárias em %VAR_2% repositórios.",

"infoRepairComplete": "INFO - Processo de reparo completo!\n",
"infoRepairComplete": "\nINFO - Processo de reparo completo!\n",

"confirmRemoveRepoDatabase": "AVISO - Parece que %VAR_0% não existe!\nVocê quer remover esse item do banco de dados? [S/n] ",

Expand Down
3 changes: 1 addition & 2 deletions src/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
Import TS modules
*/

import { grpp_updateRepoData } from './main';
import { grpp_displayMainLogo } from './utils';
import { grpp_updateRepoData, originalCwd } from './main';
import { grpp_convertLangVar, langDatabase } from './lang';
import { createLogEntry, execReasonListCheck, runExternalCommand, runExternalCommand_Defaults } from './tools';

Expand Down Expand Up @@ -76,7 +76,6 @@ export async function grpp_startImport(cloneURL:string){
urlData = cloneURL.split('/'),
name = urlData[urlData.length - 1],
owner = urlData[urlData.length - 2],
originalCwd = structuredClone(process.cwd()),
repoPath = `${process.cwd()}/repos/${urlData[2]}/${owner}/${name}`;

// Check conditions
Expand Down
4 changes: 1 addition & 3 deletions src/lang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,8 @@ export var langDatabase:any = {
"infoRemoveKey": "INFO - Removing deprecated key from %VAR_0%: %VAR_1%",

"removePathFromKey": "INFO - Removing path from current repo entry: \"%VAR_0%\"",

"infoAddRemoveKeys": "INFO - GRPP added %VAR_0% missing keys and removed %VAR_1% deprecated keys on %VAR_2% repos.",

"infoRepairComplete": "INFO - Repair complete!\n",
"infoRepairComplete": "\nINFO - Repair complete!\n",

"confirmRemoveRepoDatabase": "WARN - It seems that %VAR_0% does not exists!\nDo you want to remove this entry from database? [Y/n] ",

Expand Down
46 changes: 17 additions & 29 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import { grpp_getReposFrom } from './getReposFrom';
import { grpp_startRepairDatabase } from './repair';
import { createLogEntry, preventMinMax } from './tools';
import { createLogEntry, preventMinMax, checkFlagIsValid } from './tools';
import { grpp_batchImport, grpp_startImport, grppRepoEntry } from './import';
import { grpp_checkBatchUpdateProcess, grpp_processBatchFile, grpp_updateRepo } from './update';
import { grpp_convertLangVar, grpp_displayLangList, grpp_loadLang, grpp_setLang, langDatabase } from './lang';
Expand Down Expand Up @@ -82,7 +82,7 @@ export const grppSettingsFile_Defaults:any | Pick <grppSettingsFile, 'version' |
}

// Default user settings
export const grppUserSettings_Defaults: Pick <grppUserSettings, 'lang'> = {
export const grppUserSettings_Defaults:Pick <grppUserSettings, 'lang'> = {
lang: 'en-us'
}

Expand All @@ -109,6 +109,9 @@ export var
// NPM global path
NPM_GLOBAL_PATH = '',

// App default working dir
originalCwd = structuredClone(process.cwd()),

// User settings
grppUserSettings:grppUserSettings = { ...grppUserSettings_Defaults },

Expand Down Expand Up @@ -171,8 +174,9 @@ async function grpp_loadSettings(){
*/
export async function grpp_saveSettings(mode:string = 'db'){
try {

// Swicth save mode
process.chdir(originalCwd);
switch (mode){

// User settings
Expand Down Expand Up @@ -235,33 +239,16 @@ export function grpp_updateRepoData(path:string, repoData:grppRepoEntry){
* @param path [string] Repo to be removed from database
*/
export function grpp_removeRepo(path:string){
if (grppSettings.repoEntries[path] !== void 0){
delete grppSettings.repoEntries[path];
grpp_saveSettings();
} else {
createLogEntry(`WARN - Unable to find ${path} on repo database!`, 'warn');
}
}

/**
* Check if current arg is valid
* @param arg [string] Arg to be checked
*/
function checkFlagIsValid(arg:string):string {

var res = '',
handleDatabase = ['-', '/'];

if (arg.slice(0, 2) === '--'){
res = arg.slice(2, arg.length);
} else {
if (handleDatabase.indexOf(arg.slice(0, 1)) !== -1) res = arg.slice(1, arg.length);
}

return res;

return new Promise<void>(function(resolve){
if (grppSettings.repoEntries[path] !== void 0){
delete grppSettings.repoEntries[path];
grpp_saveSettings();
} else {
createLogEntry(`WARN - Unable to find ${path} on repo database!`, 'warn');
}
resolve();
});
}

/**
* Load user settings
*/
Expand Down Expand Up @@ -386,6 +373,7 @@ async function init(){
// Set new path var and check if it exists. If not, try creating it
const newPath = currentFlag.replace('path=', '');
if (module_fs.existsSync(newPath) === !1) module_fs.mkdirSync(newPath);
originalCwd = structuredClone(newPath);
process.chdir(newPath);

}
Expand Down
23 changes: 14 additions & 9 deletions src/repair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,18 +232,17 @@ async function grpp_repairAddMissingRepo(path:string){

// Declare config file path and check if current repo isn't bare
var configPath = `${path}/config`;
if (module_fs.existsSync(`${path}/.git/config`) === !0){
if (module_fs.existsSync(`${process.cwd()}/repos/${path}/.git/config`) === !0){
configPath = `${path}/.git/config`;
createLogEntry(grpp_convertLangVar(langDatabase.repair.warnRepoNotBare, [module_path.parse(path).name]), 'warn');
}

// Check if config file exists
if (module_fs.existsSync(configPath) === !0){
if (module_fs.existsSync(`${process.cwd()}/repos/${configPath}`) === !0){

// Create vars
const
gitConfig = parseINI(module_fs.readFileSync(configPath, 'utf-8')),
originalCwd = structuredClone(process.cwd()),
gitConfig = parseINI(module_fs.readFileSync(`${process.cwd()}/repos/${configPath}`, 'utf-8')),
repoUrl = gitConfig['remote "origin"'].url,
urlData = repoUrl.split('/'),
repoName = urlData[urlData.length - 1],
Expand All @@ -259,12 +258,19 @@ async function grpp_repairAddMissingRepo(path:string){
importDate: new Date().toString()
};

// Create path structure
[
`repos/${urlData[2]}`,
`repos/${urlData[2]}/${owner}`
].forEach(function(cEntry){
if (module_fs.existsSync(`${process.cwd()}/${cEntry}`) === !1) module_fs.mkdirSync(`${process.cwd()}/${cEntry}`);
});

// Create log entry and start import process
createLogEntry(grpp_convertLangVar(langDatabase.repair.importMissingRepo, [repoName, path]));
await runExternalCommand('git config remote.origin.fetch "+refs/*:refs/*"', { ...runExternalCommand_Defaults, chdir: path })
await runExternalCommand('git config remote.origin.fetch "+refs/*:refs/*"', { ...runExternalCommand_Defaults, chdir: `${process.cwd()}/repos/${path}` })
.then(function(){
grpp_updateRepoData(path.replace(`${process.cwd()}/repos/`, ''), repoData);
process.chdir(originalCwd);
grpp_updateRepoData(path, repoData);
importSuccessCounter++;
resolve();
});
Expand All @@ -273,8 +279,7 @@ async function grpp_repairAddMissingRepo(path:string){

// Create error msg, log, push error and resolve
pushError(path, grpp_convertLangVar(langDatabase.repair.errorConfigFileNotExists, [module_path.parse(path).name]));
grpp_removeRepo(path);
resolve();
await grpp_removeRepo(path).then(resolve);

}

Expand Down
25 changes: 21 additions & 4 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ declare var console:any;
*/

import { grpp_convertLangVar } from './lang';
import { enableSilentMode, grppSettings } from './main';
import { enableSilentMode, grppSettings, originalCwd } from './main';

/*
Require node modules
Expand Down Expand Up @@ -96,6 +96,25 @@ export const consoleTextStyle = {
Functions
*/

/**
* Check if current arg is valid
* @param arg [string] Arg to be checked
*/
export function checkFlagIsValid(arg:string):string {

var res = '',
handleDatabase = ['-', '/'];

if (arg.slice(0, 2) === '--'){
res = arg.slice(2, arg.length);
} else {
if (handleDatabase.indexOf(arg.slice(0, 1)) !== -1) res = arg.slice(1, arg.length);
}

return res;

}

/**
* Change text color if determinated var is higher than zero
* @param currentValue [number] Current value
Expand Down Expand Up @@ -284,9 +303,7 @@ export async function runExternalCommand(cmd:string, options:runExternalCommandO
// Change current working directory and declare some vars
var stdData = '';
process.chdir(options.chdir);
const
originalCwd = structuredClone(process.cwd()),
execCmd = module_childProcess.exec(cmd);
const execCmd = module_childProcess.exec(cmd);

// Process std data
execCmd.stderr?.on('data', function(data){
Expand Down
11 changes: 3 additions & 8 deletions src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import { grppRepoEntry } from './import';
import { grpp_convertLangVar, langDatabase } from './lang';
import { grpp_displayMainLogo, grpp_getLogoString } from './utils';
import { APP_COMPILED_AT, APP_HASH, APP_VERSION, grpp_updateRepoData, grpp_updateDatabaseSettings, grppSettings } from './main';
import { APP_COMPILED_AT, APP_HASH, APP_VERSION, grpp_updateRepoData, grpp_updateDatabaseSettings, grppSettings, originalCwd } from './main';
import { checkConnection, converMsToHHMMSS, convertArrayToString, createLogEntry, execReasonListCheck, isValidJSON, openOnTextEditor, parsePercentage, parsePositive, runExternalCommand, runExternalCommand_Defaults, runExternalCommand_output, spliceArrayIntoChunks, trimString, updateConsoleLine, consoleTextStyle, changeTextColorNumber } from './tools';

/*
Expand Down Expand Up @@ -174,12 +174,8 @@ export async function grpp_updateRepo(path:string){
*/
export async function grpp_processBatchFile(id:number){

// Create consts
const
originalCwd = structuredClone(process.cwd()),
batchFilePath = `${originalCwd}/.temp/GRPP_BATCH.json`;

// Check if batch file exists
// Create batch file path and check if batch file exists
const batchFilePath = `${originalCwd}/.temp/GRPP_BATCH.json`;
if (module_fs.existsSync(batchFilePath) === !0){

// Read batch update file, set total repos var on update results and start processing repos
Expand Down Expand Up @@ -212,7 +208,6 @@ export async function grpp_processBatchFile(id:number){
async function grpp_startBatchUpdate(){

// Declare vars
const originalCwd = structuredClone(process.cwd());
var completedRunners = 0,
updateList:string[] = [],
priorityRepos:string[] = [];
Expand Down

0 comments on commit d47d07b

Please sign in to comment.