Subject: [PATCH 2/4] git-init: inject some sanity to the option parser

From: Junio C Hamano <[email-masked]>
Date: Sat, 28 Feb 2009 16:03:40 -0800

The parsing loop was a mess full of side effects.

This commit separates the loop that parses and understand the options
given, and the part that makes side effects based on given options.

Signed-off-by: Junio C Hamano <[email-masked]>
---
 builtin-init-db.c |   35 ++++++++++++++++++++++++-----------
 1 files changed, 24 insertions(+), 11 deletions(-)

diff --git a/builtin-init-db.c b/builtin-init-db.c
index ee3911f..9628803 100644
--- a/builtin-init-db.c
+++ b/builtin-init-db.c
@@ -377,27 +377,40 @@ int cmd_init_db(int argc, const char **argv, const char *prefix)
 	const char *git_dir;
 	const char *template_dir = NULL;
 	unsigned int flags = 0;
+	const char *shared_given = NULL;
+	int bare_given = 0;
 	int i;
 
-	for (i = 1; i < argc; i++, argv++) {
-		const char *arg = argv[1];
+	/* Parse without side effects that is hard to undo or unparse */
+	for (i = 1; i < argc; i++) {
+		const char *arg = argv[i];
 		if (!prefixcmp(arg, "--template="))
-			template_dir = arg+11;
-		else if (!strcmp(arg, "--bare")) {
-			static char git_dir[PATH_MAX+1];
-			is_bare_repository_cfg = 1;
-			setenv(GIT_DIR_ENVIRONMENT, getcwd(git_dir,
-						sizeof(git_dir)), 0);
-		} else if (!strcmp(arg, "--shared"))
-			init_shared_repository = PERM_GROUP;
+			template_dir = arg + 11;
+		else if (!strcmp(arg, "--bare"))
+			bare_given = 1;
+		else if (!strcmp(arg, "--shared"))
+			shared_given = "";
 		else if (!prefixcmp(arg, "--shared="))
-			init_shared_repository = git_config_perm("arg", arg+9);
+			shared_given = arg + 9;
 		else if (!strcmp(arg, "-q") || !strcmp(arg, "--quiet"))
 			flags |= INIT_DB_QUIET;
 		else
 			usage(init_db_usage);
 	}
 
+	if (bare_given) {
+		static char git_dir[PATH_MAX+1];
+		is_bare_repository_cfg = 1;
+		setenv(GIT_DIR_ENVIRONMENT,
+		       getcwd(git_dir, sizeof(git_dir)), 0);
+	}
+
+	if (shared_given)
+		init_shared_repository =
+			((!*shared_given)
+			 ? PERM_GROUP
+			 : git_config_perm("arg", shared_given));
+
 	/*
 	 * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
 	 * without --bare.  Catch the error early.
-- 
1.6.2.rc2.99.g9f3bb