Skip to content

Commit c8a1c5e

Browse files
authored
Merge pull request #261 from jakub-nt/_minor-code-improvements-2
Code quality improvements
2 parents a252d8d + 79933af commit c8a1c5e

File tree

5 files changed

+82
-60
lines changed

5 files changed

+82
-60
lines changed

cfbs/args.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class ArgsTypesNamespace(argparse.Namespace):
2020
check: bool
2121
checksum: Union[str, None]
2222
keep_order: bool
23-
git: Union[str, None]
23+
git: Union[bool, None]
2424
git_user_name: Union[str, None]
2525
git_user_email: Union[str, None]
2626
git_commit_message: Union[str, None]
@@ -63,6 +63,21 @@ def get_manual():
6363
raise CFBSExitError("Manual file does not exist")
6464

6565

66+
def yesno_to_bool(s: str):
67+
if s == "yes":
68+
return True
69+
if s == "no":
70+
return False
71+
assert False
72+
73+
74+
class YesNoToBool(argparse.Action):
75+
def __call__(self, parser, namespace, values, option_string=None):
76+
assert type(values) is str
77+
values = yesno_to_bool(values)
78+
setattr(namespace, self.dest, values)
79+
80+
6681
@cache
6782
def get_arg_parser():
6883
command_list = commands.get_command_names()
@@ -116,6 +131,7 @@ def get_arg_parser():
116131
parser.add_argument(
117132
"--git",
118133
choices=("yes", "no"),
134+
action=YesNoToBool,
119135
help="Override git option in cfbs.json",
120136
)
121137
parser.add_argument(

cfbs/commands.py

Lines changed: 24 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,8 @@ def search_command(terms: List[str]) -> int:
100100
)
101101
from cfbs.index import _VERSION_INDEX, Index
102102
from cfbs.git import (
103-
git_exists,
103+
git_configure_and_initialize,
104104
is_git_repo,
105-
git_get_config,
106-
git_set_config,
107-
git_init,
108105
CFBSGitError,
109106
ls_remote,
110107
)
@@ -169,11 +166,16 @@ def pretty_command(filenames: list, check: bool, keep_order: bool) -> int:
169166

170167

171168
@cfbs_command("init")
172-
def init_command(index=None, masterfiles=None, non_interactive=False) -> int:
169+
def init_command(
170+
index=None,
171+
masterfiles=None,
172+
non_interactive=False,
173+
use_git: Union[bool, None] = None,
174+
) -> int:
173175
if is_cfbs_repo():
174176
raise CFBSUserError("Already initialized - look at %s" % cfbs_filename())
175177

