summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEdward Thomson <ethomson@edwardthomson.com>2020-05-03 23:13:28 +0100
committerEdward Thomson <ethomson@edwardthomson.com>2022-02-26 14:43:48 -0500
commit3a3ab065f0685202c854e13708ddfd2a93d75e2c (patch)
treeb64392eaff3110848574f0877f964759811392db
parentd02f4f7ad73d91504b9c9eb096989684edbc3417 (diff)
downloadlibgit2-3a3ab065f0685202c854e13708ddfd2a93d75e2c.tar.gz
cli: infrastructure for a cli project
Introduce a command-line interface for libgit2. The goal is for it to be git-compatible. 1. The libgit2 developers can more easily dogfood libgit2 to find bugs, and performance issues. 2. There is growing usage of libgit2's examples as a client; libgit2's examples should be exactly that - simple code samples that illustrate libgit2's usage. This satisfies that need directly. 3. By producing a client ourselves, we can better understand the needs of client creators, possibly producing a shared "middleware" for commonly-used pieces of client functionality like interacting with external tools. 4. Since git is the reference implementation, we may be able to benefit from git's unit tests, running their test suite against our CLI to ensure correct behavior. This commit introduces a simple infrastructure for the CLI. The CLI is currently links libgit2 statically; this is because the utility layer is required for libgit2 _but_ shares the error state handling with libgit2 itself. There's no obviously good solution here without introducing annoying indirection or more complexity. Until we can untangle that dependency, this is a good step forward. In the meantime, we link the libgit2 object files, but we do not include the (private) libgit2 headers. This constrains the CLI to the public libgit2 interfaces.
-rw-r--r--CMakeLists.txt1
-rw-r--r--src/CMakeLists.txt4
-rw-r--r--src/README.md2
-rw-r--r--src/cli/CMakeLists.txt53
-rw-r--r--src/cli/README.md3
-rw-r--r--src/cli/cli.h18
-rw-r--r--src/cli/error.h51
-rw-r--r--src/cli/main.c51
-rw-r--r--src/cli/opt.c750
-rw-r--r--src/cli/opt.h362
-rw-r--r--src/cli/win32/precompiled.c1
-rw-r--r--src/cli/win32/precompiled.h3
12 files changed, 1299 insertions, 0 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 90ecc92fe..763bd437b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -18,6 +18,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake")
# Optional subsystems
option(BUILD_SHARED_LIBS "Build Shared Library (OFF for Static)" ON)
option(BUILD_TESTS "Build Tests using the Clar suite" ON)
+option(BUILD_CLI "Build the command-line interface" ON)
option(BUILD_EXAMPLES "Build library usage example apps" OFF)
option(BUILD_FUZZERS "Build the fuzz targets" OFF)
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 8b0d7f443..72ec410fc 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -178,6 +178,10 @@ configure_file(features.h.in git2/sys/features.h)
add_subdirectory(libgit2)
add_subdirectory(util)
+if(BUILD_CLI)
+ add_subdirectory(cli)
+endif()
+
# re-export these to the root so that peer projects (tests, fuzzers,
# examples) can use them
set(LIBGIT2_INCLUDES ${LIBGIT2_INCLUDES} PARENT_SCOPE)
diff --git a/src/README.md b/src/README.md
index 12e0d0e43..10b86c1dc 100644
--- a/src/README.md
+++ b/src/README.md
@@ -3,6 +3,8 @@
This is the source that makes up the core of libgit2 and its related
projects.
+* `cli`
+ A git-compatible command-line interface that uses libgit2.
* `libgit2`
This is the libgit2 project, a cross-platform, linkable library
implementation of Git that you can use in your application.
diff --git a/src/cli/CMakeLists.txt b/src/cli/CMakeLists.txt
new file mode 100644
index 000000000..4f347e93f
--- /dev/null
+++ b/src/cli/CMakeLists.txt
@@ -0,0 +1,53 @@
+set(CLI_INCLUDES
+ "${libgit2_BINARY_DIR}/src"
+ "${libgit2_SOURCE_DIR}/src/util"
+ "${libgit2_SOURCE_DIR}/src/cli"
+ "${libgit2_SOURCE_DIR}/include")
+
+if(WIN32 AND NOT CYGWIN)
+ file(GLOB CLI_SRC_OS win32/*.c)
+ list(SORT CLI_SRC_OS)
+else()
+ file(GLOB CLI_SRC_OS unix/*.c)
+ list(SORT CLI_SRC_OS)
+endif()
+
+file(GLOB CLI_SRC_C *.c *.h)
+list(SORT CLI_SRC_C)
+
+#
+# The CLI currently needs to be statically linked against libgit2 because
+# the utility library uses libgit2's thread-local error buffers. TODO:
+# remove this dependency and allow us to dynamically link against libgit2.
+#
+
+if(BUILD_CLI STREQUAL "dynamic")
+ set(CLI_LIBGIT2_LIBRARY libgit2package)
+else()
+ set(CLI_LIBGIT2_OBJECTS $<TARGET_OBJECTS:libgit2>)
+endif()
+
+#
+# Compile and link the CLI
+#
+
+add_executable(git2_cli ${CLI_SRC_C} ${CLI_SRC_OS} ${CLI_OBJECTS}
+ $<TARGET_OBJECTS:util>
+ ${CLI_LIBGIT2_OBJECTS}
+ ${LIBGIT2_DEPENDENCY_OBJECTS})
+target_link_libraries(git2_cli ${CLI_LIBGIT2_LIBRARY} ${LIBGIT2_SYSTEM_LIBS})
+
+set_target_properties(git2_cli PROPERTIES C_STANDARD 90)
+set_target_properties(git2_cli PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${libgit2_BINARY_DIR})
+
+ide_split_sources(git2_cli)
+
+target_include_directories(git2_cli PRIVATE ${CLI_INCLUDES})
+
+if(MSVC_IDE)
+ # Precompiled headers
+ set_target_properties(git2_cli PROPERTIES COMPILE_FLAGS "/Yuprecompiled.h /FIprecompiled.h")
+ set_source_files_properties(win32/precompiled.c COMPILE_FLAGS "/Ycprecompiled.h")
+endif()
+
+install(TARGETS git2_cli RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
diff --git a/src/cli/README.md b/src/cli/README.md
new file mode 100644
index 000000000..eefd2ff27
--- /dev/null
+++ b/src/cli/README.md
@@ -0,0 +1,3 @@
+# cli
+
+A git-compatible command-line interface that uses libgit2.
diff --git a/src/cli/cli.h b/src/cli/cli.h
new file mode 100644
index 000000000..a27081d87
--- /dev/null
+++ b/src/cli/cli.h
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+
+#ifndef CLI_cli_h__
+#define CLI_cli_h__
+
+#define PROGRAM_NAME "git2"
+
+#include "git2_util.h"
+
+#include "error.h"
+#include "opt.h"
+
+#endif /* CLI_cli_h__ */
diff --git a/src/cli/error.h b/src/cli/error.h
new file mode 100644
index 000000000..cce7a54c0
--- /dev/null
+++ b/src/cli/error.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+
+#ifndef CLI_error_h__
+#define CLI_error_h__
+
+#include "cli.h"
+#include <stdio.h>
+
+#define CLI_EXIT_OK 0
+#define CLI_EXIT_ERROR 1
+#define CLI_EXIT_OS 128
+#define CLI_EXIT_GIT 128
+#define CLI_EXIT_USAGE 129
+
+#define cli_error__print(fmt) do { \
+ va_list ap; \
+ va_start(ap, fmt); \
+ fprintf(stderr, "%s: ", PROGRAM_NAME); \
+ vfprintf(stderr, fmt, ap); \
+ fprintf(stderr, "\n"); \
+ va_end(ap); \
+ } while(0)
+
+GIT_INLINE(int) cli_error(const char *fmt, ...)
+{
+ cli_error__print(fmt);
+ return CLI_EXIT_ERROR;
+}
+
+GIT_INLINE(int) cli_error_usage(const char *fmt, ...)
+{
+ cli_error__print(fmt);
+ return CLI_EXIT_USAGE;
+}
+
+GIT_INLINE(int) cli_error_git(void)
+{
+ const git_error *err = git_error_last();
+ fprintf(stderr, "%s: %s\n", PROGRAM_NAME,
+ err ? err->message : "unknown error");
+ return CLI_EXIT_GIT;
+}
+
+#define cli_error_os() (perror(PROGRAM_NAME), CLI_EXIT_OS)
+
+#endif /* CLI_error_h__ */
diff --git a/src/cli/main.c b/src/cli/main.c
new file mode 100644
index 000000000..709f6b452
--- /dev/null
+++ b/src/cli/main.c
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) the libgit2 contributors. All rights reserved.
+ *
+ * This file is part of libgit2, distributed under the GNU GPL v2 with
+ * a Linking Exception. For full terms see the included COPYING file.
+ */
+
+#include <stdio.h>
+#include <git2.h>
+#include "cli.h"
+
+static int show_version = 0;
+
+static const cli_opt_spec common_opts[] = {
+ { CLI_OPT_TYPE_SWITCH, "version", 0, &show_version, 1,
+ CLI_OPT_USAGE_DEFAULT, NULL, "display the version" },
+ { 0 }
+};
+
+int main(int argc, char **argv)
+{
+ cli_opt_parser optparser;
+ cli_opt opt;
+ int ret = 0;
+
+ if (git_libgit2_init() < 0) {
+ cli_error("failed to initialize libgit2");
+ exit(CLI_EXIT_GIT);
+ }
+
+ cli_opt_parser_init(&optparser, common_opts, argv + 1, argc - 1, CLI_OPT_PARSE_GNU);
+
+ /* Parse the top-level (common) options and command information */
+ while (cli_opt_parser_next(&opt, &optparser)) {
+ if (!opt.spec) {
+ cli_opt_status_fprint(stderr, PROGRAM_NAME, &opt);
+ cli_opt_usage_fprint(stderr, PROGRAM_NAME, common_opts);
+ ret = CLI_EXIT_USAGE;
+ goto done;
+ }
+ }
+
+ if (show_version) {
+ printf("%s version %s\n", PROGRAM_NAME, LIBGIT2_VERSION);
+ goto done;
+ }
+
+done:
+ git_libgit2_shutdown();
+ return ret;
+}
diff --git a/src/cli/opt.c b/src/cli/opt.c
new file mode 100644
index 000000000..11faa92c5
--- /dev/null
+++ b/src/cli/opt.c
@@ -0,0 +1,750 @@
+/*
+ * Copyright (c), Edward Thomson <ethomson@edwardthomson.com>
+ * All rights reserved.
+ *
+ * This file is part of adopt, distributed under the MIT license.
+ * For full terms and conditions, see the included LICENSE file.
+ *
+ * THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT.
+ *
+ * This file was produced by using the `rename.pl` script included with
+ * adopt. The command-line specified was:
+ *
+ * ./rename.pl cli_opt --filename=opt --include=cli.h --inline=GIT_INLINE --header-guard=CLI_opt_h__ --lowercase-status
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <limits.h>
+#include <assert.h>
+
+#include "cli.h"
+#include "opt.h"
+
+#ifdef _WIN32
+# include <Windows.h>
+#else
+# include <fcntl.h>
+# include <sys/ioctl.h>
+#endif
+
+#ifdef _MSC_VER
+# define alloca _alloca
+#endif
+
+#define spec_is_option_type(x) \
+ ((x)->type == CLI_OPT_TYPE_BOOL || \
+ (x)->type == CLI_OPT_TYPE_SWITCH || \
+ (x)->type == CLI_OPT_TYPE_VALUE)
+
+GIT_INLINE(const cli_opt_spec *) spec_for_long(
+ int *is_negated,
+ int *has_value,
+ const char **value,
+ const cli_opt_parser *parser,
+ const char *arg)
+{
+ const cli_opt_spec *spec;
+ char *eql;
+ size_t eql_pos;
+
+ eql = strchr(arg, '=');
+ eql_pos = (eql = strchr(arg, '=')) ? (size_t)(eql - arg) : strlen(arg);
+
+ for (spec = parser->specs; spec->type; ++spec) {
+ /* Handle -- (everything after this is literal) */
+ if (spec->type == CLI_OPT_TYPE_LITERAL && arg[0] == '\0')
+ return spec;
+
+ /* Handle --no-option arguments for bool types */
+ if (spec->type == CLI_OPT_TYPE_BOOL &&
+ strncmp(arg, "no-", 3) == 0 &&
+ strcmp(arg + 3, spec->name) == 0) {
+ *is_negated = 1;
+ return spec;
+ }
+
+ /* Handle the typical --option arguments */
+ if (spec_is_option_type(spec) &&
+ spec->name &&
+ strcmp(arg, spec->name) == 0)
+ return spec;
+
+ /* Handle --option=value arguments */
+ if (spec->type == CLI_OPT_TYPE_VALUE &&
+ eql &&
+ strncmp(arg, spec->name, eql_pos) == 0 &&
+ spec->name[eql_pos] == '\0') {
+ *has_value = 1;
+ *value = arg[eql_pos + 1] ? &arg[eql_pos + 1] : NULL;
+ return spec;
+ }
+ }
+
+ return NULL;
+}
+
+GIT_INLINE(const cli_opt_spec *) spec_for_short(
+ const char **value,
+ const cli_opt_parser *parser,
+ const char *arg)
+{
+ const cli_opt_spec *spec;
+
+ for (spec = parser->specs; spec->type; ++spec) {
+ /* Handle -svalue short options with a value */
+ if (spec->type == CLI_OPT_TYPE_VALUE &&
+ arg[0] == spec->alias &&
+ arg[1] != '\0') {
+ *value = &arg[1];
+ return spec;
+ }
+
+ /* Handle typical -s short options */
+ if (arg[0] == spec->alias) {
+ *value = NULL;
+ return spec;
+ }
+ }
+
+ return NULL;
+}
+
+GIT_INLINE(const cli_opt_spec *) spec_for_arg(cli_opt_parser *parser)
+{
+ const cli_opt_spec *spec;
+ size_t args = 0;
+
+ for (spec = parser->specs; spec->type; ++spec) {
+ if (spec->type == CLI_OPT_TYPE_ARG) {
+ if (args == parser->arg_idx) {
+ parser->arg_idx++;
+ return spec;
+ }
+
+ args++;
+ }
+
+ if (spec->type == CLI_OPT_TYPE_ARGS && args == parser->arg_idx)
+ return spec;
+ }
+
+ return NULL;
+}
+
+GIT_INLINE(int) spec_is_choice(const cli_opt_spec *spec)
+{
+ return ((spec + 1)->type &&
+ ((spec + 1)->usage & CLI_OPT_USAGE_CHOICE));
+}
+
+/*
+ * If we have a choice with switches and bare arguments, and we see
+ * the switch, then we no longer expect the bare argument.
+ */
+GIT_INLINE(void) consume_choices(const cli_opt_spec *spec, cli_opt_parser *parser)
+{
+ /* back up to the beginning of the choices */
+ while (spec->type && (spec->usage & CLI_OPT_USAGE_CHOICE))
+ --spec;
+
+ if (!spec_is_choice(spec))
+ return;
+
+ do {
+ if (spec->type == CLI_OPT_TYPE_ARG)
+ parser->arg_idx++;
+ ++spec;
+ } while(spec->type && (spec->usage & CLI_OPT_USAGE_CHOICE));
+}
+
+static cli_opt_status_t parse_long(cli_opt *opt, cli_opt_parser *parser)
+{
+ const cli_opt_spec *spec;
+ char *arg = parser->args[parser->idx++];
+ const char *value = NULL;
+ int is_negated = 0, has_value = 0;
+
+ opt->arg = arg;
+
+ if ((spec = spec_for_long(&is_negated, &has_value, &value, parser, &arg[2])) == NULL) {
+ opt->spec = NULL;
+ opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
+ goto done;
+ }
+
+ opt->spec = spec;
+
+ /* Future options parsed as literal */
+ if (spec->type == CLI_OPT_TYPE_LITERAL)
+ parser->in_literal = 1;
+
+ /* --bool or --no-bool */
+ else if (spec->type == CLI_OPT_TYPE_BOOL && spec->value)
+ *((int *)spec->value) = !is_negated;
+
+ /* --accumulate */
+ else if (spec->type == CLI_OPT_TYPE_ACCUMULATOR && spec->value)
+ *((int *)spec->value) += spec->switch_value ? spec->switch_value : 1;
+
+ /* --switch */
+ else if (spec->type == CLI_OPT_TYPE_SWITCH && spec->value)
+ *((int *)spec->value) = spec->switch_value;
+
+ /* Parse values as "--foo=bar" or "--foo bar" */
+ else if (spec->type == CLI_OPT_TYPE_VALUE) {
+ if (has_value)
+ opt->value = (char *)value;
+ else if ((parser->idx + 1) <= parser->args_len)
+ opt->value = parser->args[parser->idx++];
+
+ if (spec->value)
+ *((char **)spec->value) = opt->value;
+ }
+
+ /* Required argument was not provided */
+ if (spec->type == CLI_OPT_TYPE_VALUE &&
+ !opt->value &&
+ !(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL))
+ opt->status = CLI_OPT_STATUS_MISSING_VALUE;
+ else
+ opt->status = CLI_OPT_STATUS_OK;
+
+ consume_choices(opt->spec, parser);
+
+done:
+ return opt->status;
+}
+
+static cli_opt_status_t parse_short(cli_opt *opt, cli_opt_parser *parser)
+{
+ const cli_opt_spec *spec;
+ char *arg = parser->args[parser->idx++];
+ const char *value;
+
+ opt->arg = arg;
+
+ if ((spec = spec_for_short(&value, parser, &arg[1 + parser->in_short])) == NULL) {
+ opt->spec = NULL;
+ opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
+ goto done;
+ }
+
+ opt->spec = spec;
+
+ if (spec->type == CLI_OPT_TYPE_BOOL && spec->value)
+ *((int *)spec->value) = 1;
+
+ else if (spec->type == CLI_OPT_TYPE_ACCUMULATOR && spec->value)
+ *((int *)spec->value) += spec->switch_value ? spec->switch_value : 1;
+
+ else if (spec->type == CLI_OPT_TYPE_SWITCH && spec->value)
+ *((int *)spec->value) = spec->switch_value;
+
+ /* Parse values as "-ifoo" or "-i foo" */
+ else if (spec->type == CLI_OPT_TYPE_VALUE) {
+ if (value)
+ opt->value = (char *)value;
+ else if ((parser->idx + 1) <= parser->args_len)
+ opt->value = parser->args[parser->idx++];
+
+ if (spec->value)
+ *((char **)spec->value) = opt->value;
+ }
+
+ /*
+ * Handle compressed short arguments, like "-fbcd"; see if there's
+ * another character after the one we processed. If not, advance
+ * the parser index.
+ */
+ if (spec->type != CLI_OPT_TYPE_VALUE && arg[2 + parser->in_short] != '\0') {
+ parser->in_short++;
+ parser->idx--;
+ } else {
+ parser->in_short = 0;
+ }
+
+ /* Required argument was not provided */
+ if (spec->type == CLI_OPT_TYPE_VALUE && !opt->value)
+ opt->status = CLI_OPT_STATUS_MISSING_VALUE;
+ else
+ opt->status = CLI_OPT_STATUS_OK;
+
+ consume_choices(opt->spec, parser);
+
+done:
+ return opt->status;
+}
+
+static cli_opt_status_t parse_arg(cli_opt *opt, cli_opt_parser *parser)
+{
+ const cli_opt_spec *spec = spec_for_arg(parser);
+
+ opt->spec = spec;
+ opt->arg = parser->args[parser->idx];
+
+ if (!spec) {
+ parser->idx++;
+ opt->status = CLI_OPT_STATUS_UNKNOWN_OPTION;
+ } else if (spec->type == CLI_OPT_TYPE_ARGS) {
+ if (spec->value)
+ *((char ***)spec->value) = &parser->args[parser->idx];
+
+ /*
+ * We have started a list of arguments; the remainder of
+ * given arguments need not be examined.
+ */
+ parser->in_args = (parser->args_len - parser->idx);
+ parser->idx = parser->args_len;
+ opt->args_len = parser->in_args;
+ opt->status = CLI_OPT_STATUS_OK;
+ } else {
+ if (spec->value)
+ *((char **)spec->value) = parser->args[parser->idx];
+
+ parser->idx++;
+ opt->status = CLI_OPT_STATUS_OK;
+ }
+
+ return opt->status;
+}
+
+static int support_gnu_style(unsigned int flags)
+{
+ if ((flags & CLI_OPT_PARSE_FORCE_GNU) != 0)
+ return 1;
+
+ if ((flags & CLI_OPT_PARSE_GNU) == 0)
+ return 0;
+
+ /* TODO: Windows */
+#if defined(_WIN32) && defined(UNICODE)
+ if (_wgetenv(L"POSIXLY_CORRECT") != NULL)
+ return 0;
+#else
+ if (getenv("POSIXLY_CORRECT") != NULL)
+ return 0;
+#endif
+
+ return 1;
+}
+
+void cli_opt_parser_init(
+ cli_opt_parser *parser,
+ const cli_opt_spec specs[],
+ char **args,
+ size_t args_len,
+ unsigned int flags)
+{
+ assert(parser);
+
+ memset(parser, 0x0, sizeof(cli_opt_parser));
+
+ parser->specs = specs;
+ parser->args = args;
+ parser->args_len = args_len;
+ parser->flags = flags;
+
+ parser->needs_sort = support_gnu_style(flags);
+}
+
+GIT_INLINE(const cli_opt_spec *) spec_for_sort(
+ int *needs_value,
+ const cli_opt_parser *parser,
+ const char *arg)
+{
+ int is_negated, has_value = 0;
+ const char *value;
+ const cli_opt_spec *spec = NULL;
+ size_t idx = 0;
+
+ *needs_value = 0;
+
+ if (strncmp(arg, "--", 2) == 0) {
+ spec = spec_for_long(&is_negated, &has_value, &value, parser, &arg[2]);
+ *needs_value = !has_value;
+ }
+
+ else if (strncmp(arg, "-", 1) == 0) {
+ spec = spec_for_short(&value, parser, &arg[1]);
+
+ /*
+ * Advance through compressed short arguments to see if
+ * the last one has a value, eg "-xvffilename".
+ */
+ while (spec && !value && arg[1 + ++idx] != '\0')
+ spec = spec_for_short(&value, parser, &arg[1 + idx]);
+
+ *needs_value = (value == NULL);
+ }
+
+ return spec;
+}
+
+/*
+ * Some parsers allow for handling arguments like "file1 --help file2";
+ * this is done by re-sorting the arguments in-place; emulate that.
+ */
+static int sort_gnu_style(cli_opt_parser *parser)
+{
+ size_t i, j, insert_idx = parser->idx, offset;
+ const cli_opt_spec *spec;
+ char *option, *value;
+ int needs_value, changed = 0;
+
+ parser->needs_sort = 0;
+
+ for (i = parser->idx; i < parser->args_len; i++) {
+ spec = spec_for_sort(&needs_value, parser, parser->args[i]);
+
+ /* Not a "-" or "--" prefixed option. No change. */
+ if (!spec)
+ continue;
+
+ /* A "--" alone means remaining args are literal. */
+ if (spec->type == CLI_OPT_TYPE_LITERAL)
+ break;
+
+ option = parser->args[i];
+
+ /*
+ * If the argument is a value type and doesn't already
+ * have a value (eg "--foo=bar" or "-fbar") then we need
+ * to copy the next argument as its value.
+ */
+ if (spec->type == CLI_OPT_TYPE_VALUE && needs_value) {
+ /*
+ * A required value is not provided; set parser
+ * index to this value so that we fail on it.
+ */
+ if (i + 1 >= parser->args_len) {
+ parser->idx = i;
+ return 1;
+ }
+
+ value = parser->args[i + 1];
+ offset = 1;
+ } else {
+ value = NULL;
+ offset = 0;
+ }
+
+ /* Caller error if args[0] is an option. */
+ if (i == 0)
+ return 0;
+
+ /* Shift args up one (or two) and insert the option */
+ for (j = i; j > insert_idx; j--)
+ parser->args[j + offset] = parser->args[j - 1];
+
+ parser->args[insert_idx] = option;
+
+ if (value)
+ parser->args[insert_idx + 1] = value;
+
+ insert_idx += (1 + offset);
+ i += offset;
+
+ changed = 1;
+ }
+
+ return changed;
+}
+
+cli_opt_status_t cli_opt_parser_next(cli_opt *opt, cli_opt_parser *parser)
+{
+ assert(opt && parser);
+
+ memset(opt, 0x0, sizeof(cli_opt));
+
+ if (parser->idx >= parser->args_len) {
+ opt->args_len = parser->in_args;
+ return CLI_OPT_STATUS_DONE;
+ }
+
+ /* Handle options in long form, those beginning with "--" */
+ if (strncmp(parser->args[parser->idx], "--", 2) == 0 &&
+ !parser->in_short &&
+ !parser->in_literal)
+ return parse_long(opt, parser);
+
+ /* Handle options in short form, those beginning with "-" */
+ else if (parser->in_short ||
+ (strncmp(parser->args[parser->idx], "-", 1) == 0 &&
+ !parser->in_literal))
+ return parse_short(opt, parser);
+
+ /*
+ * We've reached the first "bare" argument. In POSIX mode, all
+ * remaining items on the command line are arguments. In GNU
+ * mode, there may be long or short options after this. Sort any
+ * options up to this position then re-parse the current position.
+ */
+ if (parser->needs_sort && sort_gnu_style(parser))
+ return cli_opt_parser_next(opt, parser);
+
+ return parse_arg(opt, parser);
+}
+
+GIT_INLINE(int) spec_included(const cli_opt_spec **specs, const cli_opt_spec *spec)
+{
+ const cli_opt_spec **i;
+
+ for (i = specs; *i; ++i) {
+ if (spec == *i)
+ return 1;
+ }
+
+ return 0;
+}
+
+static cli_opt_status_t validate_required(
+ cli_opt *opt,
+ const cli_opt_spec specs[],
+ const cli_opt_spec **given_specs)
+{
+ const cli_opt_spec *spec, *required;
+ int given;
+
+ /*
+ * Iterate over the possible specs to identify requirements and
+ * ensure that those have been given on the command-line.
+ * Note that we can have required *choices*, where one in a
+ * list of choices must be specified.
+ */
+ for (spec = specs, required = NULL, given = 0; spec->type; ++spec) {
+ if (!required && (spec->usage & CLI_OPT_USAGE_REQUIRED)) {
+ required = spec;
+ given = 0;
+ } else if (!required) {
+ continue;
+ }
+
+ if (!given)
+ given = spec_included(given_specs, spec);
+
+ /*
+ * Validate the requirement unless we're in a required
+ * choice. In that case, keep the required state and
+ * validate at the end of the choice list.
+ */
+ if (!spec_is_choice(spec)) {
+ if (!given) {
+ opt->spec = required;
+ opt->status = CLI_OPT_STATUS_MISSING_ARGUMENT;
+ break;
+ }
+
+ required = NULL;
+ given = 0;
+ }
+ }
+
+ return opt->status;
+}
+
+cli_opt_status_t cli_opt_parse(
+ cli_opt *opt,
+ const cli_opt_spec specs[],
+ char **args,
+ size_t args_len,
+ unsigned int flags)
+{
+ cli_opt_parser parser;
+ const cli_opt_spec **given_specs;
+ size_t given_idx = 0;
+
+ cli_opt_parser_init(&parser, specs, args, args_len, flags);
+
+ given_specs = alloca(sizeof(const cli_opt_spec *) * (args_len + 1));
+
+ while (cli_opt_parser_next(opt, &parser)) {
+ if (opt->status != CLI_OPT_STATUS_OK &&
+ opt->status != CLI_OPT_STATUS_DONE)
+ return opt->status;
+
+ if ((opt->spec->usage & CLI_OPT_USAGE_STOP_PARSING))
+ return (opt->status = CLI_OPT_STATUS_DONE);
+
+ given_specs[given_idx++] = opt->spec;
+ }
+
+ given_specs[given_idx] = NULL;
+
+ return validate_required(opt, specs, given_specs);
+}
+
+static int spec_name_fprint(FILE *file, const cli_opt_spec *spec)
+{
+ int error;
+
+ if (spec->type == CLI_OPT_TYPE_ARG)
+ error = fprintf(file, "%s", spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_ARGS)
+ error = fprintf(file, "%s", spec->value_name);
+ else if (spec->alias && !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
+ error = fprintf(file, "-%c", spec->alias);
+ else
+ error = fprintf(file, "--%s", spec->name);
+
+ return error;
+}
+
+int cli_opt_status_fprint(
+ FILE *file,
+ const char *command,
+ const cli_opt *opt)
+{
+ const cli_opt_spec *choice;
+ int error;
+
+ if (command && (error = fprintf(file, "%s: ", command)) < 0)
+ return error;
+
+ switch (opt->status) {
+ case CLI_OPT_STATUS_DONE:
+ error = fprintf(file, "finished processing arguments (no error)\n");
+ break;
+ case CLI_OPT_STATUS_OK:
+ error = fprintf(file, "no error\n");
+ break;
+ case CLI_OPT_STATUS_UNKNOWN_OPTION:
+ error = fprintf(file, "unknown option: %s\n", opt->arg);
+ break;
+ case CLI_OPT_STATUS_MISSING_VALUE:
+ if ((error = fprintf(file, "argument '")) < 0 ||
+ (error = spec_name_fprint(file, opt->spec)) < 0 ||
+ (error = fprintf(file, "' requires a value.\n")) < 0)
+ break;
+ break;
+ case CLI_OPT_STATUS_MISSING_ARGUMENT:
+ if (spec_is_choice(opt->spec)) {
+ int is_choice = 1;
+
+ if (spec_is_choice((opt->spec)+1))
+ error = fprintf(file, "one of");
+ else
+ error = fprintf(file, "either");
+
+ if (error < 0)
+ break;
+
+ for (choice = opt->spec; is_choice; ++choice) {
+ is_choice = spec_is_choice(choice);
+
+ if (!is_choice)
+ error = fprintf(file, " or");
+ else if (choice != opt->spec)
+ error = fprintf(file, ",");
+
+ if ((error < 0) ||
+ (error = fprintf(file, " '")) < 0 ||
+ (error = spec_name_fprint(file, choice)) < 0 ||
+ (error = fprintf(file, "'")) < 0)
+ break;
+
+ if (!spec_is_choice(choice))
+ break;
+ }
+
+ if ((error < 0) ||
+ (error = fprintf(file, " is required.\n")) < 0)
+ break;
+ } else {
+ if ((error = fprintf(file, "argument '")) < 0 ||
+ (error = spec_name_fprint(file, opt->spec)) < 0 ||
+ (error = fprintf(file, "' is required.\n")) < 0)
+ break;
+ }
+
+ break;
+ default:
+ error = fprintf(file, "unknown status: %d\n", opt->status);
+ break;
+ }
+
+ return error;
+}
+
+int cli_opt_usage_fprint(
+ FILE *file,
+ const char *command,
+ const cli_opt_spec specs[])
+{
+ const cli_opt_spec *spec;
+ int choice = 0, next_choice = 0, optional = 0;
+ int error;
+
+ if ((error = fprintf(file, "usage: %s", command)) < 0)
+ goto done;
+
+ for (spec = specs; spec->type; ++spec) {
+ if (!choice)
+ optional = !(spec->usage & CLI_OPT_USAGE_REQUIRED);
+
+ next_choice = !!((spec + 1)->usage & CLI_OPT_USAGE_CHOICE);
+
+ if (spec->usage & CLI_OPT_USAGE_HIDDEN)
+ continue;
+
+ if (choice)
+ error = fprintf(file, "|");
+ else
+ error = fprintf(file, " ");
+
+ if (error < 0)
+ goto done;
+
+ if (optional && !choice && (error = fprintf(file, "[")) < 0)
+ error = fprintf(file, "[");
+ if (!optional && !choice && next_choice)
+ error = fprintf(file, "(");
+
+ if (error < 0)
+ goto done;
+
+ if (spec->type == CLI_OPT_TYPE_VALUE && spec->alias &&
+ !(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL) &&
+ !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
+ error = fprintf(file, "-%c <%s>", spec->alias, spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_VALUE && spec->alias &&
+ !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
+ error = fprintf(file, "-%c [<%s>]", spec->alias, spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_VALUE &&
+ !(spec->usage & CLI_OPT_USAGE_VALUE_OPTIONAL))
+ error = fprintf(file, "--%s[=<%s>]", spec->name, spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_VALUE)
+ error = fprintf(file, "--%s=<%s>", spec->name, spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_ARG)
+ error = fprintf(file, "<%s>", spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_ARGS)
+ error = fprintf(file, "<%s>...", spec->value_name);
+ else if (spec->type == CLI_OPT_TYPE_LITERAL)
+ error = fprintf(file, "--");
+ else if (spec->alias && !(spec->usage & CLI_OPT_USAGE_SHOW_LONG))
+ error = fprintf(file, "-%c", spec->alias);
+ else
+ error = fprintf(file, "--%s", spec->name);
+
+ if (error < 0)
+ goto done;
+
+ if (!optional && choice && !next_choice)
+ error = fprintf(file, ")");
+ else if (optional && !next_choice)
+ error = fprintf(file, "]");
+
+ if (error < 0)
+ goto done;
+
+ choice = next_choice;
+ }
+
+ error = fprintf(file, "\n");
+
+done:
+ error = (error < 0) ? -1 : 0;
+ return error;
+}
+
diff --git a/src/cli/opt.h b/src/cli/opt.h
new file mode 100644
index 000000000..f7b6b9326
--- /dev/null
+++ b/src/cli/opt.h
@@ -0,0 +1,362 @@
+/*
+ * Copyright (c), Edward Thomson <ethomson@edwardthomson.com>
+ * All rights reserved.
+ *
+ * This file is part of adopt, distributed under the MIT license.
+ * For full terms and conditions, see the included LICENSE file.
+ *
+ * THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT.
+ *
+ * This file was produced by using the `rename.pl` script included with
+ * adopt. The command-line specified was:
+ *
+ * ./rename.pl cli_opt --filename=opt --include=cli.h --inline=GIT_INLINE --header-guard=CLI_opt_h__ --lowercase-status
+ */
+
+#ifndef CLI_opt_h__
+#define CLI_opt_h__
+
+#include <stdio.h>
+#include <stdint.h>
+
+/**
+ * The type of argument to be parsed.
+ */
+typedef enum {
+ CLI_OPT_TYPE_NONE = 0,
+
+ /**
+ * An option that, when specified, sets a given value to true.
+ * This is useful for options like "--debug". A negation
+ * option (beginning with "no-") is implicitly specified; for
+ * example "--no-debug". The `value` pointer in the returned
+ * option will be set to `1` when this is specified, and set to
+ * `0` when the negation "no-" option is specified.
+ */
+ CLI_OPT_TYPE_BOOL,
+
+ /**
+ * An option that, when specified, sets the given `value` pointer
+ * to the specified `switch_value`. This is useful for booleans
+ * where you do not want the implicit negation that comes with an
+ * `CLI_OPT_TYPE_BOOL`, or for switches that multiplex a value, like
+ * setting a mode. For example, `--read` may set the `value` to
+ * `MODE_READ` and `--write` may set the `value` to `MODE_WRITE`.
+ */
+ CLI_OPT_TYPE_SWITCH,
+
+ /**
+ * An option that, when specified, increments the given
+ * `value` by the given `switch_value`. This can be specified
+ * multiple times to continue to increment the `value`.
+ * (For example, "-vvv" to set verbosity to 3.)
+ */
+ CLI_OPT_TYPE_ACCUMULATOR,
+
+ /**
+ * An option that takes a value, for example `-n value`,
+ * `-nvalue`, `--name value` or `--name=value`.
+ */
+ CLI_OPT_TYPE_VALUE,
+
+ /**
+ * A bare "--" that indicates that arguments following this are
+ * literal. This allows callers to specify things that might
+ * otherwise look like options, for example to operate on a file
+ * named "-rf" then you can invoke "program -- -rf" to treat
+ * "-rf" as an argument not an option.
+ */
+ CLI_OPT_TYPE_LITERAL,
+
+ /**
+ * A single argument, not an option. When options are exhausted,
+ * arguments will be matches in the order that they're specified
+ * in the spec list. For example, if two `CLI_OPT_TYPE_ARGS` are
+ * specified, `input_file` and `output_file`, then the first bare
+ * argument on the command line will be `input_file` and the
+ * second will be `output_file`.
+ */
+ CLI_OPT_TYPE_ARG,
+
+ /**
+ * A collection of arguments. This is useful when you want to take
+ * a list of arguments, for example, multiple paths. When specified,
+ * the value will be set to the first argument in the list.
+ */
+ CLI_OPT_TYPE_ARGS,
+} cli_opt_type_t;
+
+/**
+ * Additional information about an option, including parsing
+ * restrictions and usage information to be displayed to the end-user.
+ */
+typedef enum {
+ /** Defaults for the argument. */
+ CLI_OPT_USAGE_DEFAULT = 0,
+
+ /** This argument is required. */
+ CLI_OPT_USAGE_REQUIRED = (1u << 0),
+
+ /**
+ * This is a multiple choice argument, combined with the previous
+ * argument. For example, when the previous argument is `-f` and
+ * this optional is applied to an argument of type `-b` then one
+ * of `-f` or `-b` may be specified.
+ */
+ CLI_OPT_USAGE_CHOICE = (1u << 1),
+
+ /**
+ * This argument short-circuits the remainder of parsing.
+ * Useful for arguments like `--help`.
+ */
+ CLI_OPT_USAGE_STOP_PARSING = (1u << 2),
+
+ /** The argument's value is optional ("-n" or "-n foo") */
+ CLI_OPT_USAGE_VALUE_OPTIONAL = (1u << 3),
+
+ /** This argument should not be displayed in usage. */
+ CLI_OPT_USAGE_HIDDEN = (1u << 4),
+
+ /** In usage, show the long format instead of the abbreviated format. */
+ CLI_OPT_USAGE_SHOW_LONG = (1u << 5),
+} cli_opt_usage_t;
+
+typedef enum {
+ /** Default parsing behavior. */
+ CLI_OPT_PARSE_DEFAULT = 0,
+
+ /**
+ * Parse with GNU `getopt_long` style behavior, where options can
+ * be intermixed with arguments at any position (for example,
+ * "file1 --help file2".) Like `getopt_long`, this can mutate the
+ * arguments given.
+ */
+ CLI_OPT_PARSE_GNU = (1u << 0),
+
+ /**
+ * Force GNU `getopt_long` style behavior; the `POSIXLY_CORRECT`
+ * environment variable is ignored.
+ */
+ CLI_OPT_PARSE_FORCE_GNU = (1u << 1),
+} cli_opt_flag_t;
+
+/** Specification for an available option. */
+typedef struct cli_opt_spec {
+ /** Type of option expected. */
+ cli_opt_type_t type;
+
+ /** Name of the long option. */
+ const char *name;
+
+ /** The alias is the short (one-character) option alias. */
+ const char alias;
+
+ /**
+ * If this spec is of type `CLI_OPT_TYPE_BOOL`, this is a pointer
+ * to an `int` that will be set to `1` if the option is specified.
+ *
+ * If this spec is of type `CLI_OPT_TYPE_SWITCH`, this is a pointer
+ * to an `int` that will be set to the opt's `switch_value` (below)
+ * when this option is specified.
+ *
+ * If this spec is of type `CLI_OPT_TYPE_ACCUMULATOR`, this is a
+ * pointer to an `int` that will be incremented by the opt's
+ * `switch_value` (below). If no `switch_value` is provided then
+ * the value will be incremented by 1.
+ *
+ * If this spec is of type `CLI_OPT_TYPE_VALUE`,
+ * `CLI_OPT_TYPE_VALUE_OPTIONAL`, or `CLI_OPT_TYPE_ARG`, this is
+ * a pointer to a `char *` that will be set to the value
+ * specified on the command line.
+ *
+ * If this spec is of type `CLI_OPT_TYPE_ARGS`, this is a pointer
+ * to a `char **` that will be set to the remaining values
+ * specified on the command line.
+ */
+ void *value;
+
+ /**
+ * If this spec is of type `CLI_OPT_TYPE_SWITCH`, this is the value
+ * to set in the option's `value` pointer when it is specified. If
+ * this spec is of type `CLI_OPT_TYPE_ACCUMULATOR`, this is the value
+ * to increment in the option's `value` pointer when it is
+ * specified. This is ignored for other opt types.
+ */
+ int switch_value;
+
+ /**
+ * Optional usage flags that change parsing behavior and how
+ * usage information is shown to the end-user.
+ */
+ uint32_t usage;
+
+ /**
+ * The name of the value, provided when creating usage information.
+ * This is required only for the functions that display usage
+ * information and only when a spec is of type `CLI_OPT_TYPE_VALUE,
+ * `CLI_OPT_TYPE_ARG` or `CLI_OPT_TYPE_ARGS``.
+ */
+ const char *value_name;
+
+ /**
+ * Optional short description of the option to display to the
+ * end-user. This is only used when creating usage information.
+ */
+ const char *help;
+} cli_opt_spec;
+
+/** Return value for `cli_opt_parser_next`. */
+typedef enum {
+ /** Parsing is complete; there are no more arguments. */
+ CLI_OPT_STATUS_DONE = 0,
+
+ /**
+ * This argument was parsed correctly; the `opt` structure is
+ * populated and the value pointer has been set.
+ */
+ CLI_OPT_STATUS_OK = 1,
+
+ /**
+ * The argument could not be parsed correctly, it does not match
+ * any of the specifications provided.
+ */
+ CLI_OPT_STATUS_UNKNOWN_OPTION = 2,
+
+ /**
+ * The argument matched a spec of type `CLI_OPT_VALUE`, but no value
+ * was provided.
+ */
+ CLI_OPT_STATUS_MISSING_VALUE = 3,
+
+ /** A required argument was not provided. */
+ CLI_OPT_STATUS_MISSING_ARGUMENT = 4,
+} cli_opt_status_t;
+
+/** An option provided on the command-line. */
+typedef struct cli_opt {
+ /** The status of parsing the most recent argument. */
+ cli_opt_status_t status;
+
+ /**
+ * The specification that was provided on the command-line, or
+ * `NULL` if the argument did not match an `cli_opt_spec`.
+ */
+ const cli_opt_spec *spec;
+
+ /**
+ * The argument as it was specified on the command-line, including
+ * dashes, eg, `-f` or `--foo`.
+ */
+ char *arg;
+
+ /**
+ * If the spec is of type `CLI_OPT_VALUE` or `CLI_OPT_VALUE_OPTIONAL`,
+ * this is the value provided to the argument.
+ */
+ char *value;
+
+ /**
+ * If the argument is of type `CLI_OPT_ARGS`, this is the number of
+ * arguments remaining. This value is persisted even when parsing
+ * is complete and `status` == `CLI_OPT_STATUS_DONE`.
+ */
+ size_t args_len;
+} cli_opt;
+
+/* The internal parser state. Callers should not modify this structure. */
+typedef struct cli_opt_parser {
+ const cli_opt_spec *specs;
+ char **args;
+ size_t args_len;
+ unsigned int flags;
+
+ /* Parser state */
+ size_t idx;
+ size_t arg_idx;
+ size_t in_args;
+ size_t in_short;
+ int needs_sort : 1,
+ in_literal : 1;
+} cli_opt_parser;
+
+/**
+ * Parses all the command-line arguments and updates all the options using
+ * the pointers provided. Parsing stops on any invalid argument and
+ * information about the failure will be provided in the opt argument.
+ *
+ * This is the simplest way to parse options; it handles the initialization
+ * (`parser_init`) and looping (`parser_next`).
+ *
+ * @param opt The The `cli_opt` information that failed parsing
+ * @param specs A NULL-terminated array of `cli_opt_spec`s that can be parsed
+ * @param args The arguments that will be parsed
+ * @param args_len The length of arguments to be parsed
+ * @param flags The `cli_opt_flag_t flags for parsing
+ */
+cli_opt_status_t cli_opt_parse(
+ cli_opt *opt,
+ const cli_opt_spec specs[],
+ char **args,
+ size_t args_len,
+ unsigned int flags);
+
+/**
+ * Initializes a parser that parses the given arguments according to the
+ * given specifications.
+ *
+ * @param parser The `cli_opt_parser` that will be initialized
+ * @param specs A NULL-terminated array of `cli_opt_spec`s that can be parsed
+ * @param args The arguments that will be parsed
+ * @param args_len The length of arguments to be parsed
+ * @param flags The `cli_opt_flag_t flags for parsing
+ */
+void cli_opt_parser_init(
+ cli_opt_parser *parser,
+ const cli_opt_spec specs[],
+ char **args,
+ size_t args_len,
+ unsigned int flags);
+
+/**
+ * Parses the next command-line argument and places the information about
+ * the argument into the given `opt` data.
+ *
+ * @param opt The `cli_opt` information parsed from the argument
+ * @param parser An `cli_opt_parser` that has been initialized with
+ * `cli_opt_parser_init`
+ * @return true if the caller should continue iterating, or 0 if there are
+ * no arguments left to process.
+ */
+cli_opt_status_t cli_opt_parser_next(
+ cli_opt *opt,
+ cli_opt_parser *parser);
+
+/**
+ * Prints the status after parsing the most recent argument. This is
+ * useful for printing an error message when an unknown argument was
+ * specified, or when an argument was specified without a value.
+ *
+ * @param file The file to print information to
+ * @param command The name of the command to use when printing (optional)
+ * @param opt The option that failed to parse
+ * @return 0 on success, -1 on failure
+ */
+int cli_opt_status_fprint(
+ FILE *file,
+ const char *command,
+ const cli_opt *opt);
+
+/**
+ * Prints usage information to the given file handle.
+ *
+ * @param file The file to print information to
+ * @param command The name of the command to use when printing
+ * @param specs The specifications allowed by the command
+ * @return 0 on success, -1 on failure
+ */
+int cli_opt_usage_fprint(
+ FILE *file,
+ const char *command,
+ const cli_opt_spec specs[]);
+
+#endif /* CLI_opt_h__ */
diff --git a/src/cli/win32/precompiled.c b/src/cli/win32/precompiled.c
new file mode 100644
index 000000000..5f656a45d
--- /dev/null
+++ b/src/cli/win32/precompiled.c
@@ -0,0 +1 @@
+#include "precompiled.h"
diff --git a/src/cli/win32/precompiled.h b/src/cli/win32/precompiled.h
new file mode 100644
index 000000000..b0309b864
--- /dev/null
+++ b/src/cli/win32/precompiled.h
@@ -0,0 +1,3 @@
+#include <git2.h>
+
+#include "cli.h"