Skip to content
This repository was archived by the owner on Apr 13, 2023. It is now read-only.

Commit 0c98a44

Browse files
author
staticdev
committed
Config Manager
1 parent 4227adb commit 0c98a44

File tree

2 files changed

+78
-36
lines changed

2 files changed

+78
-36
lines changed

src/__main__.py

Lines changed: 47 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
import getpass
21
import logging
32
import sys
43
from typing import Any
54
from typing import Dict
65

76
import github
87
import inquirer
8+
import requests
9+
10+
import config_manager
911

1012

1113
# starting log
@@ -36,21 +38,21 @@ def _ignore_if_not_confirmed(answers: Dict[str, Any]) -> bool:
3638
class Manager():
3739
def __init__(self):
3840
self.github_repos = []
39-
self.selected_github_repos = []
40-
self.github_username = getpass.getuser()
4141
self.github_connection = None
42+
self.config_manager = config_manager.ConfigManager()
43+
self.configs = self.config_manager.load_configs()
4244

43-
def issue_create(self) -> None:
45+
def create_issues(self) -> None:
4446
questions = [
4547
inquirer.Text('title', message='Write an issue title', validate=_not_empty_validation),
4648
inquirer.Text('body', message='Write an issue body [optional]'),
4749
inquirer.Text('labels', message='Write issue labels separated by comma [optional]'),
48-
inquirer.Confirm('correct', message='Confirm creation of issue for the project(s) {}. Continue?'.format(self.selected_github_repos), default=False),
50+
inquirer.Confirm('correct', message='Confirm creation of issue for the project(s) {}. Continue?'.format(self.configs.github_selected_repos), default=False),
4951
]
5052
answers = inquirer.prompt(questions)
51-
labels = [label.strip() for label in answers['labels'].split(",")]
53+
labels = [label.strip() for label in answers['labels'].split(",")] if answers['labels'] else []
5254
if answers['correct']:
53-
for github_repo in self.selected_github_repos:
55+
for github_repo in self.configs.github_selected_repos:
5456
repo = self.github_connection.get_repo(github_repo)
5557
try:
5658
repo.create_issue(title=answers['title'], body=answers['body'], labels=labels)
@@ -61,7 +63,7 @@ def issue_create(self) -> None:
6163
else:
6264
print("{}: {}.".format(github_repo, github_exception.data["message"]))
6365

64-
def pull_request_create(self) -> None:
66+
def create_pull_requests(self) -> None:
6567
# TODO create issue for github to add labels to their API
6668
questions = [
6769
inquirer.Text('base', message='Write base branch name (destination)', default="master", validate=_not_empty_validation),
@@ -71,12 +73,12 @@ def pull_request_create(self) -> None:
7173
inquirer.Confirm('draft', message='Do you want to create a draft pull request?', default=False),
7274
inquirer.Confirm('confirmation', message='Do you want to link pull request to issues by title?', default=False),
7375
inquirer.Text('link', message='Write issue title (or part of it)', validate=_not_empty_validation, ignore=_ignore_if_not_confirmed),
74-
inquirer.Confirm('correct', message='Confirm creation of pull request(s) for the project(s) {}. Continue?'.format(self.selected_github_repos), default=False)
76+
inquirer.Confirm('correct', message='Confirm creation of pull request(s) for the project(s) {}. Continue?'.format(self.configs.github_selected_repos), default=False)
7577
]
7678
answers = inquirer.prompt(questions)
7779
if answers['correct']:
7880
body = answers['body']
79-
for github_repo in self.selected_github_repos:
81+
for github_repo in self.configs.github_selected_repos:
8082
repo = self.github_connection.get_repo(github_repo)
8183
# link issues
8284
if answers['confirmation']:
@@ -100,14 +102,14 @@ def pull_request_create(self) -> None:
100102
extra += "Invalid field {}. ".format(error["field"])
101103
print("{}: {}. {}".format(github_repo, github_exception.data["message"], extra))
102104

103-
def pull_request_merge(self) -> None:
105+
def merge_pull_requests(self) -> None:
104106
"""Merge pull request."""
105107
state = "open"
106108
questions = [
107109
inquirer.Text('base', message='Write base branch name (destination)', default="master", validate=_not_empty_validation),
108110
inquirer.Text('head', message='Write the head branch name (source)', validate=_not_empty_validation),
109111
inquirer.Text('prefix', message='Write base user or organization name from PR head', default=self.github_username, validate=_not_empty_validation),
110-
inquirer.Confirm('correct', message='Confirm merging of pull request(s) for the project(s) {}. Continue?'.format(self.selected_github_repos), default=False)
112+
inquirer.Confirm('correct', message='Confirm merging of pull request(s) for the project(s) {}. Continue?'.format(self.configs.github_selected_repos), default=False)
111113
]
112114
answers = inquirer.prompt(questions)
113115
# Important note: base and head arguments have different import formats.
@@ -116,7 +118,7 @@ def pull_request_merge(self) -> None:
116118
head = "{}:{}".format(answers["prefix"], answers["head"])
117119

118120
if answers['correct']:
119-
for github_repo in self.selected_github_repos:
121+
for github_repo in self.configs.github_selected_repos:
120122
repo = self.github_connection.get_repo(github_repo)
121123
pulls = repo.get_pulls(state=state, base=answers['base'], head=head)
122124
if pulls.totalCount == 1:
@@ -132,14 +134,14 @@ def pull_request_merge(self) -> None:
132134
else:
133135
print("{}: no open PR found for {}:{}.".format(github_repo, answers['base'], answers['head']))
134136