176-
name = prompt_user(
178+
project_name = prompt_user(
177179
non_interactive,
178180
"Please enter the name of this CFEngine Build project",
179181
default="Example project",
@@ -186,7 +188,7 @@ def init_command(index=None, masterfiles=None, non_interactive=False) -> int:
186188

187189
config = OrderedDict(
188190
{
189-
"name": name,
191+
"name": project_name,
190192
"type": "policy-set", # TODO: Prompt whether user wants to make a module
191193
"description": description,
192194
"build": [],
@@ -195,81 +197,47 @@ def init_command(index=None, masterfiles=None, non_interactive=False) -> int:
195197
if index:
196198
config["index"] = index
197199

198-
do_git = get_args().git
199-
is_git = is_git_repo()
200-
if do_git is None:
201-
if is_git:
202-
do_git = prompt_user_yesno(
200+
if use_git is None:
201+
if is_git_repo():
202+
use_git = prompt_user_yesno(
203203
non_interactive,
204204
"This is a git repository. Do you want cfbs to make commits to it?",
205205
)
206206
else:
207-
do_git = prompt_user_yesno(
207+
use_git = prompt_user_yesno(
208208
non_interactive,
209209
"Do you want cfbs to initialize a git repository and make commits to it?",
210210
)
211-
else:
212-
assert do_git in ("yes", "no")
213-
do_git = True if do_git == "yes" else False
214-
215-
if do_git is True:
216-
if not git_exists():
217-
print("Command 'git' was not found")
218-
return 1
219211

212+
if use_git is True:
220213
user_name = get_args().git_user_name
221-
if not user_name:
222-
user_name = git_get_config("user.name")
223-
user_name = prompt_user(
224-
non_interactive,
225-
"Please enter user name to use for git commits",
226-
default=user_name or "cfbs",
227-
)
228-
229214
user_email = get_args().git_user_email
230-
if not user_email:
231-
user_email = git_get_config("user.email")
232-
node_name = os.uname().nodename
233-
user_email = prompt_user(
234-
non_interactive,
235-
"Please enter user email to use for git commits",
236-
default=user_email or ("cfbs@%s" % node_name),
237-
)
238-
239-
if not is_git:
240-
try:
241-
git_init(user_name, user_email, description)
242-
except CFBSGitError as e:
243-
print(str(e))
244-
return 1
245-
else:
246-
if not git_set_config("user.name", user_name) or not git_set_config(
247-
"user.email", user_email
248-
):
249-
print("Failed to set Git user name and email")
250-
return 1
215+
git_configure_and_initialize(
216+
user_name, user_email, non_interactive, description
217+
)
251218

252-
config["git"] = do_git
219+
config["git"] = use_git
253220

254221
data = pretty(config, CFBS_DEFAULT_SORTING_RULES) + "\n"
255222
with open(cfbs_filename(), "w") as f:
256223
f.write(data)
257224
assert is_cfbs_repo()
258225

259-
if do_git:
226+
if use_git:
260227
try:
261228
git_commit_maybe_prompt(
262229
"Initialized a new CFEngine Build project",
263230
non_interactive,
264231
[cfbs_filename()],
265232
)
266-
except CFBSGitError as e:
267-
print(str(e))
233+
except CFBSGitError:
268234
os.unlink(cfbs_filename())
269-
return 1
235+
raise
270236

271237
print(
272-
"Initialized an empty project called '{}' in '{}'".format(name, cfbs_filename())
238+
"Initialized an empty project called '{}' in '{}'".format(
239+
project_name, cfbs_filename()
240+
)
273241
)
274242

275243
"""

cfbs/git.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
from subprocess import check_call, check_output, run, PIPE, DEVNULL, CalledProcessError
1515
from typing import Iterable, Union
1616

17-
from cfbs.utils import are_paths_equal
17+
from cfbs.prompts import prompt_user
18+
from cfbs.utils import CFBSExitError, are_paths_equal
1819

1920

2021
class CFBSGitError(Exception):
@@ -115,6 +116,38 @@ def git_init(user_name=None, user_email=None, description=None, initial_branch="
115116
f.write(description + "\n")
116117

117118

119+
def git_configure_and_initialize(
120+
user_name=None, user_email=None, non_interactive=False, description=None
121+
):
122+
if not git_exists():
123+
raise CFBSExitError("Command 'git' was not found")
124+
125+
if not user_name:
126+
user_name = git_get_config("user.name")
127+
user_name = prompt_user(
128+
non_interactive,
129+
"Please enter user name to use for git commits",
130+
default=user_name or "cfbs",
131+
)
132+
133+
if not user_email:
134+
user_email = git_get_config("user.email")
135+
node_name = os.uname().nodename
136+
user_email = prompt_user(
137+
non_interactive,
138+
"Please enter user email to use for git commits",
139+
default=user_email or ("cfbs@%s" % node_name),
140+
)
141+
142+
if not is_git_repo():
143+
git_init(user_name, user_email, description)
144+
else:
145+
if not git_set_config("user.name", user_name) or not git_set_config(
146+
"user.email", user_email
147+
):
148+
raise CFBSExitError("Failed to set Git user name and email")
149+
150+
118151
def git_commit(
119152
commit_msg,
120153
edit_commit_msg=False,

cfbs/git_magic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,13 @@ def decorated_fn(*args, **kwargs):
9898
if not should_commit:
9999
return ret
100100

101-
if do_git == "yes":
101+
if do_git is True:
102102
if not is_git_repo():
103103
log.error(
104104
"Used '--git=yes' option on what appears to not be a git repository"
105105
)
106106
return ret
107-
elif do_git == "no":
107+
elif do_git is False:
108108
return ret
109109
else:
110110
assert do_git is None

cfbs/main.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import pathlib
1111
from typing import Union
1212

13+
from cfbs.git import CFBSGitError
1314
from cfbs.result import Result
1415
from cfbs.validate import validate_index_string
1516
from cfbs.version import string as version
@@ -163,6 +164,7 @@ def _main() -> Union[int, Result]:
163164
index=args.index,
164165
masterfiles=args.masterfiles,
165166
non_interactive=args.non_interactive,
167+
use_git=args.git,
166168
)
167169

168170
if args.command == "search":
@@ -284,6 +286,9 @@ def main() -> int:
284286
except CFBSNetworkError as e:
285287
print("Error: " + str(e))
286288
return 1
289+
except CFBSGitError as e:
290+
print("Error: " + str(e))
291+
return 1
287292
# AssertionError and CFBSProgrammerError are not expected, print extra info:
288293
except AssertionError as e:
289294
tb = traceback.extract_tb(e.__traceback__)

0 commit comments

Comments
 (0)