diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..56e8a35 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,38 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Setup Go + uses: actions/setup-go@v2 + with: + go-version: '1.24.2' + + - name: golangci-lint + uses: golangci/golangci-lint-action@v8 + with: + version: v2.1.6 + + - name: Run testing + run: go test -v + + - name: Run the scripts + run: | + GOOS=darwin GOARCH=arm64 go build -o ./build/dist/mbx_darwin_arm64 . + GOOS=darwin GOARCH=amd64 go build -o ./build/dist/mbx_darwin_amd64 . + GOOS=linux GOARCH=amd64 go build -o ./build/dist/mbx_linux_amd64 . + GOOS=linux GOARCH=arm64 go build -o ./build/dist/mbx_linux_arm64 . + diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 0000000..f7c27d5 --- /dev/null +++ b/.tool-versions @@ -0,0 +1,2 @@ +golang 1.24.2 +golangci-lint 2.1.6 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a2d93f0..0000000 --- a/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: java - -jdk: - - oraclejdk8 - -install: true - -script: - - ./gradlew goClean goBuild diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..589a945 --- /dev/null +++ b/Makefile @@ -0,0 +1,117 @@ +# Makefile for Go Project + +# ============================================================================== +# Variables +# ============================================================================== + +# Binary name (default: name of the current directory) +BINARY_NAME = mbx + +# Output directory for the binary +BUILD_OUTPUT_DIR = ./build/dist + +# Go command +GO_CMD ?= go + +# GolangCI-Lint command +# Assumes golangci-lint is in the PATH. If not, provide the full path. +GOLANGCI_LINT_CMD ?= golangci-lint + +# Go build flags (e.g., -ldflags="-s -w" to strip symbols and debug info) +# Example: GO_BUILD_FLAGS = -ldflags="-X main.Version=1.0.0" +GO_BUILD_FLAGS ?= + +# Go test flags (e.g., -v for verbose, -race for race detector) +GO_TEST_FLAGS ?= -v + +# Packages to include in build/test etc. (default: all packages in the current module) +# Note: golangci-lint typically uses ./... by default, but we keep the variable for consistency +PACKAGES ?= ./... + +# ============================================================================== +# Targets +# ============================================================================== + +.PHONY: all build run test cover clean deps fmt lint help + +# Default target: builds the project +all: build + +# Build the Go application +# Creates the binary in the specified BUILD_OUTPUT_DIR +build: deps + @echo "==> Building $(BINARY_NAME)..." + @mkdir -p $(BUILD_OUTPUT_DIR) + $(GO_CMD) build $(GO_BUILD_FLAGS) -o $(BUILD_OUTPUT_DIR)/$(BINARY_NAME) . + +build-multi: deps + @echo "==> Building $(BINARY_NAME)..." + @mkdir -p $(BUILD_OUTPUT_DIR) + GOOS=darwin GOARCH=arm64 $(GO_CMD) build $(GO_BUILD_FLAGS) -o $(BUILD_OUTPUT_DIR)/$(BINARY_NAME)_darwin_arm64 . + GOOS=darwin GOARCH=amd64 $(GO_CMD) build $(GO_BUILD_FLAGS) -o $(BUILD_OUTPUT_DIR)/$(BINARY_NAME)_darwin_amd64 . + GOOS=linux GOARCH=amd64 $(GO_CMD) build $(GO_BUILD_FLAGS) -o $(BUILD_OUTPUT_DIR)/$(BINARY_NAME)_linux_amd64 . + GOOS=linux GOARCH=arm64 $(GO_CMD) build $(GO_BUILD_FLAGS) -o $(BUILD_OUTPUT_DIR)/$(BINARY_NAME)_linux_arm64 . + +# Run the Go application +# Assumes the main package is in the current directory or specified by PACKAGES if it's a single package +run: build + @echo "==> Running $(BINARY_NAME)..." + $(BUILD_OUTPUT_DIR)/$(BINARY_NAME) + +# Run tests +test: deps + @echo "==> Running tests..." + $(GO_CMD) test $(GO_TEST_FLAGS) $(PACKAGES) + +# Run tests with coverage report +cover: deps + @echo "==> Running tests with coverage..." + $(GO_CMD) test $(GO_TEST_FLAGS) -coverprofile=coverage.out $(PACKAGES) + @echo "==> Generating coverage report (coverage.html)..." + $(GO_CMD) tool cover -html=coverage.out -o coverage.html + +# Clean build artifacts and coverage files +clean: + @echo "==> Cleaning..." + @rm -rf $(BUILD_OUTPUT_DIR) + @rm -f coverage.out coverage.html + +# Tidy dependencies (download new, remove unused) +deps: + @echo "==> Tidying dependencies..." + $(GO_CMD) mod tidy + $(GO_CMD) mod download # Optional: ensures all deps are downloaded + +# Format Go code +fmt: + @echo "==> Formatting code..." + $(GO_CMD) fmt $(PACKAGES) + +# Run golangci-lint linter +# Assumes golangci-lint is installed (go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest) +# It will use the configuration file (.golangci.yml, .golangci.toml, or .golangci.json) if present. +lint: deps + @echo "==> Running golangci-lint..." + $(GOLANGCI_LINT_CMD) run $(PACKAGES) + +# Display help message +help: + @echo "Usage: make [target]" + @echo "" + @echo "Targets:" + @echo " all Build the application (default)" + @echo " build Compile the application" + @echo " run Compile and run the application" + @echo " test Run tests" + @echo " cover Run tests and generate HTML coverage report" + @echo " clean Remove build artifacts and coverage files" + @echo " deps Tidy and download dependencies" + @echo " fmt Format Go source code" + @echo " lint Run golangci-lint linter" + @echo " help Show this help message" + @echo "" + @echo "Variables:" + @echo " GOLANGCI_LINT_CMD Command to run golangci-lint (default: golangci-lint)" + @echo " GO_BUILD_FLAGS Flags for 'go build' (e.g., -ldflags='...') " + @echo " GO_TEST_FLAGS Flags for 'go test' (e.g., -v -race)" + @echo " PACKAGES Packages to target (default: ./...)" diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 08ee78d..0000000 --- a/build.gradle +++ /dev/null @@ -1,32 +0,0 @@ -plugins { - id 'com.github.blindpirate.gogradle' version '0.11.3' -} - -golang { - goVersion = '1.11.4' - packagePath = 'github.com/vanroy/microcli' -} - -dependencies { - golang { - build 'github.com/urfave/cli#v1.20.0' - build 'github.com/c-bata/go-prompt#v0.1.1' - build 'github.com/thoas/go-funk#0.2' - build 'github.com/go-resty/resty#v1.0' - build 'github.com/BurntSushi/toml#v0.3.0' - build 'github.com/gobwas/glob#v0.2.2' - build 'github.com/howeyc/gopass' - build 'github.com/zalando/go-keyring' - } -} - -goBuild { - targetPlatform = ['linux-amd64', 'darwin-amd64'] - outputLocation = './build/dist/mbx_${GOOS}_${GOARCH}${GOEXE}' -} - -goBuild.dependsOn goTest - -task build() {} - -build.dependsOn goBuild diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..61ecd69 --- /dev/null +++ b/go.mod @@ -0,0 +1,32 @@ +module github.com/vanroy/microcli + +go 1.24.2 + +require github.com/urfave/cli/v3 v3.3.2 + +require github.com/c-bata/go-prompt v0.2.6 + +require github.com/thoas/go-funk v0.9.3 + +require github.com/go-resty/resty/v2 v2.16.5 + +require github.com/BurntSushi/toml v1.4.0 + +require github.com/gobwas/glob v0.2.2 + +require github.com/zalando/go-keyring v0.2.6 + +require golang.org/x/term v0.31.0 + +require ( + al.essio.dev/pkg/shellescape v1.5.1 // indirect + github.com/danieljoos/wincred v1.2.2 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/mattn/go-colorable v0.1.7 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/mattn/go-runewidth v0.0.9 // indirect + github.com/mattn/go-tty v0.0.3 // indirect + github.com/pkg/term v1.2.0-beta.2 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/sys v0.32.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fdf7c6a --- /dev/null +++ b/go.sum @@ -0,0 +1,67 @@ +al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho= +al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890= +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI= +github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY= +github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0= +github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM= +github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA= +github.com/gobwas/glob v0.2.2 h1:czsC5u90AkrSujyGY0l7ST7QVLEPrdoMoXxRx/hXgq0= +github.com/gobwas/glob v0.2.2/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw= +github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI= +github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0= +github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw= +github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/thoas/go-funk v0.9.3 h1:7+nAEx3kn5ZJcnDm2Bh23N2yOtweO14bi//dvRtgLpw= +github.com/thoas/go-funk v0.9.3/go.mod h1:+IWnUfUmFO1+WVYQWQtIJHeRRdaIyyYglZN7xzUPe4Q= +github.com/urfave/cli/v3 v3.3.2 h1:BYFVnhhZ8RqT38DxEYVFPPmGFTEf7tJwySTXsVRrS/o= +github.com/urfave/cli/v3 v3.3.2/go.mod h1:FJSKtM/9AiiTOJL4fJ6TbMUkxBXn7GO9guZqoZtpYpo= +github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s= +github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o= +golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw= +golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U= +golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5b902e1..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 08897df..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Fri Dec 22 18:08:38 CET 2017 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip diff --git a/gradlew b/gradlew deleted file mode 100755 index 4453cce..0000000 --- a/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save ( ) { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index f955316..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/impl/banner.go b/impl/banner.go index 42844a8..85d1a44 100644 --- a/impl/banner.go +++ b/impl/banner.go @@ -2,6 +2,7 @@ package impl import ( "fmt" + "github.com/vanroy/microcli/impl/config" ) diff --git a/impl/cmd/cmd.go b/impl/cmd/cmd.go index 49aff34..698d79a 100644 --- a/impl/cmd/cmd.go +++ b/impl/cmd/cmd.go @@ -34,5 +34,5 @@ func ExecAndOutCmd(cmdName string, cmdArgs []string) error { } func ErrorString(err string) string { - return strings.Replace(strings.TrimSuffix(err, "\n"), "\n", " ", -1) + return strings.ReplaceAll(strings.TrimSuffix(err, "\n"), "\n", " ") } diff --git a/impl/commands.go b/impl/commands.go index 0154fd7..297434b 100644 --- a/impl/commands.go +++ b/impl/commands.go @@ -1,20 +1,23 @@ package impl import ( + "context" "fmt" + "os" + "sort" + + "github.com/c-bata/go-prompt" "github.com/thoas/go-funk" - "github.com/urfave/cli" + "github.com/urfave/cli/v3" "github.com/vanroy/microcli/impl/config" "github.com/vanroy/microcli/impl/git" - "os" - "sort" ) type CliCommands map[string]cli.Command var Commands CliCommands -func InitCommands(config config.Config) []cli.Command { +func InitCommands(config config.Config) []*cli.Command { gitCommands := git.NewCommands(config) @@ -25,62 +28,85 @@ func InitCommands(config config.Config) []cli.Command { {Name: "list", Usage: "list projects on workspace", Action: gitCommands.ListLocal}, {Name: "glist", Usage: "list all remote " + labels.RepositoriesLabel + " from " + labels.GroupsLabel, Action: gitCommands.ListRemote}, - {Name: "gclone", Usage: "clone all remote " + labels.RepositoriesLabel + " from " + labels.GroupsLabel, ArgsUsage: "[glob]", Action: gitCommands.Clone}, + {Name: "gclone", Usage: "clone all remote " + labels.RepositoriesLabel + " from " + labels.GroupsLabel, ArgsUsage: "[glob]", Flags: []cli.Flag{ + &cli.StringSliceFlag{ + Name: "exclude", + Aliases: []string{"e"}, + Usage: "Pattern to exclude", + }, + }, Action: gitCommands.Clone}, {Name: "gup", Usage: "git pull + rebase all local " + labels.RepositoriesLabel, ArgsUsage: "[glob]", Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "stash, s", - Usage: "Enable autostash before pull", + &cli.BoolFlag{ + Name: "stash", + Aliases: []string{"s"}, + Usage: "Enable autostash before pull", }, }, Action: gitCommands.Up}, {Name: "gst", Usage: "show git status for all local " + labels.RepositoriesLabel, ArgsUsage: "[glob]", Action: gitCommands.St}, {Name: "ggadd", Usage: "create new " + labels.GroupLabel, ArgsUsage: labels.CreateGroupUsage, Action: gitCommands.AddGroup}, {Name: "gadd", Usage: "create new " + labels.RepositoryLabel, ArgsUsage: labels.CreateRepositoryUsage, Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "init, i", - Usage: "Init repository with Initializr", + &cli.BoolFlag{ + Name: "init", + Aliases: []string{"i"}, + Usage: "Init repository with Initializr", }, - cli.StringFlag{ - Name: "type, t", - Usage: "Project initializr type", + &cli.StringFlag{ + Name: "type", + Aliases: []string{"t"}, + Usage: "Project initializr type", }, - cli.StringFlag{ - Name: "name, n", - Usage: "Project initializr name", + &cli.StringFlag{ + Name: "name", + Aliases: []string{"n"}, + Usage: "Project initializr name", }, - cli.StringFlag{ - Name: "dependencies, d", - Usage: "Project dependencies ( separated with comma )", + &cli.StringFlag{ + Name: "dependencies", + Aliases: []string{"d"}, + Usage: "Project dependencies ( separated with comma )", }, }, Action: gitCommands.Add}, {Name: "ginit", Usage: "initialize " + labels.RepositoryLabel + " with Initializr", ArgsUsage: "repo type name dependencies", Action: gitCommands.Init}, - {Name: "exec", Usage: "execute script / action on " + labels.RepositoryLabel + "", ArgsUsage: "glob action", Flags: []cli.Flag{ - cli.BoolFlag{ - Name: "interactive, i", - Usage: "Wait manual approval after each steps", + {Name: "exec", Usage: "execute script / action on " + labels.RepositoryLabel + "", ArgsUsage: "[glob] [action]", Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "interactive", + Aliases: []string{"i"}, + Usage: "Wait manual approval after each steps", + }, + &cli.StringFlag{ + Name: "branch", + Aliases: []string{"b"}, + Usage: "Name of branch to create for execution", }, - cli.StringFlag{ - Name: "branch, b", - Usage: "Name of branch to create for execution", + &cli.StringFlag{ + Name: "commit-message", + Aliases: []string{"cm"}, + Usage: "Message of commit", }, - cli.StringFlag{ - Name: "commitMessage, cm", - Usage: "Message of commit", + &cli.BoolFlag{ + Name: "review", + Aliases: []string{"r"}, + Usage: "Enable creation of " + labels.CodeReviewRequest, }, - cli.BoolFlag{ - Name: "review, r", - Usage: "Enable creation of " + labels.CodeReviewRequest, + &cli.StringFlag{ + Name: "review-title", + Aliases: []string{"rt"}, + Usage: "Title of review use on " + labels.CodeReviewRequest, }, - cli.StringFlag{ - Name: "reviewTitle, rt", - Usage: "Title of review use on " + labels.CodeReviewRequest, + &cli.StringFlag{ + Name: "review-message", + Aliases: []string{"rm"}, + Usage: "Message of review use on " + labels.CodeReviewRequest, }, - cli.StringFlag{ - Name: "reviewMessage, rm", - Usage: "Message of review use on " + labels.CodeReviewRequest, + &cli.BoolFlag{ + Name: "review-draft", + Aliases: []string{"rd"}, + Usage: "Submit " + labels.CodeReviewRequest + " as draft", }, }, Action: gitCommands.Exec}, + {Name: "shell", Usage: "Enter in interactive shell mode", Action: displayPrompt}, {Name: "exit", Usage: "exit the prompt", Action: exitCommand}, {Name: "clear", Usage: "clear the screen", Action: clearCommand}, }, "Name").(map[string]cli.Command) @@ -88,7 +114,7 @@ func InitCommands(config config.Config) []cli.Command { return Commands.GetCliCmdArray() } -func (c *CliCommands) GetCliCmdArray() []cli.Command { +func (c *CliCommands) GetCliCmdArray() []*cli.Command { commands := funk.Values(c).([]cli.Command) @@ -96,16 +122,35 @@ func (c *CliCommands) GetCliCmdArray() []cli.Command { return commands[i].Name < commands[j].Name }) - return commands + // var cmds []*cli.Command + return funk.Map(commands, func(c cli.Command) *cli.Command { return &c }).([]*cli.Command) } -func exitCommand(c *cli.Context) error { +func exitCommand(_ context.Context, c *cli.Command) error { os.Exit(0) return nil } -func clearCommand(c *cli.Context) error { +func clearCommand(_ context.Context, c *cli.Command) error { fmt.Print("\033[2J") fmt.Printf("\033[%d;%dH", 1, 1) return nil } + +// Display interactive prompt +func displayPrompt(_ context.Context, c *cli.Command) error { + + p := prompt.New( + NexExecutor(c.Root()).Execute, + Completer, + prompt.OptionTitle("Microbox CLI"), + prompt.OptionPrefix("=> "), + prompt.OptionAddKeyBind(prompt.KeyBind{Key: prompt.ControlC, Fn: func(buffer *prompt.Buffer) { + os.Exit(1) + }}), + ) + + p.Run() + + return nil +} diff --git a/impl/completer.go b/impl/completer.go index d17e609..648c8da 100644 --- a/impl/completer.go +++ b/impl/completer.go @@ -3,7 +3,7 @@ package impl import ( "github.com/c-bata/go-prompt" "github.com/thoas/go-funk" - "github.com/urfave/cli" + "github.com/urfave/cli/v3" ) // completer returns the completion items from user input. diff --git a/impl/config/config.go b/impl/config/config.go index 2d3f12e..45cc865 100644 --- a/impl/config/config.go +++ b/impl/config/config.go @@ -3,14 +3,15 @@ package config import ( "bufio" "errors" - "github.com/BurntSushi/toml" - "github.com/zalando/go-keyring" "log" "net/url" "os" "os/user" "path/filepath" "strings" + + "github.com/BurntSushi/toml" + "github.com/zalando/go-keyring" ) const CONFIG_FILE = ".microbox/config.toml" @@ -37,6 +38,9 @@ type GitConfig struct { PrivateToken string GroupIds []string IncludeArchivedProjects bool + NormalizeName bool + CloneProtocol string + UseTokenForOperation bool } type InitializrConfig struct { @@ -61,7 +65,7 @@ func Exist() (bool, error) { func Load() (*Config, error) { - if exist, err := Exist(); exist == false { + if exist, err := Exist(); !exist { return nil, err } @@ -78,6 +82,11 @@ func Load() (*Config, error) { conf.Git.PrivateToken = getPassword(conf.Git) } + // Default to SSH clone protocol + if len(conf.Git.CloneProtocol) == 0 { + conf.Git.CloneProtocol = "ssh" + } + return &conf, nil } @@ -86,11 +95,14 @@ func Save(config Config) { configFile, _ := getConfigFile() dir := filepath.Dir(configFile) - os.Mkdir(dir, 0755) + err := os.Mkdir(dir, 0755) + if err != nil { + panic(err) + } file, _ := os.Create(configFile) - defer file.Close() + defer closeFile(file) writer := bufio.NewWriter(file) @@ -101,14 +113,17 @@ func Save(config Config) { config.Git.PrivateToken = "" } - toml.NewEncoder(writer).Encode(config) + writeError := toml.NewEncoder(writer).Encode(config) + if writeError != nil { + panic(writeError) + } } func getConfigFile() (string, error) { currentDir, err := os.Getwd() if err != nil { - return "", errors.New("Cannot retreive current dir.") + return "", errors.New("cannot retreive current dir") } return filepath.Join(currentDir, CONFIG_FILE), nil @@ -149,3 +164,10 @@ func savePassword(conf GitConfig) { } } + +func closeFile(f *os.File) { + err := f.Close() + if err != nil { + panic(err) + } +} diff --git a/impl/executor.go b/impl/executor.go index d638ec1..04b90e7 100644 --- a/impl/executor.go +++ b/impl/executor.go @@ -1,20 +1,20 @@ package impl import ( - "flag" "fmt" - "github.com/urfave/cli" "os" "strings" + + "github.com/urfave/cli/v3" ) type Executor struct { - context *cli.Context + command *cli.Command } -func NexExecutor(context *cli.Context) *Executor { +func NexExecutor(command *cli.Command) *Executor { return &Executor{ - context: context, + command: command, } } @@ -22,9 +22,10 @@ func NexExecutor(context *cli.Context) *Executor { func (e *Executor) Execute(s string) { s = strings.TrimSpace(s) - if s == "" { + switch s { + case "": return - } else if s == "quit" || s == "exit" { + case "quit", "exit": fmt.Println("Bye!") os.Exit(0) return @@ -33,13 +34,11 @@ func (e *Executor) Execute(s string) { args := strings.Split(s, " ") cmd := args[0] - cli.HandleAction(e.context.App.Command(cmd).Action, e.makeContext(args[1:])) -} - -func (e *Executor) makeContext(args []string) *cli.Context { - - flagSet := flag.NewFlagSet("cmd", flag.ContinueOnError) - flagSet.Parse(args) + command := e.command.Command(cmd) + if command != nil { + command.Action(nil, e.command) //nolint:errcheck + return + } - return cli.NewContext(e.context.App, flagSet, e.context) + e.command.CommandNotFound(nil, e.command, cmd) } diff --git a/impl/git/azure.go b/impl/git/azure.go new file mode 100644 index 0000000..91c4e7e --- /dev/null +++ b/impl/git/azure.go @@ -0,0 +1,356 @@ +package git + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/go-resty/resty/v2" + "github.com/thoas/go-funk" + "github.com/urfave/cli/v3" + "github.com/vanroy/microcli/impl/config" + "github.com/vanroy/microcli/impl/prompt" +) + +type azure struct { + config config.Config + labels Labels +} + +type azProject struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Url string `json:"url"` + State string `json:"state"` + Revision int `json:"revision"` + Visibility string `json:"visibility"` +} + +type azProjectResponse struct { + Value []azProject `json:"value"` + Count int `json:"count"` +} + +type azRepository struct { + Id string `json:"id"` + Name string `json:"name"` + Url string `json:"url"` + RemoteUrl string `json:"remoteUrl"` + SshUrl string `json:"sshUrl"` + WebUrl string `json:"webUrl"` + DefaultBranch string `json:"defaultBranch"` + Project azProject `json:"project"` +} + +type azRepositoriesResponse struct { + Value []azRepository `json:"value"` + Count int `json:"count"` +} + +type azProcess struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + IsDefault bool `json:"isDefault"` +} + +type azProcessResponse struct { + Value []azProcess `json:"value"` + Count int `json:"count"` +} + +type azCreateProject struct { + Name string `json:"name"` + Description string `json:"description"` + Capabilities azCreateProjectCapabilities `json:"capabilities"` + Visibility string `json:"visibility"` +} + +type azCreateProjectCapabilities struct { + VersionControl azCreateProjectVersionControl `json:"versioncontrol"` + ProcessTemplate azCreateProjectProcessTemplate `json:"processTemplate"` +} + +type azCreateProjectVersionControl struct { + Type string `json:"sourceControlType"` +} + +type azCreateProjectProcessTemplate struct { + Id string `json:"templateTypeId"` +} + +type azCreateProjectResponse struct { + Id string `json:"id"` + Status string `json:"status"` + Url string `json:"url"` +} + +type azCreateRepository struct { + Name string `json:"name"` + Project azCreateRepositoryProject `json:"project"` +} + +type azCreateRepositoryProject struct { + Id string `json:"id"` +} + +type azCreatePullRequest struct { + Title string `json:"title"` + Description string `json:"description"` + SourceRefName string `json:"sourceRefName"` + TargetRefName string `json:"targetRefName"` + IsDraft bool `json:"isDraft"` +} + +type azPullRequest struct { + PullRequestId int `json:"pullRequestId"` + Repository azRepository `json:"repository"` + Url string `json:"url"` + Status string `json:"status"` +} + +var azProjectVisibilities = []prompt.Option{ + {Id: "private", Name: "Private"}, + {Id: "public", Name: "Public"}, +} + +func newAzure(config config.Config) gitRemote { + return &azure{ + config: config, + labels: Labels{ + GroupLabel: "projet", + GroupsLabel: "projets", + RepositoryLabel: "repository", + RepositoriesLabel: "repositories", + CreateGroupUsage: "name [description] [visibility] [process]", + CreateRepositoryUsage: "[project] name", + CodeReviewRequest: "pull requests", + }, + } +} + +func (az *azure) getLabels() Labels { + return az.labels +} + +func (az *azure) createGroup(args cli.Args) (string, error) { + + processResp, processErr := az.execGet("_apis/process/processes?api-version=7.1", &azProcessResponse{}) + if processErr != nil { + return "", processErr + } + + var selectedProcessId = "" + var defaultProcessId = "" + processOptions := funk.Map(processResp.(*azProcessResponse).Value, func(process azProcess) prompt.Option { + var def = "" + + if args.Get(3) == process.Name { + selectedProcessId = process.Id + } + + if process.IsDefault { + def = " (default)" + defaultProcessId = process.Id + } + return prompt.Option{Id: process.Id, Name: fmt.Sprintf("%s : %s%s", process.Name, process.Description, def)} + }).([]prompt.Option) + + projectName := prompt.Input("Enter your project name :", args.Get(0)) + projectDescription := prompt.Input("\nEnter your project description :", args.Get(1)) + visibility := prompt.Choice("\nSelect your project visibility :", azProjectVisibilities, args.Get(2)) + projectProcessTemplateId := prompt.Choice("\nSelect your project process template :", processOptions, selectedProcessId) + if projectProcessTemplateId == "" { + projectProcessTemplateId = defaultProcessId + } + + prompt.PrintNewLine() + + data := azCreateProject{ + Name: projectName, + Description: projectDescription, + Visibility: visibility, + Capabilities: azCreateProjectCapabilities{ + VersionControl: azCreateProjectVersionControl{Type: "GIT"}, + ProcessTemplate: azCreateProjectProcessTemplate{Id: projectProcessTemplateId}, + }, + } + + createResp, err := az.execPost("_apis/projects?api-version=2.0-preview", data, &azCreateProjectResponse{}) + + if err != nil { + prompt.PrintErrorf("Cannot create project. ( %s )", err.Error()) + return "", err + } + + prompt.PrintInfo("Project created") + + return createResp.(*azCreateProjectResponse).Id, nil +} + +func (az *azure) createRepository(args cli.Args) (string, error) { + + groups, _ := az.getGroups() + + groups = funk.Filter(groups, func(g gitGroup) bool { return funk.ContainsString(az.config.Git.GroupIds, g.Id) }).([]gitGroup) + + idx := 0 + groupId := "" + if len(groups) == 0 { + prompt.PrintErrorf("No projects available") + return "", errors.New("no projects available") + } else if len(groups) == 1 { + groupId = groups[0].Id + } else { + defaultProjectId := "" + groupOptions := funk.Map(groups, func(group gitGroup) prompt.Option { + if args.Get(0) == group.Name { + defaultProjectId = group.Id + } + return prompt.Option{Id: group.Id, Name: group.Name} + }).([]prompt.Option) + + groupId = prompt.Choice("Select your project :", groupOptions, defaultProjectId) + idx = idx + 1 + } + + projectName := prompt.Input("\nEnter your repository name :", args.Get(idx)) + prompt.PrintNewLine() + + data := azCreateRepository{ + Name: projectName, + Project: azCreateRepositoryProject{ + Id: groupId, + }, + } + + createResp, err := az.execPost("_apis/git/repositories/?api-version=7.1", data, &azRepository{}) + + if err != nil { + prompt.PrintErrorf("Cannot create repository. ( %s )", err.Error()) + return "", err + } + + prompt.PrintInfo("Repository created") + + return createResp.(*azRepository).Id, nil +} + +func (az *azure) getGroups() ([]gitGroup, error) { + + resp, err := az.execGet("_apis/projects/?api-version=7.1", &azProjectResponse{}) + if err != nil { + return nil, err + } + + return funk.Map(resp.(*azProjectResponse).Value, az.toGitGroup).([]gitGroup), nil +} + +func (az *azure) getRepositories() ([]gitRepository, error) { + + var repos []gitRepository + + funk.ForEach(az.config.Git.GroupIds, func(groupId string) { + + resp, err := az.execGet(groupId+"/_apis/git/repositories/?api-version=7.1", &azRepositoriesResponse{}) + if err == nil { + repos = append(repos, funk.Map(resp.(*azRepositoriesResponse).Value, az.toGitRepo(groupId)).([]gitRepository)...) + } + }) + + return repos, nil +} + +func (az *azure) createReviewRequest(groupId string, repoId string, from string, into string, title string, message string, draft bool) (reviewRequest, error) { + data := azCreatePullRequest{ + Title: title, + SourceRefName: "refs/heads/" + strings.TrimPrefix(from, "refs/heads/"), + TargetRefName: "refs/heads/" + strings.TrimPrefix(into, "refs/heads/"), + Description: message, + IsDraft: draft, + } + + azReview, err := az.execPost(groupId+"/_apis/git/repositories/"+repoId+"/pullrequests?api-version=7.1", data, &azPullRequest{}) + if err != nil { + return reviewRequest{}, err + } + + return az.toReviewRequest(azReview.(*azPullRequest)), err +} + +func (az *azure) execGet(url string, resultType interface{}) (interface{}, error) { + + resp, err := resty.New().R(). + SetBasicAuth("", az.config.Git.PrivateToken). + SetResult(resultType). + Get(az.config.Git.BaseUrl + "/" + url) + + if err != nil { + prompt.PrintError(resp.String()) + } + + return resp.Result(), err +} + +func (az *azure) execPost(url string, data interface{}, resultType interface{}) (interface{}, error) { + + resp, err := resty.New().R(). + SetBasicAuth("", az.config.Git.PrivateToken). + SetResult(resultType). + SetBody(data). + Post(az.config.Git.BaseUrl + "/" + url) + + if err != nil { + return nil, err + } + + if resp.StatusCode() < 200 || resp.StatusCode() > 300 { + return nil, fmt.Errorf("cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String()) + } + + return resp.Result(), nil +} + +func (az *azure) toGitRepo(groupId string) interface{} { + + return func(repository azRepository) gitRepository { + return gitRepository{ + Id: repository.Id, + Name: repository.Name, + NameWithNamespace: repository.Project.Name + " / " + repository.Name, + Path: az.normalize(repository.Name), + PathWithNamespace: az.normalize(repository.Project.Name) + "/" + az.normalize(repository.Name), + SshUrl: repository.SshUrl, + HttpUrl: repository.RemoteUrl, + DefaultBranch: strings.TrimPrefix(repository.DefaultBranch, "refs/heads/"), + Archived: false, + GroupId: groupId, + } + } +} + +func (az *azure) toGitGroup(project azProject) gitGroup { + + return gitGroup{ + Id: project.Id, + Name: project.Name, + } +} +func (az *azure) toReviewRequest(request *azPullRequest) reviewRequest { + + return reviewRequest{ + Id: strconv.Itoa(request.PullRequestId), + Url: fmt.Sprintf("%s/pullrequest/%d", request.Repository.WebUrl, request.PullRequestId), + State: request.Status, + Mergeable: "", + } +} + +func (az *azure) normalize(name string) string { + if !az.config.Git.NormalizeName { + return name + } + return strings.ToLower(strings.ReplaceAll(name, " ", "-")) +} diff --git a/impl/git/commands.go b/impl/git/commands.go index 8a79bb6..a697aac 100644 --- a/impl/git/commands.go +++ b/impl/git/commands.go @@ -1,19 +1,22 @@ package git import ( + "context" + "encoding/base64" "fmt" - "github.com/gobwas/glob" + "os" + "path/filepath" + "sort" + "strings" + "github.com/thoas/go-funk" - "github.com/urfave/cli" + "github.com/urfave/cli/v3" "github.com/vanroy/microcli/impl/cmd" "github.com/vanroy/microcli/impl/config" "github.com/vanroy/microcli/impl/file" + "github.com/vanroy/microcli/impl/glob" "github.com/vanroy/microcli/impl/initialzr" "github.com/vanroy/microcli/impl/prompt" - "os" - "path/filepath" - "sort" - "strings" ) const ( @@ -21,6 +24,7 @@ const ( ) type GitCommands struct { + config config.Config impl gitRemote initializr *initialzr.Initializr } @@ -34,19 +38,20 @@ type GitImplement struct { var gitImplements = []GitImplement{ {Id: "github", Name: "GitHub", Impl: newGitHub}, {Id: "gitlab", Name: "GitLab", Impl: newGitLab}, - {Id: "visualstudio", Name: "VisualStudio", Impl: newVisualStudio}, + {Id: "azure", Name: "Azure DevOps", Impl: newAzure}, } func NewCommands(config config.Config) *GitCommands { return &GitCommands{ + config: config, impl: getImpl(config), initializr: initialzr.NewInitializr(config), } } // Init config -func Init(c *cli.Context) error { +func Init(_ context.Context, c *cli.Command) error { typeOptions := funk.Map(gitImplements, func(impl GitImplement) prompt.Option { return prompt.Option{Id: impl.Id, Name: impl.Name} @@ -57,7 +62,6 @@ func Init(c *cli.Context) error { gitTypeName := getImplCfg(gitType).Name baseUrl := prompt.Input(fmt.Sprintf("Enter your %s base url :", gitTypeName)) - prompt.PrintNewLine() token := prompt.Password(fmt.Sprintf("Enter your %s token :", gitTypeName)) prompt.PrintNewLine() @@ -72,11 +76,11 @@ func Init(c *cli.Context) error { impl := getImpl(tmpConfig) groups, err := impl.getGroups() if err != nil { - prompt.PrintError("Cannot retrieve %s (%s)", impl.getLabels().GroupsLabel, err.Error()) + prompt.PrintErrorf("Cannot retrieve %s (%s)", impl.getLabels().GroupsLabel, err.Error()) os.Exit(1) } if len(groups) == 0 { - prompt.PrintError("Cannot retrieve %s", impl.getLabels().GroupsLabel) + prompt.PrintErrorf("Cannot retrieve %s", impl.getLabels().GroupsLabel) os.Exit(1) } @@ -84,11 +88,32 @@ func Init(c *cli.Context) error { return prompt.Option{Id: group.Id, Name: group.Name} }).([]prompt.Option) + prompt.PrintNewLine() groupId := prompt.Choice("Select group to add on workspace :", groupOptions) prompt.PrintNewLine() tmpConfig.Git.GroupIds = []string{groupId} + protocolOptions := []prompt.Option{ + {Id: "ssh", Name: "SSH"}, + {Id: "https", Name: "HTTPS"}, + } + + protocol := prompt.Choice("Select the protocol used for cloning repositories :", protocolOptions) + prompt.PrintNewLine() + + tmpConfig.Git.CloneProtocol = protocol + + if protocol == "https" { + useTokenOpen := []prompt.Option{ + {Id: "token", Name: "Use token for GIT operation"}, + {Id: "cm", Name: "Use GIT integrated authentication ( git-credentials-manager)"}, + } + useToken := prompt.Choice("Select the protocol used for cloning repositories :", useTokenOpen) + prompt.PrintNewLine() + tmpConfig.Git.UseTokenForOperation = useToken == "token" + } + config.Save(tmpConfig) return nil @@ -100,9 +125,9 @@ func (g *GitCommands) GetLabels() Labels { } // Return list of GIT repository present in local folder -func (g *GitCommands) ListLocal(c *cli.Context) error { +func (g *GitCommands) ListLocal(_ context.Context, c *cli.Command) error { - folders, err := getGitFolders("") + folders, err := getGitFolders("", c.StringArgs("exclude")) if err != nil { return err } @@ -119,43 +144,44 @@ func (g *GitCommands) ListLocal(c *cli.Context) error { } // Return list of GIT repository present on remote server -func (g *GitCommands) ListRemote(c *cli.Context) error { +func (g *GitCommands) ListRemote(_ context.Context, c *cli.Command) error { repos, err := g.impl.getRepositories() if err != nil || len(repos) == 0 { - prompt.PrintError("No project found") + prompt.PrintErrorf("No project found") } funk.ForEach(repos, func(repo gitRepository) { - prompt.PrintItem(repo.NameWithNamespace + " ( " + strings.Replace(repo.Description, "\n", " ", -1) + " )") + prompt.PrintItem(repo.NameWithNamespace + " ( " + strings.ReplaceAll(repo.Description, "\n", " ") + " )") }) return nil } // Clone GIT repository matching with pattern -func (g *GitCommands) Clone(c *cli.Context) error { +func (g *GitCommands) Clone(_ context.Context, c *cli.Command) error { var globStr = "" if c.NArg() > 0 { globStr = c.Args().Get(0) } - _, error := g.cloneRepos(globStr, true) + _, error := g.cloneRepos(globStr, c.StringSlice("exclude"), true) return error } // PULL + REBASE all local GIT repository -func (g *GitCommands) Up(c *cli.Context) error { +func (g *GitCommands) Up(_ context.Context, c *cli.Command) error { - folders, err := getGitFolders(c.Args().Get(0)) + folders, err := getGitFolders(c.Args().Get(0), c.StringSlice("exclude")) if err != nil { return err } funk.ForEach(folders, func(folder string) { - var args = []string{"-C", file.Rel(folder), "pull", "-q", "--rebase"} + args := g.authorization() + args = append(args, []string{"-C", file.Rel(folder), "pull", "-q", "--rebase"}...) if c.Bool("stash") { args = append(args, "--autostash") } @@ -172,9 +198,9 @@ func (g *GitCommands) Up(c *cli.Context) error { } // Display status for all local GIT repository -func (g *GitCommands) St(c *cli.Context) error { +func (g *GitCommands) St(_ context.Context, c *cli.Command) error { - folders, err := getGitFolders(c.Args().Get(0)) + folders, err := getGitFolders(c.Args().Get(0), c.StringArgs("exclude")) if err != nil { return err } @@ -185,15 +211,18 @@ func (g *GitCommands) St(c *cli.Context) error { } // Add new ( group / orga / project ) on remote hosting -func (g *GitCommands) AddGroup(c *cli.Context) error { +func (g *GitCommands) AddGroup(_ context.Context, c *cli.Command) error { - g.impl.createGroup(c.Args()) + _, err := g.impl.createGroup(c.Args()) + if err != nil { + prompt.PrintErrorf("Cannot create group, error : %s", err.Error()) + } return nil } // Add new GIT repository on remote hosting -func (g *GitCommands) Add(c *cli.Context) error { +func (g *GitCommands) Add(_ context.Context, c *cli.Command) error { id, err := g.impl.createRepository(c.Args()) if err != nil { @@ -223,29 +252,35 @@ func (g *GitCommands) Add(c *cli.Context) error { repo := funk.Find(repos, func(repo gitRepository) bool { return repo.Id == id }).(gitRepository) - _, cloneErr := clone(repo.SshUrl, repo.Path) + _, cloneErr := g.clone(g.computeCloneUrl(repo), repo.Path) if cloneErr != nil { return cloneErr } // Init repo - g.initRepo(repo.Path, pType, pName, pDeps) + initErr := g.initRepo(repo.Path, pType, pName, pDeps) + if initErr != nil { + prompt.PrintErrorf("Cannot init repository, error : %s", err.Error()) + } } return nil } // Initialize existing GIT repository -func (g *GitCommands) Init(c *cli.Context) error { +func (g *GitCommands) Init(_ context.Context, c *cli.Command) error { // Init repository - g.initRepo(c.Args().Get(0), c.Args().Get(1), c.Args().Get(2), c.Args().Get(3)) + err := g.initRepo(c.Args().Get(0), c.Args().Get(1), c.Args().Get(2), c.Args().Get(3)) + if err != nil { + prompt.PrintErrorf("Cannot init repository, error : %s", err.Error()) + } return nil } // Execute scripts on repositories -func (g *GitCommands) Exec(c *cli.Context) error { +func (g *GitCommands) Exec(_ context.Context, c *cli.Command) error { pGlob := prompt.Input("\nEnter your project filter :", c.Args().Get(0)) pAction := prompt.Input("\nEnter your action name :", c.Args().Get(1)) @@ -254,32 +289,33 @@ func (g *GitCommands) Exec(c *cli.Context) error { acceptAll := false isInteractive := c.Bool("interactive") branchName := c.String("branch") - commitMessage := c.String("commitMessage") + commitMessage := c.String("commit-message") review := c.Bool("review") - reviewTitle := c.String("reviewTitle") + reviewTitle := c.String("review-title") if len(reviewTitle) == 0 { reviewTitle = commitMessage } - reviewMessage := c.String("reviewMessage") + reviewMessage := c.String("review-message") + reviewDraft := c.Bool("review-draft") pParams := []string{} - if len(c.Args()) < 2 { + if c.Args().Len() < 2 { pParams = strings.Split(prompt.Input("\nEnter your action parameters :"), " ") } else { - pParams = c.Args()[2:] + pParams = c.Args().Slice()[2:] } // Start by cloning matching repositories - repos, err := g.cloneRepos(pGlob, false) + repos, err := g.cloneRepos(pGlob, c.StringArgs("exclude"), false) if err != nil { - prompt.PrintError("Cannot clone repositories (%s)", err.Error()) + prompt.PrintErrorf("Cannot clone repositories (%s)", err.Error()) return err } pathToRepo := funk.Map(repos, func(r gitRepository) (string, gitRepository) { return r.Path, r }).(map[string]gitRepository) - folders, _ := getGitFolders(pGlob) + folders, _ := getGitFolders(pGlob, c.StringArgs("exclude")) funk.ForEach(folders, func(folder string) { repo := pathToRepo[folder] @@ -291,9 +327,9 @@ func (g *GitCommands) Exec(c *cli.Context) error { prompt.PrintInfo("Executing action for '%s'", folder) - //Cleanup ( defaultBranch ) + // Cleanup ( defaultBranch ) prompt.PrintInfo("Executing action for '%s' : %sinitializing", folder, prompt.Color(prompt.FgYellow)) - cleanup(folder, defaultBranch) + g.cleanup(folder, defaultBranch) // Check branch if required if len(branchName) > 0 { @@ -302,11 +338,12 @@ func (g *GitCommands) Exec(c *cli.Context) error { if isInteractive && !acceptAll { response := prompt.RestrictedInput("Initialization done, continue to execute?", acceptedInputs) - if response == "q" { + switch response { + case "q": os.Exit(0) - } else if response == "n" { + case "n": return - } else if response == "a" { + case "a": acceptAll = true } } @@ -315,7 +352,7 @@ func (g *GitCommands) Exec(c *cli.Context) error { prompt.PrintInfo("Executing action for '%s' : %sexecuting", folder, prompt.Color(prompt.FgYellow)) out, err := g.exec(folder, pAction, pParams) if err != nil { - prompt.PrintError("Cannot execute action for %s , error : %s \n%s", folder, err.Error(), out) + prompt.PrintErrorf("Cannot execute action for %s , error : %s \n%s", folder, err.Error(), out) return } @@ -328,7 +365,7 @@ func (g *GitCommands) Exec(c *cli.Context) error { for { response := prompt.RestrictedInput("Execution done, continue to commit?", append(acceptedInputs, "d")) if response == "y" { - break; + break } else if response == "q" { os.Exit(0) } else if response == "n" { @@ -339,7 +376,7 @@ func (g *GitCommands) Exec(c *cli.Context) error { } else if response == "d" { err := displayDiff(folder) if err != nil { - prompt.PrintError("Cannot execute diff for %s , error : %s \n", folder, err.Error()) + prompt.PrintErrorf("Cannot execute diff for %s , error : %s \n", folder, err.Error()) } } } @@ -350,35 +387,38 @@ func (g *GitCommands) Exec(c *cli.Context) error { if isInteractive && !acceptAll { response := prompt.RestrictedInput("Commit done, continue to push?", acceptedInputs) - if response == "q" { + switch response { + case "q": os.Exit(0) - } else if response == "n" { + case "n": return - } else if response == "a" { + case "a": acceptAll = true } } prompt.PrintInfo("Executing action for '%s' : %spushing", folder, prompt.Color(prompt.FgYellow)) - push(folder, branchName) + g.push(folder, branchName) if repo.Id != "" && len(branchName) > 0 && branchName != defaultBranch && review && len(reviewTitle) > 0 { if isInteractive && !acceptAll { response := prompt.RestrictedInput("Push done, continue to create "+g.GetLabels().CodeReviewRequest+"?", acceptedInputs) - if response == "q" { + + switch response { + case "q": os.Exit(0) - } else if response == "n" { + case "n": return - } else if response == "a" { + case "a": acceptAll = true } } prompt.PrintInfo("Executing action for '%s' : %screating %s", folder, prompt.Color(prompt.FgYellow), g.GetLabels().CodeReviewRequest) - review, err := g.impl.createReviewRequest(repo.GroupId, folder, branchName, defaultBranch, reviewTitle, reviewMessage) + review, err := g.impl.createReviewRequest(repo.GroupId, repo.Id, branchName, defaultBranch, reviewTitle, reviewMessage, reviewDraft) if err != nil { - prompt.PrintError("Cannot create %s for '%s' : , error : %s", g.GetLabels().CodeReviewRequest, folder, err.Error()) + prompt.PrintErrorf("Cannot create %s for '%s' : , error : %s", g.GetLabels().CodeReviewRequest, folder, err.Error()) } else { prompt.PrintInfo("Succeeded to create %s for '%s' , URL: %s%s", g.GetLabels().CodeReviewRequest, folder, prompt.Color(prompt.FgBlue), review.Url) } @@ -400,33 +440,27 @@ func (g *GitCommands) Exec(c *cli.Context) error { // Execute scripts one repository func (g *GitCommands) exec(folder string, action string, params []string) (string, error) { - dir, _ := os.Getwd() return cmd.ExecCmdDir(dir+"/.microbox/actions/"+action, params, dir+"/"+folder) } // Clone GIT repository matching with pattern -func (g *GitCommands) cloneRepos(globStr string, output bool) ([]gitRepository, error) { +func (g *GitCommands) cloneRepos(globStr string, exclusion []string, output bool) ([]gitRepository, error) { repos, err := g.impl.getRepositories() if err != nil || len(repos) == 0 { if output { - prompt.PrintError("No project found") + prompt.PrintErrorf("No project found") } } - var pattern glob.Glob - var patternString string - - if globStr != "" { - patternString = globStr - pattern = glob.MustCompile(patternString, '-', '.', '_', '/') - } + var matcher = glob.NewGlobMatcher(globStr, exclusion...) funk.ForEach(repos, func(repo gitRepository) { - if pattern != nil && !pattern.Match(repo.Path) { + match, reason := matcher.Match(repo.Path) + if !match { if output { - prompt.PrintInfo("'%s' not match with pattern '%s' %sskipping", repo.Name, patternString, prompt.Color(prompt.FgYellow)) + prompt.PrintInfo("%s %sskipping", reason, prompt.Color(prompt.FgYellow)) } return } @@ -441,8 +475,8 @@ func (g *GitCommands) cloneRepos(globStr string, output bool) ([]gitRepository, prompt.PrintInfo("'%s' not existing, %scloning%s into '%s'", repo.Name, prompt.Color(prompt.FgGreen), prompt.Color(prompt.FgWhite), repo.Path) } - if out, err := clone(repo.SshUrl, repo.Path); err != nil { - prompt.PrintError("Cannot clone ( %s )", err) + if out, err := g.clone(g.computeCloneUrl(repo), repo.Path); err != nil { + prompt.PrintErrorf("Cannot clone ( %s )", err) } else { if checkIsRepoEmptyErr(out) { if output { @@ -469,7 +503,7 @@ func (g *GitCommands) initRepo(folder string, projectType string, projectName st addAndCommit(folder, "Initial commit", false) // Push - push(folder, "") + g.push(folder, "") return nil } @@ -502,7 +536,7 @@ func (g *GitCommands) status(folder string) { } else { // Fetch from remote - fetch(folder) + g.fetch(folder) // Check for diverged branches local, remote := checkBranchOrigin(folder, currentBranch) @@ -519,21 +553,44 @@ func (g *GitCommands) status(folder string) { } } +// Compute Clone URL based on selected protocol +func (g *GitCommands) computeCloneUrl(repo gitRepository) string { + cloneProtocol := g.config.Git.CloneProtocol + switch cloneProtocol { + case "ssh": + return repo.SshUrl + case "https": + return repo.HttpUrl + default: + prompt.PrintErrorf("Invalid clone URL protocol '%s'", cloneProtocol) + os.Exit(1) + return "" + } +} + +// Compute authorization GIT parameter if required +func (g *GitCommands) authorization() []string { + + cloneProtocol := g.config.Git.CloneProtocol + usePatToken := g.config.Git.UseTokenForOperation + + if cloneProtocol != "https" || !usePatToken { + return []string{} + } + + pat := base64.StdEncoding.EncodeToString([]byte(":" + g.config.Git.PrivateToken)) + return []string{"-c", "http.extraHeader=Authorization: Basic " + pat} +} + // Return all git folders matching with glob -func getGitFolders(globPattern string) (folders []string, err error) { +func getGitFolders(globPattern string, exclusion []string) (folders []string, err error) { dir, err := os.Getwd() if err != nil { return nil, err } - var pattern glob.Glob - var patternString string - - if globPattern != "" { - patternString = globPattern - pattern = glob.MustCompile(patternString, '-', '.', '_', '/') - } + var matcher = glob.NewGlobMatcher(globPattern, exclusion...) var gitFolders []string @@ -543,9 +600,9 @@ func getGitFolders(globPattern string) (folders []string, err error) { relativePath := strings.TrimPrefix(filepath.Clean(strings.TrimPrefix(path, dir)), string(os.PathSeparator)) if strings.HasSuffix(relativePath, "/.git") { - folder := strings.TrimSuffix(relativePath, "/.git") - if pattern == nil || pattern.Match(folder) { + match, _ := matcher.Match(folder) + if match { gitFolders = append(gitFolders, folder) } } @@ -619,37 +676,33 @@ func checkBranchOrigin(folder string, branch string) (string, string) { } // Return true if files is changed and not tracked in GIT repo -func clone(sshUrl string, folder string) (string, error) { - return cmd.ExecCmd("git", []string{"clone", "-q", sshUrl, folder}) +func (g *GitCommands) clone(cloneUrl string, folder string) (string, error) { + return cmd.ExecCmd("git", append(g.authorization(), []string{"clone", "-q", cloneUrl, folder}...)) } // Return true if files is changed and not tracked in GIT repo -func fetch(folder string) { - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "fetch"}) +func (g *GitCommands) fetch(folder string) { + cmd.ExecCmd("git", append(g.authorization(), []string{"-C", file.Rel(folder), "fetch"}...)) //nolint:errcheck } // Checkout existing branch func checkout(folder string, branch string) { - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", branch}) + cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", branch}) //nolint:errcheck } // Create new branch func branch(folder string, branch string) { - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", "-B", branch}) + cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", "-B", branch}) //nolint:errcheck } // Cleanup repo and update to specified branch -func cleanup(folder string, branch string) { - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "stash", "save", "Auto-stash by microcli"}) - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", branch}) - cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "pull", "-q", "--rebase"}) +func (g *GitCommands) cleanup(folder string, branch string) { + cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "stash", "save", "Auto-stash by microcli"}) //nolint:errcheck + cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "checkout", branch}) //nolint:errcheck + cmd.ExecCmd("git", append(g.authorization(), []string{"-C", file.Rel(folder), "pull", "-q", "--rebase"}...)) //nolint:errcheck } // Show diff -func diff(folder string) (string, error) { - return cmd.ExecCmd("git", []string{"-C", file.Rel(folder), "diff"}) -} - func displayDiff(folder string) error { return cmd.ExecAndOutCmd("git", []string{"-C", file.Rel(folder), "diff"}) } @@ -675,9 +728,10 @@ func addAndCommit(folder string, comment string, onlyTracked bool) { } // Return true if files is changed and not tracked in GIT repo -func push(folder string, track string) { +func (g *GitCommands) push(folder string, track string) { - params := []string{"-C", file.Rel(folder), "push"} + params := g.authorization() + params = append(params, "-C", file.Rel(folder), "push") if len(track) > 0 { params = append(params, "-u", "origin", track) @@ -699,7 +753,7 @@ func getImpl(config config.Config) gitRemote { impl := getImplCfg(config.Git.Type) if impl == nil { - prompt.PrintError("Invalid server type '%s,'", config.Git.Type) + prompt.PrintErrorf("Invalid server type '%s,'", config.Git.Type) os.Exit(1) } @@ -709,7 +763,7 @@ func getImpl(config config.Config) gitRemote { func getImplCfg(gitType string) *GitImplement { for e := range gitImplements { - if strings.ToLower(gitImplements[e].Id) == strings.ToLower(gitType) { + if strings.EqualFold(gitImplements[e].Id, gitType) { return &gitImplements[e] } } diff --git a/impl/git/git_remote.go b/impl/git/git_remote.go index bbbd114..8b72d84 100644 --- a/impl/git/git_remote.go +++ b/impl/git/git_remote.go @@ -1,6 +1,6 @@ package git -import "github.com/urfave/cli" +import "github.com/urfave/cli/v3" type Labels struct { GroupLabel string @@ -31,9 +31,9 @@ type gitGroup struct { Name string } -var PERSONAL_GROUP = gitGroup { - Id:"PERSONAL", - Name:"Personal", +var PERSONAL_GROUP = gitGroup{ + Id: "PERSONAL", + Name: "Personal", } type reviewRequest struct { @@ -50,5 +50,5 @@ type gitRemote interface { createRepository(args cli.Args) (string, error) getGroups() ([]gitGroup, error) getRepositories() ([]gitRepository, error) - createReviewRequest(group string, folder string, from string, into string, title string, message string) (reviewRequest, error) + createReviewRequest(groupId string, repoId string, from string, into string, title string, message string, draft bool) (reviewRequest, error) } diff --git a/impl/git/github.go b/impl/git/github.go index 3e0092b..e106eb8 100644 --- a/impl/git/github.go +++ b/impl/git/github.go @@ -3,15 +3,16 @@ package git import ( "errors" "fmt" - "github.com/go-resty/resty" - "github.com/thoas/go-funk" - "github.com/urfave/cli" - "github.com/vanroy/microcli/impl/config" - "github.com/vanroy/microcli/impl/prompt" "net/url" "sort" "strconv" "strings" + + "github.com/go-resty/resty/v2" + "github.com/thoas/go-funk" + "github.com/urfave/cli/v3" + "github.com/vanroy/microcli/impl/config" + "github.com/vanroy/microcli/impl/prompt" ) type gitHub struct { @@ -67,6 +68,7 @@ type ghCreatePullRequest struct { Head string `json:"head"` Base string `json:"base"` Body string `json:"body"` + Draft bool `json:"draft"` } type ghPullRequest struct { @@ -87,9 +89,7 @@ func newGitHub(config config.Config) gitRemote { baseUrl += "api/v3" } - if strings.HasSuffix(baseUrl, "/") { - baseUrl = strings.TrimSuffix(baseUrl, "/") - } + baseUrl = strings.TrimSuffix(baseUrl, "/") return &gitHub{ config: config, @@ -119,7 +119,7 @@ func (gh *gitHub) createGroup(args cli.Args) (string, error) { prompt.PrintNewLine() if orgaLogin == "" || orgaAdminLogin == "" { - prompt.PrintError("Missing parameters, group name and group admin login are required") + prompt.PrintErrorf("Missing parameters, group name and group admin login are required") return "", errors.New("missing parameters") } @@ -131,7 +131,7 @@ func (gh *gitHub) createGroup(args cli.Args) (string, error) { createResp, err := gh.execPost("admin/organizations", data, &ghOrg{}) if err != nil { - prompt.PrintError("Cannot create organization. ( %s )", err.Error()) + prompt.PrintErrorf("Cannot create organization. ( %s )", err.Error()) return "", err } @@ -144,7 +144,7 @@ func (gh *gitHub) createGroup(args cli.Args) (string, error) { } _, err := gh.execPatch("orgs/"+orgId, descData, &ghOrg{}) if err != nil { - prompt.PrintError("Cannot create organization. ( %s )", err.Error()) + prompt.PrintErrorf("Cannot create organization. ( %s )", err.Error()) return "", err } @@ -157,14 +157,14 @@ func (gh *gitHub) createGroup(args cli.Args) (string, error) { func (gh *gitHub) createRepository(args cli.Args) (string, error) { - groups, err := gh.getGroups() + groups, _ := gh.getGroups() groups = funk.Filter(groups, func(g gitGroup) bool { return funk.ContainsString(gh.config.Git.GroupIds, g.Id) }).([]gitGroup) idx := 0 groupId := "" if len(groups) == 0 { - prompt.PrintError("No organization available") + prompt.PrintErrorf("No organization available") return "", errors.New("no organization available") } else if len(groups) == 1 { groupId = groups[0].Id @@ -185,15 +185,12 @@ func (gh *gitHub) createRepository(args cli.Args) (string, error) { projectDescription := prompt.Input("\nEnter your repository description :", args.Get(idx+1)) projectVisibility := prompt.Choice("\nSelect your repository visibility ( default: private ) :", ghVisibilityOptions, args.Get(idx+2)) - projectPrivate := true - if projectVisibility == "public" { - projectPrivate = false - } + projectPrivate := projectVisibility != "public" prompt.PrintNewLine() if groupId == "" || projectName == "" { - prompt.PrintError("Missing parameters, project name and group are required") + prompt.PrintErrorf("Missing parameters, project name and group are required") return "", errors.New("missing parameters") } @@ -205,7 +202,7 @@ func (gh *gitHub) createRepository(args cli.Args) (string, error) { createResp, err := gh.execPost(gh.getGroupBasePath(groupId)+"/repos", data, &ghRepo{}) if err != nil { - prompt.PrintError("Cannot create repository. ( %s )", err.Error()) + prompt.PrintErrorf("Cannot create repository. ( %s )", err.Error()) return "", err } @@ -262,16 +259,17 @@ func (gh *gitHub) getRepositories() ([]gitRepository, error) { return repos, nil } -func (gh *gitHub) createReviewRequest(group string, folder string, from string, into string, title string, message string) (reviewRequest, error) { +func (gh *gitHub) createReviewRequest(groupId string, repoId string, from string, into string, title string, message string, draft bool) (reviewRequest, error) { data := ghCreatePullRequest{ Title: title, Head: from, Base: into, Body: message, + Draft: draft, } - ghReview, err := gh.execPost("repos/"+group+"/"+folder+"/pulls", data, &ghPullRequest{}) + ghReview, err := gh.execPost("repos/"+groupId+"/"+repoId+"/pulls", data, &ghPullRequest{}) if err != nil { return reviewRequest{}, err } @@ -281,7 +279,7 @@ func (gh *gitHub) createReviewRequest(group string, folder string, from string, func (gh *gitHub) execGet(url string, resultType interface{}) (interface{}, int, error) { - resp, err := resty.R(). + resp, err := resty.New().R(). SetHeader("Authorization", "token "+gh.config.Git.PrivateToken). SetResult(resultType). Get(gh.apiUrl + "/" + url) @@ -297,7 +295,7 @@ func (gh *gitHub) execGet(url string, resultType interface{}) (interface{}, int, func (gh *gitHub) execPost(url string, data interface{}, resultType interface{}) (interface{}, error) { - resp, err := resty.R(). + resp, err := resty.New().R(). SetHeader("Authorization", "token "+gh.config.Git.PrivateToken). SetResult(resultType). SetBody(data). @@ -308,7 +306,7 @@ func (gh *gitHub) execPost(url string, data interface{}, resultType interface{}) } if resp.StatusCode() < 200 || resp.StatusCode() > 300 { - return nil, errors.New(fmt.Sprintf("Cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String())) + return nil, fmt.Errorf("cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String()) } return resp.Result(), nil @@ -316,7 +314,7 @@ func (gh *gitHub) execPost(url string, data interface{}, resultType interface{}) func (gh *gitHub) execPatch(url string, data interface{}, resultType interface{}) (interface{}, error) { - resp, err := resty.R(). + resp, err := resty.New().R(). SetHeader("Authorization", "token "+gh.config.Git.PrivateToken). SetResult(resultType). SetBody(data). @@ -327,7 +325,7 @@ func (gh *gitHub) execPatch(url string, data interface{}, resultType interface{} } if resp.StatusCode() < 200 || resp.StatusCode() > 300 { - return nil, errors.New(fmt.Sprintf("Cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String())) + return nil, fmt.Errorf("cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String()) } return resp.Result(), nil @@ -350,8 +348,8 @@ func (gh *gitHub) toGitRepo(groupId string) interface{} { Name: repository.Name, Description: repository.Description, NameWithNamespace: repository.NameWithNamespace, - Path: repository.Name, - PathWithNamespace: repository.NameWithNamespace, + Path: gh.normalize(repository.Name), + PathWithNamespace: gh.normalize(repository.NameWithNamespace), SshUrl: repository.SshUrl, HttpUrl: repository.HttpUrl, DefaultBranch: repository.DefaultBranch, @@ -375,14 +373,10 @@ func (gh *gitHub) getGroupBasePath(groupId string) string { if groupId == PERSONAL_GROUP.Id { return "user" } else { - return "orgs/"+groupId + return "orgs/" + groupId } } -func (gh *gitHub) normalize(name string) string { - return strings.ToLower(strings.Replace(name, " ", "-", -1)) -} - func (gh *gitHub) parseNextPageValue(r *resty.Response) int { link := r.Header().Get("Link") if len(link) == 0 { @@ -423,3 +417,10 @@ func (gh *gitHub) parseNextPageValue(r *resty.Response) int { return 0 } + +func (gh *gitHub) normalize(name string) string { + if !gh.config.Git.NormalizeName { + return name + } + return strings.ToLower(strings.ReplaceAll(name, " ", "-")) +} diff --git a/impl/git/gitlab.go b/impl/git/gitlab.go index e759e1f..b7e2cde 100644 --- a/impl/git/gitlab.go +++ b/impl/git/gitlab.go @@ -3,13 +3,14 @@ package git import ( "errors" "fmt" - "github.com/go-resty/resty" + "strconv" + "strings" + + "github.com/go-resty/resty/v2" "github.com/thoas/go-funk" - "github.com/urfave/cli" + "github.com/urfave/cli/v3" "github.com/vanroy/microcli/impl/config" "github.com/vanroy/microcli/impl/prompt" - "strconv" - "strings" ) type gitLab struct { @@ -93,7 +94,7 @@ func (gl *gitLab) createGroup(args cli.Args) (string, error) { prompt.PrintNewLine() if groupName == "" || groupPath == "" { - prompt.PrintError("Missing parameters, group name and group path are required") + prompt.PrintErrorf("Missing parameters, group name and group path are required") return "", errors.New("missing parameters") } @@ -107,7 +108,7 @@ func (gl *gitLab) createGroup(args cli.Args) (string, error) { createResp, err := gl.execPost("/groups", data, &glGroup{}) if err != nil { - prompt.PrintError("Cannot create group. ( %s )", err.Error()) + prompt.PrintErrorf("Cannot create group. ( %s )", err.Error()) return "", err } @@ -118,14 +119,14 @@ func (gl *gitLab) createGroup(args cli.Args) (string, error) { func (gl *gitLab) createRepository(args cli.Args) (string, error) { - groups, err := gl.getGroups() + groups, _ := gl.getGroups() groups = funk.Filter(groups, func(g gitGroup) bool { return funk.ContainsString(gl.config.Git.GroupIds, g.Id) }).([]gitGroup) idx := 0 groupId := "" if len(groups) == 0 { - prompt.PrintError("No groups available") + prompt.PrintErrorf("No groups available") return "", errors.New("no groups available") } else if len(groups) == 1 { groupId = groups[0].Id @@ -152,7 +153,7 @@ func (gl *gitLab) createRepository(args cli.Args) (string, error) { prompt.PrintNewLine() if groupId == "" || projectName == "" { - prompt.PrintError("Missing parameters, project name and group are required") + prompt.PrintErrorf("Missing parameters, project name and group are required") return "", errors.New("missing parameters") } @@ -170,7 +171,7 @@ func (gl *gitLab) createRepository(args cli.Args) (string, error) { createResp, err := gl.execPost("projects", data, &glProject{}) if err != nil { - prompt.PrintError("Cannot create repository. ( %s )", err.Error()) + prompt.PrintErrorf("Cannot create repository. ( %s )", err.Error()) return "", err } @@ -213,7 +214,7 @@ func (gl *gitLab) getRepositories() ([]gitRepository, error) { return repos, nil } -func (gl *gitLab) createReviewRequest(group string, folder string, from string, into string, title string, message string) (reviewRequest, error) { +func (gl *gitLab) createReviewRequest(group string, folder string, from string, into string, title string, message string, draft bool) (reviewRequest, error) { // TODO ( Implement ) return reviewRequest{}, nil @@ -221,7 +222,7 @@ func (gl *gitLab) createReviewRequest(group string, folder string, from string, func (gl *gitLab) execGet(url string, resultType interface{}) (interface{}, error) { - resp, err := resty.R(). + resp, err := resty.New().R(). SetHeader("PRIVATE-TOKEN", gl.config.Git.PrivateToken). SetResult(resultType). Get(gl.apiUrl + "/" + url) @@ -235,7 +236,7 @@ func (gl *gitLab) execGet(url string, resultType interface{}) (interface{}, erro func (gl *gitLab) execPost(url string, data map[string]string, resultType interface{}) (interface{}, error) { - resp, err := resty.R(). + resp, err := resty.New().R(). SetHeader("PRIVATE-TOKEN", gl.config.Git.PrivateToken). SetResult(resultType). SetFormData(data). @@ -246,7 +247,7 @@ func (gl *gitLab) execPost(url string, data map[string]string, resultType interf } if resp.StatusCode() < 200 || resp.StatusCode() > 300 { - return nil, errors.New(fmt.Sprintf("Cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String())) + return nil, fmt.Errorf("cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String()) } return resp.Result(), nil @@ -269,8 +270,8 @@ func (gl *gitLab) toGitRepo(groupId string) interface{} { Name: project.Name, Description: project.Description, NameWithNamespace: project.NameWithNamespace, - Path: project.Path, - PathWithNamespace: project.PathWithNamespace, + Path: gl.normalize(project.Path), + PathWithNamespace: gl.normalize(project.PathWithNamespace), SshUrl: project.SshUrl, HttpUrl: project.HttpUrl, DefaultBranch: project.DefaultBranch, @@ -284,6 +285,13 @@ func (gh *gitLab) getGroupBasePath(groupId string) string { if groupId == PERSONAL_GROUP.Id { return "" } else { - return "groups/"+groupId + return "groups/" + groupId + } +} + +func (gh *gitLab) normalize(name string) string { + if !gh.config.Git.NormalizeName { + return name } + return strings.ToLower(strings.ReplaceAll(name, " ", "-")) } diff --git a/impl/git/visualstudio.go b/impl/git/visualstudio.go deleted file mode 100644 index cba1500..0000000 --- a/impl/git/visualstudio.go +++ /dev/null @@ -1,315 +0,0 @@ -package git - -import ( - "errors" - "fmt" - "github.com/go-resty/resty" - "github.com/thoas/go-funk" - "github.com/urfave/cli" - "github.com/vanroy/microcli/impl/config" - "github.com/vanroy/microcli/impl/prompt" - "strings" -) - -type visualStudio struct { - config config.Config - labels Labels -} - -type vsProject struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Url string `json:"url"` - State string `json:"state"` - Revision int `json:"revision"` - Visibility string `json:"visibility"` -} - -type vsProjectResponse struct { - Value []vsProject `json:"value"` - Count int `json:"count"` -} - -type vsRepository struct { - Id string `json:"id"` - Name string `json:"name"` - Url string `json:"url"` - RemoteUrl string `json:"remoteUrl"` - SshUrl string `json:"sshUrl"` - DefaultBranch string `json:"defaultBranch"` - Project vsProject `json:"project"` -} - -type vsRepositoriesResponse struct { - Value []vsRepository `json:"value"` - Count int `json:"count"` -} - -type vsProcess struct { - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - IsDefault bool `json:"isDefault"` -} - -type vsProcessResponse struct { - Value []vsProcess `json:"value"` - Count int `json:"count"` -} - -type vsCreateProject struct { - Name string `json:"name"` - Description string `json:"description"` - Capabilities vsCreateProjectCapabilities `json:"capabilities"` - Visibility string `json:"visibility"` -} - -type vsCreateProjectCapabilities struct { - VersionControl vsCreateProjectVersionControl `json:"versioncontrol"` - ProcessTemplate vsCreateProjectProcessTemplate `json:"processTemplate"` -} - -type vsCreateProjectVersionControl struct { - Type string `json:"sourceControlType"` -} - -type vsCreateProjectProcessTemplate struct { - Id string `json:"templateTypeId"` -} - -type vsCreateProjectResponse struct { - Id string `json:"id"` - Status string `json:"status"` - Url string `json:"url"` -} - -type vsCreateRepository struct { - Name string `json:"name"` - Project vsCreateRepositoryProject `json:"project"` -} - -type vsCreateRepositoryProject struct { - Id string `json:"id"` -} - -var vsProjectVisibilities = []prompt.Option{ - {Id: "private", Name: "Private"}, - {Id: "public", Name: "Public"}, -} - -func newVisualStudio(config config.Config) gitRemote { - return &visualStudio{ - config: config, - labels: Labels{ - GroupLabel: "projet", - GroupsLabel: "projets", - RepositoryLabel: "repository", - RepositoriesLabel: "repositories", - CreateGroupUsage: "name [description] [visibility] [process]", - CreateRepositoryUsage: "[project] name", - CodeReviewRequest: "pull requests", - }, - } -} - -func (vs *visualStudio) getLabels() Labels { - return vs.labels -} - -func (vs *visualStudio) createGroup(args cli.Args) (string, error) { - - processResp, processErr := vs.execGet("_apis/process/processes?api-version=1.0", &vsProcessResponse{}) - if processErr != nil { - return "", processErr - } - - var selectedProcessId = "" - var defaultProcessId = "" - processOptions := funk.Map(processResp.(*vsProcessResponse).Value, func(process vsProcess) prompt.Option { - var def = "" - - if args.Get(3) == process.Name { - selectedProcessId = process.Id - } - - if process.IsDefault { - def = " (default)" - defaultProcessId = process.Id - } - return prompt.Option{Id: process.Id, Name: fmt.Sprintf("%s : %s%s", process.Name, process.Description, def)} - }).([]prompt.Option) - - projectName := prompt.Input("Enter your project name :", args.Get(0)) - projectDescription := prompt.Input("\nEnter your project description :", args.Get(1)) - visibility := prompt.Choice("\nSelect your project visibility :", vsProjectVisibilities, args.Get(2)) - projectProcessTemplateId := prompt.Choice("\nSelect your project process template :", processOptions, selectedProcessId) - if projectProcessTemplateId == "" { - projectProcessTemplateId = defaultProcessId - } - - prompt.PrintNewLine() - - data := vsCreateProject{ - Name: projectName, - Description: projectDescription, - Visibility: visibility, - Capabilities: vsCreateProjectCapabilities{ - VersionControl: vsCreateProjectVersionControl{Type: "GIT"}, - ProcessTemplate: vsCreateProjectProcessTemplate{Id: projectProcessTemplateId}, - }, - } - - createResp, err := vs.execPost("_apis/projects?api-version=2.0-preview", data, &vsCreateProjectResponse{}) - - if err != nil { - prompt.PrintError("Cannot create project. ( %s )", err.Error()) - return "", err - } - - prompt.PrintInfo("Project created") - - return createResp.(*vsCreateProjectResponse).Id, nil -} - -func (vs *visualStudio) createRepository(args cli.Args) (string, error) { - - groups, err := vs.getGroups() - - groups = funk.Filter(groups, func(g gitGroup) bool { return funk.ContainsString(vs.config.Git.GroupIds, g.Id) }).([]gitGroup) - - idx := 0 - groupId := "" - if len(groups) == 0 { - prompt.PrintError("No projects available") - return "", errors.New("no projects available") - } else if len(groups) == 1 { - groupId = groups[0].Id - } else { - defaultProjectId := "" - groupOptions := funk.Map(groups, func(group gitGroup) prompt.Option { - if args.Get(0) == group.Name { - defaultProjectId = group.Id - } - return prompt.Option{Id: group.Id, Name: group.Name} - }).([]prompt.Option) - - groupId = prompt.Choice("Select your project :", groupOptions, defaultProjectId) - idx = idx + 1 - } - - projectName := prompt.Input("\nEnter your repository name :", args.Get(idx)) - prompt.PrintNewLine() - - data := vsCreateRepository{ - Name: projectName, - Project: vsCreateRepositoryProject{ - Id: groupId, - }, - } - - createResp, err := vs.execPost("_apis/git/repositories/?api-version=1.0", data, &vsRepository{}) - - if err != nil { - prompt.PrintError("Cannot create repository. ( %s )", err.Error()) - return "", err - } - - prompt.PrintInfo("Repository created") - - return createResp.(*vsRepository).Id, nil -} - -func (vs *visualStudio) getGroups() ([]gitGroup, error) { - - resp, err := vs.execGet("_apis/projects/?api-version=1.0", &vsProjectResponse{}) - if err != nil { - return nil, err - } - - return funk.Map(resp.(*vsProjectResponse).Value, vs.toGitGroup).([]gitGroup), nil -} - -func (vs *visualStudio) getRepositories() ([]gitRepository, error) { - - var repos []gitRepository - - funk.ForEach(vs.config.Git.GroupIds, func(groupId string) { - - resp, err := vs.execGet(groupId+"/_apis/git/repositories/?api-version=1.0", &vsRepositoriesResponse{}) - if err == nil { - repos = append(repos, funk.Map(resp.(*vsRepositoriesResponse).Value, vs.toGitRepo(groupId)).([]gitRepository)...) - } - }) - - return repos, nil -} - -func (vs *visualStudio) createReviewRequest(group string, folder string, from string, into string, title string, message string) (reviewRequest, error) { - - // TODO ( Implement ) - return reviewRequest{}, nil -} - -func (vs *visualStudio) execGet(url string, resultType interface{}) (interface{}, error) { - - resp, err := resty.R(). - SetBasicAuth("", vs.config.Git.PrivateToken). - SetResult(resultType). - Get(vs.config.Git.BaseUrl + "/" + url) - - if err != nil { - prompt.PrintError(resp.String()) - } - - return resp.Result(), err -} - -func (vs *visualStudio) execPost(url string, data interface{}, resultType interface{}) (interface{}, error) { - - resp, err := resty.R(). - SetBasicAuth("", vs.config.Git.PrivateToken). - SetResult(resultType). - SetBody(data). - Post(vs.config.Git.BaseUrl + "/" + url) - - if err != nil { - return nil, err - } - - if resp.StatusCode() < 200 || resp.StatusCode() > 300 { - return nil, errors.New(fmt.Sprintf("Cannot execute post request. Status code : %d. Message : %s", resp.StatusCode(), resp.String())) - } - - return resp.Result(), nil -} - -func (vs *visualStudio) toGitRepo(groupId string) interface{} { - - return func(repository vsRepository) gitRepository { - return gitRepository{ - Id: repository.Id, - Name: repository.Name, - NameWithNamespace: repository.Project.Name + " / " + repository.Name, - Path: vs.normalize(repository.Name), - PathWithNamespace: vs.normalize(repository.Project.Name) + "/" + vs.normalize(repository.Name), - SshUrl: repository.SshUrl, - HttpUrl: repository.RemoteUrl, - DefaultBranch: repository.DefaultBranch, - Archived: false, - GroupId: groupId, - } - } -} - -func (vs *visualStudio) toGitGroup(project vsProject) gitGroup { - - return gitGroup{ - Id: project.Id, - Name: project.Name, - } -} - -func (vs *visualStudio) normalize(name string) string { - return strings.ToLower(strings.Replace(name, " ", "-", -1)) -} diff --git a/impl/glob/glob_matcher.go b/impl/glob/glob_matcher.go new file mode 100644 index 0000000..5f1155d --- /dev/null +++ b/impl/glob/glob_matcher.go @@ -0,0 +1,40 @@ +package glob + +import ( + "fmt" + + "github.com/gobwas/glob" + "github.com/thoas/go-funk" +) + +type GlobMatcher struct { + pattern string + globPattern glob.Glob + excludes []string + excludesPattern []glob.Glob +} + +func NewGlobMatcher(pattern string, excludes ...string) *GlobMatcher { + return &GlobMatcher{ + pattern: pattern, + globPattern: glob.MustCompile(pattern), + excludes: excludes, + excludesPattern: funk.Map(excludes, func(p string) glob.Glob { return glob.MustCompile(p) }).([]glob.Glob), + } +} + +func (m GlobMatcher) Match(value string) (bool, string) { + + // Handle exclusion + for i, p := range m.excludesPattern { + if p.Match((value)) { + return false, fmt.Sprintf("'%s' match exclusion pattern '%s'", value, m.excludes[i]) + } + } + + if m.pattern != "" && !m.globPattern.Match(value) { + return false, fmt.Sprintf("'%s' not match with pattern '%s'", value, m.pattern) + } + + return true, "" +} diff --git a/impl/initialzr/initialzr.go b/impl/initialzr/initialzr.go index 5f69a5c..7e498ef 100644 --- a/impl/initialzr/initialzr.go +++ b/impl/initialzr/initialzr.go @@ -2,12 +2,13 @@ package initialzr import ( "fmt" - "github.com/go-resty/resty" + "os" + "strings" + + "github.com/go-resty/resty/v2" "github.com/vanroy/microcli/impl/cmd" "github.com/vanroy/microcli/impl/config" "github.com/vanroy/microcli/impl/prompt" - "os" - "strings" ) type Initializr struct { @@ -36,7 +37,7 @@ func (init *Initializr) Init(projectType string, projectName string, dependencie url = init.config.Initializr.Url } - resp, err := resty.R(). + resp, err := resty.New().R(). SetFormData(data). SetOutput(archive). Post(fmt.Sprintf("%s/starter.tgz", url)) @@ -47,7 +48,7 @@ func (init *Initializr) Init(projectType string, projectName string, dependencie } // Remove archive - defer os.Remove(archive) + defer os.Remove(archive) //nolint:errcheck // Extract archive _, archiveErr := cmd.ExecCmdDir("tar", []string{"xvzf", archive}, destFolder) diff --git a/impl/initialzr/initialzr_test.go b/impl/initialzr/initialzr_test.go index 83acfe7..e4562fe 100644 --- a/impl/initialzr/initialzr_test.go +++ b/impl/initialzr/initialzr_test.go @@ -1,13 +1,17 @@ package initialzr import ( - "github.com/vanroy/microcli/impl/config" "testing" + + "github.com/vanroy/microcli/impl/config" ) func SkipTestDownload(t *testing.T) { initializr := NewInitializr(config.Config{}) - initializr.Init("gradle-project", "test", []string{}, "/tmp/microcli-init") + err := initializr.Init("gradle-project", "test", []string{}, "/tmp/microcli-init") + if err != nil { + t.Error("Error during init") + } } diff --git a/impl/prompt/prompt.go b/impl/prompt/prompt.go index afbe026..e0d2f6d 100644 --- a/impl/prompt/prompt.go +++ b/impl/prompt/prompt.go @@ -3,18 +3,18 @@ package prompt import ( "bufio" "fmt" - "github.com/howeyc/gopass" - "github.com/thoas/go-funk" - "github.com/vanroy/microcli/impl/config" "os" "strconv" "strings" + + "github.com/thoas/go-funk" + "github.com/vanroy/microcli/impl/config" + "golang.org/x/term" ) // Color defines a custom color object which is defined by SGR parameters. type color struct { - params []Attribute - noColor *bool + params []Attribute } type Option struct { @@ -95,19 +95,25 @@ func PrintItem(text string) { } } -func PrintInfo(format string, a ...interface{}) { +func PrintInfo(format string, a ...any) { if config.Options.Verbose { fmt.Printf("%s==> %s%s%s\n", Color(Bold, FgBlue), Color(FgWhite), fmt.Sprintf(format, a...), Color(Reset)) } } -func PrintWarn(format string, a ...interface{}) { +func PrintWarn(format string, a ...any) { if config.Options.Verbose { fmt.Printf("%sWARNING: %s%s%s\n", Color(Bold, FgYellow), Color(FgWhite), fmt.Sprintf(format, a...), Color(Reset)) } } -func PrintError(format string, a ...interface{}) { +func PrintError(message string) { + if config.Options.Verbose { + fmt.Printf("%sERROR: %s%s%s\n", Color(Bold, FgRed), Color(FgWhite), message, Color(Reset)) + } +} + +func PrintErrorf(format string, a ...any) { if config.Options.Verbose { fmt.Printf("%sERROR: %s%s%s\n", Color(Bold, FgRed), Color(FgWhite), fmt.Sprintf(format, a...), Color(Reset)) } @@ -150,7 +156,7 @@ func RestrictedInput(prompt string, acceptedValues []string) string { for { input := Input(prompt + " ( " + strings.Join(acceptedValues, " / ") + " ) :") if funk.ContainsString(acceptedValues, input) { - return input; + return input } } } @@ -173,7 +179,7 @@ func Choice(prompt string, options []Option, defaultValue ...string) string { fmt.Printf("%d) %s\n", i+1, options[i].Name) } - for true { + for { str := Input("#? ") if str == "" { return "" @@ -184,8 +190,6 @@ func Choice(prompt string, options []Option, defaultValue ...string) string { return options[result-1].Id } } - - return "" } func Password(prompt string) string { @@ -198,8 +202,7 @@ func Password(prompt string) string { fmt.Print(prompt + " ") } - // Silent. For printing *'s use gopass.GetPasswdMasked() - pass, err := gopass.GetPasswdMasked() + pass, err := term.ReadPassword(int(os.Stdin.Fd())) if err == nil { return string(pass) } diff --git a/main.go b/main.go index a2e73e8..fe62d2f 100644 --- a/main.go +++ b/main.go @@ -1,60 +1,62 @@ package main import ( + "context" "os" - "github.com/c-bata/go-prompt" - "github.com/urfave/cli" + "github.com/urfave/cli/v3" + + "os/signal" + "syscall" microcli "github.com/vanroy/microcli/impl" "github.com/vanroy/microcli/impl/config" "github.com/vanroy/microcli/impl/git" pmt "github.com/vanroy/microcli/impl/prompt" - "os/signal" - "syscall" ) func main() { handleSignals() - conf, err := loadConf() + conf, err := loadConf(context.Background()) if err != nil { - pmt.PrintError("Command load config '%s'", err.Error()) + pmt.PrintErrorf("Command load config '%s'", err.Error()) os.Exit(1) } - app := cli.NewApp() - app.Name = "Microbox" + app := &cli.Command{} + app.Name = "mbx" app.Usage = "This script provides utilities to manage microservices git repositories." app.Version = "1.0.0" app.Before = initContext - app.Action = displayPrompt app.CommandNotFound = commandNotFound app.Commands = microcli.InitCommands(*conf) app.Flags = []cli.Flag{ - cli.BoolFlag{ - Name: "quiet, q", - Usage: "Disable verbose output", + &cli.BoolFlag{ + Name: "quiet", + Aliases: []string{"q"}, + Usage: "Disable verbose output", }, - cli.BoolFlag{ - Name: "non-interactive, n", - Usage: "Non interactive mode", + &cli.BoolFlag{ + Name: "non-interactive", + Aliases: []string{"n"}, + Usage: "Non interactive mode", }, } - app.Run(os.Args) + app.Run(context.Background(), os.Args) //nolint:errcheck } // Load or init configuration -func loadConf() (*config.Config, error) { +func loadConf(context context.Context) (*config.Config, error) { - if exist, err := config.Exist(); exist == false && err == nil { + if exist, err := config.Exist(); !exist && err == nil { microcli.ShowBanner() pmt.PrintWarn("Settings not exist, starting initialization\n") - git.Init(nil) + git.Init(context, nil) //nolint:errcheck pmt.PrintInfo("Settings initialized, enjoy !") os.Exit(0) } @@ -63,7 +65,7 @@ func loadConf() (*config.Config, error) { } // Init context before commands -func initContext(c *cli.Context) error { +func initContext(ctx context.Context, c *cli.Command) (context.Context, error) { config.Options = config.GlobalOptions{ Verbose: !c.Bool("quiet"), @@ -72,42 +74,12 @@ func initContext(c *cli.Context) error { microcli.ShowBanner() - return nil -} - -// Display interactive prompt -func displayPrompt(c *cli.Context) error { - - p := prompt.New( - microcli.NexExecutor(c).Execute, - microcli.Completer, - prompt.OptionTitle("Microbox CLI"), - prompt.OptionPrefix("=> "), - prompt.OptionPrefixTextColor(prompt.DefaultColor), - prompt.OptionSuggestionBGColor(prompt.LightGray), - prompt.OptionSuggestionTextColor(prompt.White), - prompt.OptionDescriptionBGColor(prompt.DarkGray), - prompt.OptionDescriptionTextColor(prompt.White), - prompt.OptionPreviewSuggestionBGColor(prompt.DarkGray), - prompt.OptionPreviewSuggestionTextColor(prompt.White), - prompt.OptionSelectedSuggestionBGColor(prompt.DarkGray), - prompt.OptionSelectedSuggestionTextColor(prompt.White), - prompt.OptionSelectedDescriptionBGColor(prompt.LightGray), - prompt.OptionSelectedDescriptionTextColor(prompt.White), - prompt.OptionAddKeyBind(prompt.KeyBind{Key: prompt.ControlC, Fn: func(buffer *prompt.Buffer) { - os.Exit(1) - }}), - ) - - p.Run() - - return nil + return ctx, nil } // Display command not found -func commandNotFound(c *cli.Context, cmd string) { - pmt.PrintError("Command not exit '%s'", cmd) - os.Exit(1) +func commandNotFound(ctx context.Context, c *cli.Command, cmd string) { + pmt.PrintErrorf("Command not exist '%s'", cmd) } func handleSignals() { diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 19acb70..0000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'microcli'