135-
def branch_delete(self):
137+
def delete_branches(self):
136138
questions = [
137139
inquirer.Text('branch', message='Write the branch name', validate=_not_empty_validation),
138-
inquirer.Confirm('correct', message='Confirm deleting of branch(es) for the project(s) {}. Continue?'.format(self.selected_github_repos), default=False)
140+
inquirer.Confirm('correct', message='Confirm deleting of branch(es) for the project(s) {}. Continue?'.format(self.configs.github_selected_repos), default=False)
139141
]
140142
answers = inquirer.prompt(questions)
141143
if answers['correct']:
142-
for github_repo in self.selected_github_repos:
144+
for github_repo in self.configs.github_selected_repos:
143145
repo = self.github_connection.get_repo(github_repo)
144146
try:
145147
branch = repo.get_branch(branch=answers['branch'])
@@ -148,37 +150,45 @@ def branch_delete(self):
148150
except github.GithubException as github_exception:
149151
print("{}: {}.".format(github_repo, github_exception.data["message"]))
150152

151-
def github_connect(self):
152-
print("We are going to connect to GitHub")
153+
def connect_github(self):
153154
questions = [
154-
inquirer.Text('github_username', message='GitHub username', default=self.github_username, validate=_not_empty_validation),
155-
inquirer.Password('github_access_token', message='GitHub access token', validate=_not_empty_validation),
155+
# inquirer.Text('github_username', message='GitHub username', default=self.github_username, validate=_not_empty_validation),
156+
inquirer.Password('github_access_token', message='GitHub access token', validate=_not_empty_validation, default=self.configs.github_access_token),
156157
inquirer.Text('github_hostname', message='GitHub hostname (change ONLY if you use GitHub Enterprise)'),
157158
]
158159
answers = inquirer.prompt(questions)
159-
self.github_username = answers["github_username"]
160-
access_token = answers["github_access_token"].strip()
160+
self.configs.github_access_token = answers["github_access_token"].strip()
161161
# GitHub Enterprise
162162
if answers["github_hostname"]:
163163
base_url = "https://{}/api/v3".format(answers["github_hostname"])
164-
self.github_connection = github.Github(base_url=base_url, login_or_token=access_token)
164+
self.github_connection = github.Github(base_url=base_url, login_or_token=self.configs.github_access_token)
165165
# GitHub.com
166166
else:
167-
self.github_connection = github.Github(access_token)
167+
self.github_connection = github.Github(self.configs.github_access_token)
168168
user = self.github_connection.get_user()
169+
try:
170+
self.github_username = user.login
171+
except (github.BadCredentialsException, github.GithubException):
172+
print("Wrong GitHub token/permissions. Please try again.")
173+
return self.connect_github()
174+
except requests.exceptions.ConnectionError:
175+
sys.exit("Unable to reach server. Please check you network.")
169176
self.github_repos = user.get_repos()
170-
self.github_repos_select()
177+
self.select_github_repos()
178+
179+
def select_github_repos(self) -> None:
180+
if self.configs.github_selected_repos:
181+
print("\nThe configured repos will be used:")
182+
for repo in self.configs.github_selected_repos:
183+
print(" *", repo)
184+
answer = inquirer.prompt([inquirer.Confirm('', message="Deseja selecionar novas áreas de projeto?")])['']
185+
if not answer:
186+
return self.create_issues()
171187

172-
def github_repos_select(self):
173188
try:
174189
repo_names = [repo.full_name for repo in self.github_repos]
175-
except github.BadCredentialsException:
176-
print("Wrong GitHub credentials. Please try again.")
177-
return self.github_connect()
178-
except github.GithubException as github_exception:
179-
LOGGER.exception(github_exception)
180-
print("Wrong GitHub token/permissions. Please try again.")
181-
return self.github_connect()
190+
except Exception as ex:
191+
print(ex)
182192

183193
while True:
184194
selected = inquirer.prompt([inquirer.Checkbox("github_repos",
@@ -190,13 +200,14 @@ def github_repos_select(self):
190200
else:
191201
break
192202

193-
self.selected_github_repos = selected
194-
self.issue_create()
203+
self.configs.github_selected_repos = selected
204+
self.config_manager.save_configs(self.configs)
205+
return self.create_issues()
195206

196207

197208
def main():
198209
manager = Manager()
199-
manager.github_connect()
210+
manager.connect_github()
200211

201212

202213
if __name__ == "__main__":

src/config_manager.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import collections
2+
import os
3+
import yaml
4+
from typing import List
5+
6+
7+
class Config:
8+
def __init__(self, github_access_token: str = "", github_selected_repos: List[str] = [""]):
9+
self.github_access_token = github_access_token
10+
self.github_selected_repos = github_selected_repos
11+
12+
13+
class ConfigManager:
14+
CONFIG_FOLDER = os.path.join(os.path.expanduser("~"), ".gitp")
15+
CONFIG_FILE = "config.yaml"
16+
17+
def load_configs(self) -> Config:
18+
if os.path.exists(os.path.join(self.CONFIG_FOLDER, self.CONFIG_FILE)):
19+
print("Loading previous configs\n")
20+
with open(os.path.join(self.CONFIG_FOLDER, self.CONFIG_FILE)) as config_file:
21+
data = yaml.load(config_file)
22+
return Config(**data)
23+
os.system(f"mkdir -p {self.CONFIG_FOLDER}")
24+
return Config()
25+
26+
def save_configs(self, configs: Config):
27+
configs_dict = vars(configs)
28+
with open(
29+
os.path.join(self.CONFIG_FOLDER, self.CONFIG_FILE), "w"
30+
) as config_file:
31+
yaml.dump(configs_dict, config_file)

0 commit comments

Comments
 (0)