Skip to content

Commit

Permalink
Funções para evitar erros
Browse files Browse the repository at this point in the history
- Adicionado uma simples verificação se a pasta de destino existe.
  • Loading branch information
Medronic authored Sep 9, 2022
1 parent 813e86f commit 6e808c9
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 69 deletions.
2 changes: 2 additions & 0 deletions src/languages.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"lblStatusMsg5": "[ERRO] Erro de soquete ao buscar estatísticas!",
"lblStatusMsg6": "Não foi possível buscar a lista de repositórios.",
"lblStatusMsg7": "[ERRO] Nome de usuário não encontrado. (O servidor retornou o status 404)",
"lblStatusPath1": "O caminho do diretório não foi encontrado.",
"lblTheme": [
"Claro",
"Escuro"
Expand All @@ -29,6 +30,7 @@
"lblStatusMsg5": "[ERROR] Socket error fetching stats!",
"lblStatusMsg6": "Could not fetch list of repositories.",
"lblStatusMsg7": "[ERROR] Username not found. (Server returned status 404)",
"lblStatusPath1": "The directory path was not found.",
"lblTheme": [
"Light",
"Dark"
Expand Down
31 changes: 16 additions & 15 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,39 @@

sg.theme("DarkPurple4")

# print(ttv.getUserID("medronic"))

UserProfile = md.getUserProfile()
DownloadFolder = md.GetDownloadPath()

main = [
[sg.Text(f'{md.lngLblUser}', key='lblUser'), sg.Input(key='github_user', size=(45, 1))],
[sg.Text(f'{md.lngLblDir}', key='lblDir'), sg.Input(default_text=f'{UserProfile}', key='download_path', size=(42, 1))],
[sg.Text(f'{md.lngLblDir}', key='lblDir'), sg.Input(default_text=f'{DownloadFolder}', key='download_path', size=(42, 1))],

[sg.Button(f'{md.lngBtnDownloadRepositories}', key='download_repositories', size=(20, 1))],

[sg.Text('Status: '), sg.Text(f'{md.lngStatusMsg1}', key='lblstatus')],
]


settings = [

[sg.Text(f'Tema', key='lblTheme'), sg.Drop(values=('Dark', 'Light'), default_value=f'{md.stgTheme}', key='stg_theme', readonly=True)],
[sg.Text(f'Linguagem', key='lblLanguage'), sg.Drop(values=('english', 'portuguese'), default_value=f'{md.stgLang}', key='stg_language', readonly=True)],
[sg.Text(f'Theme', key='lblTheme'), sg.Drop(values=('Dark', 'Light'), default_value=f'{md.stgTheme}', key='stg_theme', readonly=True)],
[sg.Text(f'Language', key='lblLanguage'), sg.Drop(values=('english', 'portuguese'), default_value=f'{md.stgLang}', key='stg_language', readonly=True)],

[sg.Text('Diretório Padrão:', key='lblDefaultDir'), sg.Input(default_text=f'{md.stgDownloadPath}', key='stg_downloadpath', size=(42, 1))],
[sg.Button('Salvar Configurações', key='btnSaveSettings',
[sg.Text('Default Dir:', key='lblDefaultDir'), sg.Input(default_text=f'{md.stgDownloadPath}', key='stg_downloadpath', size=(42, 1), tooltip='Please, add exactly Path!')],
[sg.Button('Save Settings', key='btnSaveSettings',
size=(18, 1), font='15px')]

]

about = [
[sg.Text(f'{md.AppName}', font='15px')],
[sg.Text(f'Description: {md.AppDescription}', font='15px')],
[sg.Text(f'Desenvolvido: {md.AppAuthor} - {md.AppAuthorNickname}', font='15px')],
[sg.Text(f'Versão: {md.AppVersion}', font='15px')],
[sg.Button('Verificar Atualizações', key='check_update', size=(18, 1), font='15px')]
[sg.Text(f'Created by: {md.AppAuthor} - {md.AppAuthorNickname}', font='15px')],
[sg.Text(f'Version: {md.AppVersion}', font='15px')],
[sg.Button('Check Update', key='check_update', size=(18, 1), font='15px')]
]

layout = [
[sg.TabGroup([[sg.Tab('Main', main), sg.Tab(
'Configurações', settings), sg.Tab('Sobre', about)]])],
'Settings', settings), sg.Tab('About', about)]])],
]

window = sg.Window(f"{md.AppName}", layout, size=(460, 200), icon="./static/img/icons/favicon.ico")
Expand All @@ -52,8 +49,11 @@

if event == 'download_repositories':
if values['github_user'] != '':
md.DownloadRepositories(values['github_user'], values['download_path'])
window['lblstatus'].update(f"{md.status}")
if md.VerifyPath(values['download_path']) == True:
md.DownloadRepositories(values['github_user'], values['download_path'])
window['lblstatus'].update(f"{md.status}")
else:
sg.popup(f'{md.lngStatusPath1}', title='Erro')
else:
sg.popup("Provide a username", title="Error")

Expand All @@ -63,6 +63,7 @@
md.stgDownloadPath = values['stg_downloadpath']

md.SaveSettings(md.stgTheme, md.stgLang, md.stgDownloadPath)
sg.popup('All settings saved', title='Success')
md.SaveLogs('Settings saved successfully')
if event == sg.WIN_CLOSED or event == 'Exit':
break
81 changes: 28 additions & 53 deletions src/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,39 +23,13 @@ def SaveLogs(p1):
date = datetime.datetime.now()
outfile.write(f"{date} - {p1}")

# Função para formatar o List Box removendo espaços e caracteres, apenas deixando números

def getUserProfile():
return os.path.join(os.environ['USERPROFILE'], "Downloads")

def format_string(d1):
global result_final
numbers = ["0","1","2","3","4","5","6","7","8","9"]
for i in range(len(d1)):
if d1[i] not in numbers:
d1 = d1[:i] + " " + d1[i+1:]
result_final = d1

# Função para Ler a Lista de Games

# def LoadListGames():
# print("Carregando Lista de Jogos...")

# if os.path.isfile('my_list.json'):
# arquivo_json = open('my_list.json', 'r', encoding='utf-8')
# data = json.loads(arquivo_json.read())

# global gameID
# global gameName

# gameID = data["Games"]['id']
# # gameName = data["Games"]['name']

# for i in range(len(gameID)):
# print(gameID[i])
# else:
# print("Erro ao carregar Lista de Jogos!")
# Função para salvar as configurações

def SaveSettings(p1 = None, p2 = None, p3 = None, p4 = None, p5 = None, p6 = None):
data = {}
data['Settings'] = {'Application': {'Name': AppName, 'Description': AppDescription, 'Author': AppAuthor, 'AuthorNickname': AppAuthorNickname, 'Version': AppVersion}, 'UI': {'Theme': p1, 'Language': p2, 'DownloadPath': p3}}
with open('settings.json', 'w', encoding='utf-8') as outfile:
json.dump(data, outfile)

# Função para Ler as Configurações do Arquivo JSON

Expand Down Expand Up @@ -115,17 +89,12 @@ def LoadSettings():
global lngStatusMsg5
global lngStatusMsg6
global lngStatusMsg7
global lngStatusMsg8

global lngLblTheme

# Variáveis Globais da Aplicação para Twitch
global lngStatusPath1

# global Username
# global ClientID
# global ClientSecret
global lngLblTheme

# Configurações da Aplicação
# Variáveis Globais de Configurações da Aplicação

lngLblUser = data[f'{stgLang}'][0]['lblUser']
lngLblDir = data[f'{stgLang}'][0]['lblDir']
Expand All @@ -137,6 +106,7 @@ def LoadSettings():
lngStatusMsg5 = data[f'{stgLang}'][0]['lblStatusMsg5']
lngStatusMsg6 = data[f'{stgLang}'][0]['lblStatusMsg6']
lngStatusMsg7 = data[f'{stgLang}'][0]['lblStatusMsg7']
lngStatusPath1 = data[f'{stgLang}'][0]['lblStatusPath1']

lngLblTheme = data[f'{stgLang}'][0]['lblTheme']

Expand All @@ -145,25 +115,31 @@ def LoadSettings():
else:
SaveLogs(f"Language file settings not found! Creating default language file...\n")

# Função para salvar as configurações
# Função para pegar a pasta de Downloads do usuário

def SaveSettings(p1 = None, p2 = None, p3 = None, p4 = None, p5 = None, p6 = None):
data = {}
# data['Settings'] = {'Username': p1, 'ClientID': p2, 'ClientSecret': p3} # Working
data['Settings'] = {'Application': {'Name': AppName, 'Description': AppDescription, 'Author': AppAuthor, 'AuthorNickname': AppAuthorNickname, 'Version': AppVersion}, 'UI': {'Theme': p1, 'Language': p2, 'DownloadPath': p3}}
with open('settings.json', 'w', encoding='utf-8') as outfile:
json.dump(data, outfile)
def GetDownloadPath():
if os.name == 'posix':
return os.path.expanduser('~/Downloads')
elif os.name == 'nt':
return os.path.join(os.environ['USERPROFILE'], 'Downloads')
else:
return os.getcwd()

def ThemeLang():
for i in range(len(stgTheme)):
return stgTheme[i]
# Função para verificar se o diretório existe

def VerifyPath(path):
if os.path.isdir(path):
return True
else:
return False

# Função para baixar os repositórios
def DownloadRepositories(user, path):
global status

url = 'https://api.github.com/users/{0}/repos'.format(user)
error = False
status = f"Nenhum erro por enquanto..."
status = f"No errors for now!"

try:
r = requests.get(url, timeout=10)
Expand Down Expand Up @@ -214,5 +190,4 @@ def DownloadRepositories(user, path):
print('Cloning repository: %s' % data[i]['name'])

call(['git', 'clone', data[i]['clone_url']])
status = 'All repositories cloned successfully!'
SaveLogs(status)
status = 'All repositories cloned successfully!'
2 changes: 1 addition & 1 deletion src/settings.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"Settings": {"Application": {"Name": "Github Clone - GUI", "Description": "Clone all repositories from a Github User", "Author": "Moises Freitas", "AuthorNickname": "Medronic", "Version": "0.0.1"}, "UI": {"Theme": "Dark", "Language": "english", "DownloadPath": "a"}}}
{"Settings": {"Application": {"Name": "Github Clone - GUI", "Description": "Clone all repositories from a Github User", "Author": "Moises Freitas", "AuthorNickname": "Medronic", "Version": "0.0.1"}, "UI": {"Theme": "Dark", "Language": "english", "DownloadPath": "Downloads"}}}

0 comments on commit 6e808c9

Please sign in to comment.