mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
Merge github.com:gogf/gf into personal/hailaz
This commit is contained in:
43
.github/workflows/ci-main.yml
vendored
43
.github/workflows/ci-main.yml
vendored
@ -20,6 +20,13 @@ on:
|
||||
- feature/**
|
||||
- enhance/**
|
||||
- fix/**
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug:
|
||||
type: boolean
|
||||
description: 'Enable tmate Debug'
|
||||
required: false
|
||||
default: false
|
||||
|
||||
# This allows a subsequently queued workflow run to interrupt previous runs
|
||||
concurrency:
|
||||
@ -47,7 +54,7 @@ jobs:
|
||||
# Service containers to run with `code-test`
|
||||
services:
|
||||
# Etcd service.
|
||||
# docker run -d --name etcd -p 2379:2379 -e ALLOW_NONE_AUTHENTICATION=yes bitnamilegacy/etcd:3.4.24
|
||||
# docker run -p 2379:2379 -e ALLOW_NONE_AUTHENTICATION=yes bitnamilegacy/etcd:3.4.24
|
||||
etcd:
|
||||
image: bitnamilegacy/etcd:3.4.24
|
||||
env:
|
||||
@ -68,7 +75,7 @@ jobs:
|
||||
- 6379:6379
|
||||
|
||||
# MySQL backend server.
|
||||
# docker run -d --name mysql \
|
||||
# docker run \
|
||||
# -p 3306:3306 \
|
||||
# -e MYSQL_DATABASE=test \
|
||||
# -e MYSQL_ROOT_PASSWORD=12345678 \
|
||||
@ -82,7 +89,7 @@ jobs:
|
||||
- 3306:3306
|
||||
|
||||
# MariaDb backend server.
|
||||
# docker run -d --name mariadb \
|
||||
# docker run \
|
||||
# -p 3307:3306 \
|
||||
# -e MYSQL_DATABASE=test \
|
||||
# -e MYSQL_ROOT_PASSWORD=12345678 \
|
||||
@ -96,7 +103,7 @@ jobs:
|
||||
- 3307:3306
|
||||
|
||||
# PostgreSQL backend server.
|
||||
# docker run -d --name postgres \
|
||||
# docker run \
|
||||
# -p 5432:5432 \
|
||||
# -e POSTGRES_PASSWORD=12345678 \
|
||||
# -e POSTGRES_USER=postgres \
|
||||
@ -143,7 +150,7 @@ jobs:
|
||||
--health-retries 10
|
||||
|
||||
# ClickHouse backend server.
|
||||
# docker run -d --name clickhouse \
|
||||
# docker run \
|
||||
# -p 9000:9000 -p 8123:8123 -p 9001:9001 \
|
||||
# clickhouse/clickhouse-server:24.11.1.2557-alpine
|
||||
clickhouse-server:
|
||||
@ -154,7 +161,7 @@ jobs:
|
||||
- 9001:9001
|
||||
|
||||
# Polaris backend server.
|
||||
# docker run -d --name polaris \
|
||||
# docker run \
|
||||
# -p 8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091 \
|
||||
# polarismesh/polaris-standalone:v1.17.2
|
||||
polaris:
|
||||
@ -191,6 +198,17 @@ jobs:
|
||||
ports:
|
||||
- 5236:5236
|
||||
|
||||
# openGauss server
|
||||
# docker run --privileged=true -e GS_PASSWORD=UTpass@1234 -p 9950:5432 opengauss/opengauss:7.0.0-RC1.B023
|
||||
gaussdb:
|
||||
image: opengauss/opengauss:7.0.0-RC1.B023
|
||||
env:
|
||||
GS_PASSWORD: UTpass@1234
|
||||
TZ: Asia/Shanghai
|
||||
ports:
|
||||
- 9950:5432
|
||||
|
||||
|
||||
zookeeper:
|
||||
image: zookeeper:3.8
|
||||
ports:
|
||||
@ -207,6 +225,19 @@ jobs:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup tmate Session
|
||||
uses: mxschmitt/action-tmate@v3
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.debug }}
|
||||
with:
|
||||
detached: true
|
||||
limit-access-to-actor: false
|
||||
|
||||
- name: Free Disk Space
|
||||
run: |
|
||||
df -h /
|
||||
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/hostedtoolcache/CodeQL /opt/hostedtoolcache/Python || true
|
||||
df -h /
|
||||
|
||||
- name: Start Apollo Containers
|
||||
run: docker compose -f ".github/workflows/apollo/docker-compose.yml" up -d --build
|
||||
|
||||
|
||||
5
.github/workflows/release.yml
vendored
5
.github/workflows/release.yml
vendored
@ -17,11 +17,12 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout Github Code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
|
||||
- name: Set Up Golang Environment
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: 1.25
|
||||
cache: false
|
||||
|
||||
- name: Build CLI Binary
|
||||
run: |
|
||||
@ -34,7 +35,7 @@ jobs:
|
||||
- name: Build CLI Binary For All Platform
|
||||
run: |
|
||||
cd cmd/gf
|
||||
gf build main.go -n gf -a all -s all -p temp
|
||||
gf build main.go -n gf -a all -s linux,windows,darwin,freebsd,netbsd,openbsd -p temp
|
||||
|
||||
- name: Move Files Before Release
|
||||
run: |
|
||||
|
||||
0
.github/workflows/scripts/before_script.sh
vendored
Normal file → Executable file
0
.github/workflows/scripts/before_script.sh
vendored
Normal file → Executable file
250
.github/workflows/scripts/ci-main-clean.sh
vendored
Executable file
250
.github/workflows/scripts/ci-main-clean.sh
vendored
Executable file
@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
dirpath=$1
|
||||
|
||||
# Extract the base directory name for pattern matching
|
||||
if [ -n "$dirpath" ]; then
|
||||
dirname=$(basename "$dirpath")
|
||||
echo "Cleaning Docker resources for path: $dirpath (pattern: $dirname)"
|
||||
df -h /
|
||||
|
||||
# Process containers and images based on the directory
|
||||
case "$dirname" in
|
||||
# "mysql")
|
||||
# echo "Cleaning mysql resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing mysql containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q mysql 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
"mssql")
|
||||
echo "Cleaning mssql resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing mssql containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q mcr.microsoft.com/mssql/server 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
"pgsql")
|
||||
echo "Cleaning postgres resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing postgres containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q postgres 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
"oracle")
|
||||
echo "Cleaning oracle resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing oracle containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q loads/oracle-xe-11g-r2 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
"dm")
|
||||
echo "Cleaning dm resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing dm containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q loads/dm 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
"clickhouse")
|
||||
echo "Cleaning clickhouse resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing clickhouse containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q clickhouse/clickhouse-server 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
# "redis")
|
||||
# echo "Cleaning redis resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing redis containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q redis loads/redis loads/redis-sentinel 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
"etcd")
|
||||
echo "Cleaning etcd resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing etcd containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q bitnamilegacy/etcd 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
# "consul")
|
||||
# echo "Cleaning consul resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing consul containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q consul 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
# "nacos")
|
||||
# echo "Cleaning nacos resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing nacos containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q nacos/nacos-server 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
# "polaris")
|
||||
# echo "Cleaning polaris resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing polaris containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q polarismesh/polaris-standalone 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
"zookeeper")
|
||||
echo "Cleaning zookeeper resources..."
|
||||
containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
if [ -n "$containers" ]; then
|
||||
echo "Stopping and removing zookeeper containers..."
|
||||
docker stop $containers 2>/dev/null || true
|
||||
docker rm -f $containers 2>/dev/null || true
|
||||
fi
|
||||
docker rmi -f $(docker images -q zookeeper 2>/dev/null) 2>/dev/null || true
|
||||
;;
|
||||
# "apollo")
|
||||
# echo "Cleaning apollo resources..."
|
||||
# containers=$(docker ps -aq --filter "name=$dirname" 2>/dev/null)
|
||||
# if [ -n "$containers" ]; then
|
||||
# echo "Stopping and removing apollo containers..."
|
||||
# docker stop $containers 2>/dev/null || true
|
||||
# docker rm -f $containers 2>/dev/null || true
|
||||
# fi
|
||||
# docker rmi -f $(docker images -q loads/apollo-quick-start 2>/dev/null) 2>/dev/null || true
|
||||
# ;;
|
||||
*)
|
||||
# No matching pattern, skip cleanup
|
||||
echo "No specific Docker cleanup rule for '$dirname', skipping cleanup"
|
||||
;;
|
||||
esac
|
||||
|
||||
# Remove dangling images and volumes to free up space
|
||||
echo "Removing dangling images and unused volumes..."
|
||||
docker image prune -f 2>/dev/null || true
|
||||
docker volume prune -f 2>/dev/null || true
|
||||
|
||||
echo "Docker cleanup completed for $dirname"
|
||||
docker system df
|
||||
df -h /
|
||||
fi
|
||||
|
||||
# df -h /
|
||||
# Filesystem Size Used Avail Use% Mounted on
|
||||
# /dev/root 72G 67G 5.4G 93% /
|
||||
# tmpfs 7.9G 84K 7.9G 1% /dev/shm
|
||||
# tmpfs 3.2G 2.6M 3.2G 1% /run
|
||||
# tmpfs 5.0M 0 5.0M 0% /run/lock
|
||||
# /dev/sdb16 881M 62M 758M 8% /boot
|
||||
# /dev/sdb15 105M 6.2M 99M 6% /boot/efi
|
||||
# /dev/sda1 74G 4.1G 66G 6% /mnt
|
||||
# tmpfs 1.6G 12K 1.6G 1% /run/user/1001
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ docker system df
|
||||
# TYPE TOTAL ACTIVE SIZE RECLAIMABLE
|
||||
# Images 18 11 8.326GB 1.644GB (19%)
|
||||
# Containers 11 11 2.692GB 0B (0%)
|
||||
# Local Volumes 11 8 665.7MB 211.9MB (31%)
|
||||
# Build Cache 0 0 0B 0B
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ docker images
|
||||
# REPOSITORY TAG IMAGE ID CREATED SIZE
|
||||
# alpine/curl latest 99fd43792a61 2 days ago 13.5MB
|
||||
# postgres 17-alpine b6bf692a8125 9 days ago 278MB
|
||||
# zookeeper 3.8 2f26c02b94ca 10 days ago 306MB
|
||||
# mariadb 11.4 063fb6684f96 10 days ago 332MB
|
||||
# mcr.microsoft.com/mssql/server 2022-latest a2fbff321505 4 weeks ago 1.61GB
|
||||
# clickhouse/clickhouse-server 24.11.1.2557-alpine 2eee9fd3ae74 12 months ago 539MB
|
||||
# redis 7.0 7705dd2858c1 18 months ago 109MB
|
||||
# consul 1.15 686495461132 20 months ago 155MB
|
||||
# mysql 5.7 5107333e08a8 23 months ago 501MB
|
||||
# polarismesh/polaris-standalone v1.17.2 b7a8cf0a8438 2 years ago 545MB
|
||||
# bitnamilegacy/etcd 3.4.24 74ae5e205ac5 2 years ago 134MB
|
||||
# nacos/nacos-server v2.1.2 a978644d9246 2 years ago 1.06GB
|
||||
# loads/redis 7.0-sentinel 6f12d40540ba 3 years ago 114MB
|
||||
# loads/dm v8.1.2.128_ent_x86_64_ctm_pack4 ccb727ce9dce 3 years ago 432MB
|
||||
# loads/redis-sentinel 7.0 6818c626f5ca 3 years ago 104MB
|
||||
# loads/apollo-quick-start latest 8490de672148 3 years ago 190MB
|
||||
# alpine 3.8 c8bccc0af957 5 years ago 4.41MB
|
||||
# loads/oracle-xe-11g-r2 11.2.0 0d19fd2e072e 6 years ago 2.1GB
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ docker ps -s
|
||||
# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES SIZE
|
||||
# 8214f83420c6 zookeeper:3.8 "/docker-entrypoint.…" 6 minutes ago Up 6 minutes 2888/tcp, 3888/tcp, 0.0.0.0:2181->2181/tcp, [::]:2181->2181/tcp, 8080/tcp d66bac92ae9646f688f70ed4b5176f14_zookeeper38_3a22ef 33kB (virtual 306MB)
|
||||
# 8938d73842e8 loads/dm:v8.1.2.128_ent_x86_64_ctm_pack4 "/bin/bash /opt/star…" 6 minutes ago Up 6 minutes 0.0.0.0:5236->5236/tcp, [::]:5236->5236/tcp ca280fbdb86f40c2acf86d7d526c6285_loadsdmv812128_ent_x86_64_ctm_pack4_770a59 844MB (virtual 1.28GB)
|
||||
# 0d3a653fe1f2 loads/oracle-xe-11g-r2:11.2.0 "/bin/sh -c '/usr/sb…" 6 minutes ago Up 6 minutes 22/tcp, 8080/tcp, 0.0.0.0:1521->1521/tcp, [::]:1521->1521/tcp 2048856d428c4967b1c35193eb8c9192_loadsoraclexe11gr21120_295d54 1.3GB (virtual 3.4GB)
|
||||
# ca3936189166 polarismesh/polaris-standalone:v1.17.2 "/bin/bash run.sh" 6 minutes ago Up 6 minutes 0.0.0.0:8090-8091->8090-8091/tcp, [::]:8090-8091->8090-8091/tcp, 8080/tcp, 8100-8101/tcp, 0.0.0.0:8093->8093/tcp, [::]:8093->8093/tcp, 8761/tcp, 15010/tcp, 0.0.0.0:9090-9091->9090-9091/tcp, [::]:9090-9091->9090-9091/tcp cbd43dceef754e2d8aab507e33167be7_polarismeshpolarisstandalonev1172_ca40b6 299MB (virtual 844MB)
|
||||
# 26169dad485e clickhouse/clickhouse-server:24.11.1.2557-alpine "/entrypoint.sh" 6 minutes ago Up 6 minutes 0.0.0.0:8123->8123/tcp, [::]:8123->8123/tcp, 0.0.0.0:9000-9001->9000-9001/tcp, [::]:9000-9001->9000-9001/tcp, 9009/tcp f1c7766fbe36401792a6f735d7acf123_clickhouseclickhouseserver241112557alpine_cfc034 338kB (virtual 539MB)
|
||||
# 04689a1d581f mcr.microsoft.com/mssql/server:2022-latest "/opt/mssql/bin/laun…" 6 minutes ago Up 6 minutes (healthy) 0.0.0.0:1433->1433/tcp, [::]:1433->1433/tcp 41d685349a7640b28230db8d0f60efe7_mcrmicrosoftcommssqlserver2022latest_fe29fb 108MB (virtual 1.72GB)
|
||||
# d5fbc5f811af postgres:17-alpine "docker-entrypoint.s…" 6 minutes ago Up 6 minutes (healthy) 0.0.0.0:5432->5432/tcp, [::]:5432->5432/tcp 2783be71b5ce417ab9a31428e7b4d8f2_postgres17alpine_c60840 63B (virtual 278MB)
|
||||
# da96a7ad7a01 mariadb:11.4 "docker-entrypoint.s…" 7 minutes ago Up 7 minutes 0.0.0.0:3307->3306/tcp, [::]:3307->3306/tcp 45eed646fa6c4a698893ee11cda95a4c_mariadb114_3a9cd6 2B (virtual 332MB)
|
||||
# 27ba1904ba3a mysql:5.7 "docker-entrypoint.s…" 7 minutes ago Up 7 minutes 0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp ea6d7a4c207d427a95b5ae0db91fdf56_mysql57_c21053 4B (virtual 501MB)
|
||||
# 518e785d1bb6 redis:7.0 "docker-entrypoint.s…" 7 minutes ago Up 7 minutes (healthy) 0.0.0.0:6379->6379/tcp, [::]:6379->6379/tcp af6044fc849e441bbc6c48f7a5ec5fec_redis70_b11994 0B (virtual 109MB)
|
||||
# 7495ec2cd8e3 bitnamilegacy/etcd:3.4.24 "/opt/bitnami/script…" 7 minutes ago Up 7 minutes 0.0.0.0:2379->2379/tcp, [::]:2379->2379/tcp, 2380/tcp 49f2a2a6bf3a4fae842cc950bbc3658a_bitnamilegacyetcd3424_1265e1 145MB (virtual 279MB)
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ du -ah --max-depth=1 /usr | sort -n
|
||||
# 4.0K /usr/games
|
||||
# 4.0K /usr/lib64
|
||||
# 6.6G /usr/lib
|
||||
# 9.3G /usr/share
|
||||
# 15M /usr/lib32
|
||||
# 24G /usr/local
|
||||
# 41G /usr
|
||||
# 95M /usr/sbin
|
||||
# 156M /usr/include
|
||||
# 158M /usr/src
|
||||
# 402M /usr/libexec
|
||||
# 841M /usr/bin
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ du -ah --max-depth=1 /opt | sort -n
|
||||
# 4.0K /opt/pipx_bin
|
||||
# 5.8G /opt/hostedtoolcache
|
||||
# 8.5G /opt
|
||||
# 12K /opt/containerd
|
||||
# 14M /opt/hca
|
||||
# 16K /opt/post-generation
|
||||
# 217M /opt/runner-cache
|
||||
# 243M /opt/actionarchivecache
|
||||
# 374M /opt/google
|
||||
# 515M /opt/pipx
|
||||
# 655M /opt/az
|
||||
# 783M /opt/microsoft
|
||||
|
||||
# runner@runnervmg1sw1:~/work/gf/gf$ du -ah --max-depth=1 /opt/hostedtoolcache/ | sort -n
|
||||
# 1.1G /opt/hostedtoolcache/go
|
||||
# 1.6G /opt/hostedtoolcache/CodeQL
|
||||
# 1.9G /opt/hostedtoolcache/Python
|
||||
# 5.8G /opt/hostedtoolcache/
|
||||
# 9.9M /opt/hostedtoolcache/protoc
|
||||
# 24K /opt/hostedtoolcache/Java_Temurin-Hotspot_jdk
|
||||
# 217M /opt/hostedtoolcache/Ruby
|
||||
# 520M /opt/hostedtoolcache/PyPy
|
||||
# 574M /opt/hostedtoolcache/node
|
||||
|
||||
73
.github/workflows/scripts/ci-main.sh
vendored
Normal file → Executable file
73
.github/workflows/scripts/ci-main.sh
vendored
Normal file → Executable file
@ -2,65 +2,58 @@
|
||||
|
||||
coverage=$1
|
||||
|
||||
# update code of submodules
|
||||
git clone https://github.com/gogf/examples
|
||||
|
||||
# update go.mod in examples directory to replace github.com/gogf/gf packages with local directory
|
||||
bash .github/workflows/scripts/replace_examples_gomod.sh
|
||||
|
||||
# find all path that contains go.mod.
|
||||
for file in `find . -name go.mod`; do
|
||||
dirpath=$(dirname $file)
|
||||
echo $dirpath
|
||||
|
||||
# ignore mssql tests as its docker service failed
|
||||
# TODO remove this ignoring codes after the mssql docker service OK
|
||||
if [ "mssql" = $(basename $dirpath) ]; then
|
||||
continue 1
|
||||
fi
|
||||
|
||||
|
||||
# package kubecm was moved to sub ci procedure.
|
||||
if [ "kubecm" = $(basename $dirpath) ]; then
|
||||
continue 1
|
||||
fi
|
||||
|
||||
# Check if it's a contrib directory or examples directory
|
||||
if [[ $dirpath =~ "/contrib/" ]] || [[ $dirpath =~ "/examples/" ]]; then
|
||||
# Check if go version meets the requirement
|
||||
if ! go version | grep -qE "go${LATEST_GO_VERSION}"; then
|
||||
echo "ignore path $dirpath as go version is not ${LATEST_GO_VERSION}: $(go version)"
|
||||
continue 1
|
||||
fi
|
||||
# If it's examples directory, only build without tests
|
||||
if [[ $dirpath =~ "/examples/" ]]; then
|
||||
echo "the examples directory only needs to be built, not unit tests and coverage tests."
|
||||
cd $dirpath
|
||||
go mod tidy
|
||||
go build ./...
|
||||
cd -
|
||||
continue 1
|
||||
fi
|
||||
|
||||
# examples directory was moved to sub ci procedure.
|
||||
if [[ $dirpath =~ "/examples/" ]]; then
|
||||
continue 1
|
||||
fi
|
||||
|
||||
|
||||
if [[ $file =~ "/testdata/" ]]; then
|
||||
echo "ignore testdata path $file"
|
||||
continue 1
|
||||
fi
|
||||
|
||||
|
||||
# Check if it's a contrib directory
|
||||
if [[ $dirpath =~ "/contrib/" ]]; then
|
||||
# Check if go version meets the requirement
|
||||
if ! go version | grep -qE "go${LATEST_GO_VERSION}"; then
|
||||
echo "ignore path $dirpath as go version is not ${LATEST_GO_VERSION}: $(go version)"
|
||||
# clean docker containers and images to free disk space
|
||||
# bash .github/workflows/scripts/ci-main-clean.sh "$dirpath"
|
||||
continue 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# if [[ $dirpath = "." ]]; then
|
||||
# # No space left on device error sometimes occurs in CI pipelines, so clean the cache before tests.
|
||||
# go clean -cache
|
||||
# fi
|
||||
|
||||
cd $dirpath
|
||||
go mod tidy
|
||||
go build ./...
|
||||
|
||||
|
||||
# test with coverage
|
||||
if [ "${coverage}" = "coverage" ]; then
|
||||
go test ./... -race -coverprofile=coverage.out -covermode=atomic -coverpkg=./...,github.com/gogf/gf/... || exit 1
|
||||
|
||||
if grep -q "/gogf/gf/.*/v2" go.mod; then
|
||||
sed -i "s/gogf\/gf\(\/.*\)\/v2/gogf\/gf\/v2\1/g" coverage.out
|
||||
fi
|
||||
go test ./... -count=1 -race -coverprofile=coverage.out -covermode=atomic -coverpkg=./...,github.com/gogf/gf/... || exit 1
|
||||
|
||||
if grep -q "/gogf/gf/.*/v2" go.mod; then
|
||||
sed -i "s/gogf\/gf\(\/.*\)\/v2/gogf\/gf\/v2\1/g" coverage.out
|
||||
fi
|
||||
else
|
||||
go test ./... -race || exit 1
|
||||
go test ./... -count=1 -race || exit 1
|
||||
fi
|
||||
|
||||
|
||||
cd -
|
||||
# clean docker containers and images to free disk space
|
||||
# bash .github/workflows/scripts/ci-main-clean.sh "$dirpath"
|
||||
done
|
||||
|
||||
20
.github/workflows/scripts/ci-sub.sh
vendored
Normal file → Executable file
20
.github/workflows/scripts/ci-sub.sh
vendored
Normal file → Executable file
@ -2,6 +2,12 @@
|
||||
|
||||
coverage=$1
|
||||
|
||||
# update code of submodules
|
||||
git clone https://github.com/gogf/examples
|
||||
|
||||
# update go.mod in examples directory to replace github.com/gogf/gf packages with local directory
|
||||
bash .github/workflows/scripts/replace_examples_gomod.sh
|
||||
|
||||
# Function to compare version numbers
|
||||
version_compare() {
|
||||
local ver1=$1
|
||||
@ -35,7 +41,19 @@ for file in `find . -name go.mod`; do
|
||||
dirpath=$(dirname $file)
|
||||
echo "Processing: $dirpath"
|
||||
|
||||
# Only process kubecm directory, skip others
|
||||
# Only process examples and kubecm directories
|
||||
|
||||
# Process examples directory (only build, no tests)
|
||||
if [[ $dirpath =~ "/examples/" ]]; then
|
||||
echo " the examples directory only needs to be built, not unit tests."
|
||||
cd $dirpath
|
||||
go mod tidy
|
||||
go build ./...
|
||||
cd -
|
||||
continue 1
|
||||
fi
|
||||
|
||||
# Process kubecm directory
|
||||
if [ "kubecm" != $(basename $dirpath) ]; then
|
||||
echo " Skipping: not kubecm directory"
|
||||
continue
|
||||
|
||||
785
.github/workflows/scripts/docker-services.sh
vendored
Executable file
785
.github/workflows/scripts/docker-services.sh
vendored
Executable file
@ -0,0 +1,785 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# GoFrame Docker Services Manager
|
||||
# For managing Docker services used in local development and testing
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
# Container name prefix
|
||||
PREFIX="goframe"
|
||||
|
||||
# Color definitions
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Service definitions
|
||||
declare -A SERVICES
|
||||
declare -A SERVICE_PORTS
|
||||
declare -A SERVICE_ENVS
|
||||
declare -A SERVICE_OPTS
|
||||
|
||||
# Basic services
|
||||
SERVICES["etcd"]="bitnamilegacy/etcd:3.4.24"
|
||||
SERVICE_PORTS["etcd"]="2379:2379"
|
||||
SERVICE_ENVS["etcd"]="-e ALLOW_NONE_AUTHENTICATION=yes"
|
||||
|
||||
SERVICES["redis"]="redis:7.0"
|
||||
SERVICE_PORTS["redis"]="6379:6379"
|
||||
SERVICE_OPTS["redis"]="--health-cmd 'redis-cli ping' --health-interval 10s --health-timeout 5s --health-retries 5"
|
||||
|
||||
SERVICES["mysql"]="mysql:5.7"
|
||||
SERVICE_PORTS["mysql"]="3306:3306"
|
||||
SERVICE_ENVS["mysql"]="-e MYSQL_DATABASE=test -e MYSQL_ROOT_PASSWORD=12345678"
|
||||
|
||||
SERVICES["mariadb"]="mariadb:11.4"
|
||||
SERVICE_PORTS["mariadb"]="3307:3306"
|
||||
SERVICE_ENVS["mariadb"]="-e MARIADB_DATABASE=test -e MARIADB_ROOT_PASSWORD=12345678"
|
||||
|
||||
SERVICES["postgres"]="postgres:17-alpine"
|
||||
SERVICE_PORTS["postgres"]="5432:5432"
|
||||
SERVICE_ENVS["postgres"]="-e POSTGRES_PASSWORD=12345678 -e POSTGRES_USER=postgres -e POSTGRES_DB=test -e TZ=Asia/Shanghai"
|
||||
SERVICE_OPTS["postgres"]="--health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5"
|
||||
|
||||
SERVICES["mssql"]="mcr.microsoft.com/mssql/server:2022-latest"
|
||||
SERVICE_PORTS["mssql"]="1433:1433"
|
||||
SERVICE_ENVS["mssql"]="-e TZ=Asia/Shanghai -e ACCEPT_EULA=Y -e MSSQL_SA_PASSWORD=LoremIpsum86"
|
||||
|
||||
SERVICES["clickhouse"]="clickhouse/clickhouse-server:24.11.1.2557-alpine"
|
||||
SERVICE_PORTS["clickhouse"]="9000:9000 -p 8123:8123 -p 9001:9001"
|
||||
|
||||
SERVICES["polaris"]="polarismesh/polaris-standalone:v1.17.2"
|
||||
SERVICE_PORTS["polaris"]="8090:8090 -p 8091:8091 -p 8093:8093 -p 9090:9090 -p 9091:9091"
|
||||
|
||||
SERVICES["oracle"]="loads/oracle-xe-11g-r2:11.2.0"
|
||||
SERVICE_PORTS["oracle"]="1521:1521"
|
||||
SERVICE_ENVS["oracle"]="-e ORACLE_ALLOW_REMOTE=true -e ORACLE_SID=XE -e ORACLE_DB_USER_NAME=system -e ORACLE_DB_PASSWORD=oracle"
|
||||
|
||||
SERVICES["dm"]="loads/dm:v8.1.2.128_ent_x86_64_ctm_pack4"
|
||||
SERVICE_PORTS["dm"]="5236:5236"
|
||||
|
||||
SERVICES["gaussdb"]="opengauss/opengauss:7.0.0-RC1.B023"
|
||||
SERVICE_PORTS["gaussdb"]="9950:5432"
|
||||
SERVICE_ENVS["gaussdb"]="-e GS_PASSWORD=UTpass@1234 -e TZ=Asia/Shanghai"
|
||||
SERVICE_OPTS["gaussdb"]="--privileged=true"
|
||||
|
||||
SERVICES["zookeeper"]="zookeeper:3.8"
|
||||
SERVICE_PORTS["zookeeper"]="2181:2181"
|
||||
|
||||
# Service groups
|
||||
GROUP_DB="mysql mariadb postgres mssql oracle dm gaussdb clickhouse"
|
||||
GROUP_CACHE="redis etcd"
|
||||
GROUP_REGISTRY="polaris zookeeper"
|
||||
GROUP_ALL="etcd redis mysql mariadb postgres mssql clickhouse polaris oracle dm gaussdb zookeeper"
|
||||
|
||||
# Working directories
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
WORKFLOW_DIR="$PROJECT_ROOT/.github/workflows"
|
||||
|
||||
# Print colored messages
|
||||
print_info() {
|
||||
echo -e "${BLUE}[INFO]${NC} $1"
|
||||
}
|
||||
|
||||
print_success() {
|
||||
echo -e "${GREEN}[OK]${NC} $1"
|
||||
}
|
||||
|
||||
print_warning() {
|
||||
echo -e "${YELLOW}[WARN]${NC} $1"
|
||||
}
|
||||
|
||||
print_error() {
|
||||
echo -e "${RED}[ERROR]${NC} $1"
|
||||
}
|
||||
|
||||
# Check if Docker is available
|
||||
check_docker() {
|
||||
if ! command -v docker &> /dev/null; then
|
||||
print_error "Docker is not installed or not in PATH"
|
||||
exit 1
|
||||
fi
|
||||
if ! docker info &> /dev/null; then
|
||||
print_error "Docker service is not running"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Get container name
|
||||
get_container_name() {
|
||||
echo "${PREFIX}-$1"
|
||||
}
|
||||
|
||||
# Start a single service
|
||||
start_service() {
|
||||
local service=$1
|
||||
local container_name=$(get_container_name "$service")
|
||||
local image="${SERVICES[$service]}"
|
||||
local ports="${SERVICE_PORTS[$service]}"
|
||||
local envs="${SERVICE_ENVS[$service]}"
|
||||
local opts="${SERVICE_OPTS[$service]}"
|
||||
|
||||
if [ -z "$image" ]; then
|
||||
print_error "Unknown service: $service"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check if container already exists
|
||||
if docker ps -a --format '{{.Names}}' | grep -q "^${container_name}$"; then
|
||||
if docker ps --format '{{.Names}}' | grep -q "^${container_name}$"; then
|
||||
print_warning "$service is already running"
|
||||
return 0
|
||||
else
|
||||
print_info "Starting existing container $service..."
|
||||
docker start "$container_name" > /dev/null
|
||||
print_success "$service started"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
|
||||
print_info "Starting $service..."
|
||||
|
||||
# Build docker run command
|
||||
local cmd="docker run -d --name $container_name"
|
||||
|
||||
# Add port mappings
|
||||
for port in $ports; do
|
||||
cmd="$cmd -p $port"
|
||||
done
|
||||
|
||||
# Add environment variables
|
||||
if [ -n "$envs" ]; then
|
||||
cmd="$cmd $envs"
|
||||
fi
|
||||
|
||||
# Add other options
|
||||
if [ -n "$opts" ]; then
|
||||
cmd="$cmd $opts"
|
||||
fi
|
||||
|
||||
cmd="$cmd $image"
|
||||
|
||||
if eval "$cmd" > /dev/null 2>&1; then
|
||||
print_success "$service started (container: $container_name)"
|
||||
else
|
||||
print_error "Failed to start $service"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Stop a single service
|
||||
stop_service() {
|
||||
local service=$1
|
||||
local container_name=$(get_container_name "$service")
|
||||
|
||||
if docker ps --format '{{.Names}}' | grep -q "^${container_name}$"; then
|
||||
print_info "Stopping $service..."
|
||||
docker stop "$container_name" > /dev/null
|
||||
print_success "$service stopped"
|
||||
else
|
||||
print_warning "$service is not running"
|
||||
fi
|
||||
}
|
||||
|
||||
# Remove a single service
|
||||
remove_service() {
|
||||
local service=$1
|
||||
local container_name=$(get_container_name "$service")
|
||||
|
||||
if docker ps -a --format '{{.Names}}' | grep -q "^${container_name}$"; then
|
||||
print_info "Removing $service..."
|
||||
docker rm -f "$container_name" > /dev/null
|
||||
print_success "$service removed"
|
||||
else
|
||||
print_warning "$service container does not exist"
|
||||
fi
|
||||
}
|
||||
|
||||
# View service logs
|
||||
logs_service() {
|
||||
local service=$1
|
||||
local container_name=$(get_container_name "$service")
|
||||
local lines=${2:-100}
|
||||
|
||||
if docker ps -a --format '{{.Names}}' | grep -q "^${container_name}$"; then
|
||||
docker logs --tail "$lines" -f "$container_name"
|
||||
else
|
||||
print_error "$service container does not exist"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Start docker-compose service
|
||||
start_compose_service() {
|
||||
local service=$1
|
||||
local compose_file=""
|
||||
|
||||
case $service in
|
||||
apollo)
|
||||
compose_file="$WORKFLOW_DIR/apollo/docker-compose.yml"
|
||||
;;
|
||||
nacos)
|
||||
compose_file="$WORKFLOW_DIR/nacos/docker-compose.yml"
|
||||
;;
|
||||
redis-cluster)
|
||||
compose_file="$WORKFLOW_DIR/redis/docker-compose.yml"
|
||||
;;
|
||||
consul)
|
||||
compose_file="$WORKFLOW_DIR/consul/docker-compose.yml"
|
||||
;;
|
||||
*)
|
||||
print_error "Unknown compose service: $service"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -f "$compose_file" ]; then
|
||||
print_info "Starting $service (docker-compose)..."
|
||||
docker compose -f "$compose_file" up -d
|
||||
print_success "$service started"
|
||||
else
|
||||
print_error "Compose file does not exist: $compose_file"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Stop docker-compose service
|
||||
stop_compose_service() {
|
||||
local service=$1
|
||||
local compose_file=""
|
||||
|
||||
case $service in
|
||||
apollo)
|
||||
compose_file="$WORKFLOW_DIR/apollo/docker-compose.yml"
|
||||
;;
|
||||
nacos)
|
||||
compose_file="$WORKFLOW_DIR/nacos/docker-compose.yml"
|
||||
;;
|
||||
redis-cluster)
|
||||
compose_file="$WORKFLOW_DIR/redis/docker-compose.yml"
|
||||
;;
|
||||
consul)
|
||||
compose_file="$WORKFLOW_DIR/consul/docker-compose.yml"
|
||||
;;
|
||||
*)
|
||||
print_error "Unknown compose service: $service"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -f "$compose_file" ]; then
|
||||
print_info "Stopping $service (docker-compose)..."
|
||||
docker compose -f "$compose_file" down
|
||||
print_success "$service stopped"
|
||||
else
|
||||
print_error "Compose file does not exist: $compose_file"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Show service status
|
||||
show_status() {
|
||||
echo ""
|
||||
echo -e "${CYAN}========== GoFrame Docker Services Status ==========${NC}"
|
||||
echo ""
|
||||
printf "%-15s %-12s %-30s %s\n" "SERVICE" "STATUS" "CONTAINER" "PORTS"
|
||||
echo "--------------------------------------------------------------------------------"
|
||||
|
||||
for service in $GROUP_ALL; do
|
||||
local container_name=$(get_container_name "$service")
|
||||
local status="stopped"
|
||||
local ports="-"
|
||||
|
||||
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${container_name}$"; then
|
||||
status="${GREEN}running${NC}"
|
||||
ports=$(docker port "$container_name" 2>/dev/null | tr '\n' ' ' || echo "-")
|
||||
elif docker ps -a --format '{{.Names}}' 2>/dev/null | grep -q "^${container_name}$"; then
|
||||
status="${YELLOW}stopped${NC}"
|
||||
else
|
||||
status="${RED}not created${NC}"
|
||||
fi
|
||||
|
||||
printf "%-15s %-22b %-30s %s\n" "$service" "$status" "$container_name" "$ports"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo -e "${CYAN}========== Compose Services ==========${NC}"
|
||||
echo ""
|
||||
|
||||
for compose_svc in apollo nacos redis-cluster consul; do
|
||||
local running=0
|
||||
case $compose_svc in
|
||||
apollo)
|
||||
running=$(docker ps --filter "name=apollo" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
nacos)
|
||||
running=$(docker ps --filter "name=nacos" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
redis-cluster)
|
||||
running=$(docker ps --filter "name=redis-" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
consul)
|
||||
running=$(docker ps --filter "name=consul" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ "$running" -gt 0 ]; then
|
||||
printf "%-15s ${GREEN}running${NC} (%d containers)\n" "$compose_svc" "$running"
|
||||
else
|
||||
printf "%-15s ${RED}stopped${NC}\n" "$compose_svc"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Show service information
|
||||
show_service_info() {
|
||||
echo ""
|
||||
echo -e "${CYAN}========== Available Services ==========${NC}"
|
||||
echo ""
|
||||
echo -e "${YELLOW}Basic Services (standalone containers):${NC}"
|
||||
echo ""
|
||||
printf "%-15s %-50s %s\n" "SERVICE" "IMAGE" "PORTS"
|
||||
echo "--------------------------------------------------------------------------------"
|
||||
|
||||
for service in $GROUP_ALL; do
|
||||
printf "%-15s %-50s %s\n" "$service" "${SERVICES[$service]}" "${SERVICE_PORTS[$service]}"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo -e "${YELLOW}Compose Services (multi-container):${NC}"
|
||||
echo " apollo - Apollo Config Center (8080, 8070, 8060, 13306)"
|
||||
echo " nacos - Nacos Registry (8848, 9848, 9555)"
|
||||
echo " redis-cluster - Redis Primary-Replica + Sentinel Cluster (6380-6382, 26379-26381)"
|
||||
echo " consul - Consul Service Discovery (8500, 8600)"
|
||||
echo ""
|
||||
echo -e "${YELLOW}Service Groups:${NC}"
|
||||
echo " db - Databases: $GROUP_DB"
|
||||
echo " cache - Cache: $GROUP_CACHE"
|
||||
echo " registry - Registry: $GROUP_REGISTRY"
|
||||
echo " all - All basic services"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Show help
|
||||
show_help() {
|
||||
echo ""
|
||||
echo -e "${CYAN}GoFrame Docker Services Manager${NC}"
|
||||
echo ""
|
||||
echo "Usage: $0 <command> [service|group] [options]"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " start <service|group> Start service or service group"
|
||||
echo " stop <service|group> Stop service or service group"
|
||||
echo " restart <service|group> Restart service or service group"
|
||||
echo " remove <service|group> Remove service container"
|
||||
echo " logs <service> [lines] View service logs (default 100 lines)"
|
||||
echo " status Show all service status"
|
||||
echo " info Show available service information"
|
||||
echo " clean Remove all goframe containers"
|
||||
echo " pull [service] Pull images"
|
||||
echo ""
|
||||
echo "Services:"
|
||||
echo " Basic: etcd, redis, mysql, mariadb, postgres, mssql,"
|
||||
echo " clickhouse, polaris, oracle, dm, gaussdb, zookeeper"
|
||||
echo " Compose: apollo, nacos, redis-cluster, consul"
|
||||
echo ""
|
||||
echo "Service Groups:"
|
||||
echo " db - All database services"
|
||||
echo " cache - Cache services (redis, etcd)"
|
||||
echo " registry - Registry services (polaris, zookeeper)"
|
||||
echo " all - All basic services"
|
||||
echo ""
|
||||
echo "Examples:"
|
||||
echo " $0 start mysql # Start MySQL"
|
||||
echo " $0 start db # Start all databases"
|
||||
echo " $0 start all # Start all basic services"
|
||||
echo " $0 start apollo # Start Apollo (compose)"
|
||||
echo " $0 stop all # Stop all basic services"
|
||||
echo " $0 logs mysql 50 # View last 50 lines of MySQL logs"
|
||||
echo " $0 status # View service status"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Parse service groups
|
||||
parse_services() {
|
||||
local input=$1
|
||||
case $input in
|
||||
db)
|
||||
echo "$GROUP_DB"
|
||||
;;
|
||||
cache)
|
||||
echo "$GROUP_CACHE"
|
||||
;;
|
||||
registry)
|
||||
echo "$GROUP_REGISTRY"
|
||||
;;
|
||||
all)
|
||||
echo "$GROUP_ALL"
|
||||
;;
|
||||
*)
|
||||
echo "$input"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Check if it's a compose service
|
||||
is_compose_service() {
|
||||
local service=$1
|
||||
case $service in
|
||||
apollo|nacos|redis-cluster|consul)
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Pull images
|
||||
pull_images() {
|
||||
local services=$1
|
||||
|
||||
if [ -z "$services" ]; then
|
||||
services="$GROUP_ALL"
|
||||
fi
|
||||
|
||||
for service in $services; do
|
||||
if [ -n "${SERVICES[$service]}" ]; then
|
||||
print_info "Pulling image: ${SERVICES[$service]}"
|
||||
docker pull "${SERVICES[$service]}"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Clean all goframe containers
|
||||
clean_all() {
|
||||
print_info "Removing all $PREFIX containers..."
|
||||
local containers=$(docker ps -a --filter "name=$PREFIX" --format '{{.Names}}')
|
||||
|
||||
if [ -n "$containers" ]; then
|
||||
for container in $containers; do
|
||||
docker rm -f "$container" > /dev/null
|
||||
print_success "Removed: $container"
|
||||
done
|
||||
else
|
||||
print_info "No $PREFIX containers found"
|
||||
fi
|
||||
}
|
||||
|
||||
# Get service status mark
|
||||
get_service_status_mark() {
|
||||
local service=$1
|
||||
local container_name=$(get_container_name "$service")
|
||||
|
||||
if docker ps --format '{{.Names}}' 2>/dev/null | grep -q "^${container_name}$"; then
|
||||
echo -e "${GREEN}*${NC}"
|
||||
else
|
||||
echo " "
|
||||
fi
|
||||
}
|
||||
|
||||
# Get compose service status mark
|
||||
get_compose_status_mark() {
|
||||
local service=$1
|
||||
local running=0
|
||||
|
||||
case $service in
|
||||
apollo)
|
||||
running=$(docker ps --filter "name=apollo" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
nacos)
|
||||
running=$(docker ps --filter "name=nacos" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
redis-cluster)
|
||||
running=$(docker ps --filter "name=redis-" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
consul)
|
||||
running=$(docker ps --filter "name=consul" --format '{{.Names}}' 2>/dev/null | wc -l)
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ "$running" -gt 0 ]; then
|
||||
echo -e "${GREEN}*${NC}"
|
||||
else
|
||||
echo " "
|
||||
fi
|
||||
}
|
||||
|
||||
# Service selection menu
|
||||
select_service_menu() {
|
||||
local action=$1
|
||||
local action_name=$2
|
||||
|
||||
echo ""
|
||||
echo -e "${CYAN}========== Select Service to ${action_name} ==========${NC}"
|
||||
|
||||
# Show running status for stop/restart/logs operations
|
||||
if [[ "$action" == "stop" || "$action" == "restart" || "$action" == "logs" ]]; then
|
||||
echo -e " (${GREEN}*${NC} indicates running)"
|
||||
fi
|
||||
echo ""
|
||||
echo -e "${YELLOW}Basic Services:${NC}"
|
||||
printf " %b1) etcd %b2) redis %b3) mysql\n" \
|
||||
"$(get_service_status_mark etcd)" "$(get_service_status_mark redis)" "$(get_service_status_mark mysql)"
|
||||
printf " %b4) mariadb %b5) postgres %b6) mssql\n" \
|
||||
"$(get_service_status_mark mariadb)" "$(get_service_status_mark postgres)" "$(get_service_status_mark mssql)"
|
||||
printf " %b7) clickhouse %b8) polaris %b9) oracle\n" \
|
||||
"$(get_service_status_mark clickhouse)" "$(get_service_status_mark polaris)" "$(get_service_status_mark oracle)"
|
||||
printf " %b10) dm %b11) gaussdb %b12) zookeeper\n" \
|
||||
"$(get_service_status_mark dm)" "$(get_service_status_mark gaussdb)" "$(get_service_status_mark zookeeper)"
|
||||
echo ""
|
||||
echo -e "${YELLOW}Compose Services:${NC}"
|
||||
printf " %b13) apollo %b14) nacos %b15) redis-cluster\n" \
|
||||
"$(get_compose_status_mark apollo)" "$(get_compose_status_mark nacos)" "$(get_compose_status_mark redis-cluster)"
|
||||
printf " %b16) consul\n" "$(get_compose_status_mark consul)"
|
||||
echo ""
|
||||
echo -e "${YELLOW}Service Groups:${NC}"
|
||||
echo " 17) db (all databases) 18) cache (cache services)"
|
||||
echo " 19) registry (registry services) 20) all (all basic services)"
|
||||
echo ""
|
||||
echo " 0) Back to main menu"
|
||||
echo ""
|
||||
read -p "Select [0-20]: " svc_choice
|
||||
|
||||
local svc=""
|
||||
case $svc_choice in
|
||||
1) svc="etcd" ;;
|
||||
2) svc="redis" ;;
|
||||
3) svc="mysql" ;;
|
||||
4) svc="mariadb" ;;
|
||||
5) svc="postgres" ;;
|
||||
6) svc="mssql" ;;
|
||||
7) svc="clickhouse" ;;
|
||||
8) svc="polaris" ;;
|
||||
9) svc="oracle" ;;
|
||||
10) svc="dm" ;;
|
||||
11) svc="gaussdb" ;;
|
||||
12) svc="zookeeper" ;;
|
||||
13) svc="apollo" ;;
|
||||
14) svc="nacos" ;;
|
||||
15) svc="redis-cluster" ;;
|
||||
16) svc="consul" ;;
|
||||
17) svc="db" ;;
|
||||
18) svc="cache" ;;
|
||||
19) svc="registry" ;;
|
||||
20) svc="all" ;;
|
||||
0) return ;;
|
||||
*)
|
||||
print_error "Invalid selection"
|
||||
return
|
||||
;;
|
||||
esac
|
||||
|
||||
case $action in
|
||||
start)
|
||||
if is_compose_service "$svc"; then
|
||||
start_compose_service "$svc"
|
||||
else
|
||||
for s in $(parse_services "$svc"); do
|
||||
start_service "$s"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
stop)
|
||||
if is_compose_service "$svc"; then
|
||||
stop_compose_service "$svc"
|
||||
else
|
||||
for s in $(parse_services "$svc"); do
|
||||
stop_service "$s"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
restart)
|
||||
if is_compose_service "$svc"; then
|
||||
stop_compose_service "$svc"
|
||||
start_compose_service "$svc"
|
||||
else
|
||||
for s in $(parse_services "$svc"); do
|
||||
stop_service "$s"
|
||||
start_service "$s"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
remove)
|
||||
for s in $(parse_services "$svc"); do
|
||||
remove_service "$s"
|
||||
done
|
||||
;;
|
||||
logs)
|
||||
if is_compose_service "$svc"; then
|
||||
print_error "For Compose services, please use 'docker compose logs'"
|
||||
else
|
||||
read -p "Number of lines (default 100): " lines
|
||||
lines=${lines:-100}
|
||||
logs_service "$svc" "$lines"
|
||||
fi
|
||||
;;
|
||||
pull)
|
||||
pull_images "$(parse_services "$svc")"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Interactive menu
|
||||
interactive_menu() {
|
||||
while true; do
|
||||
echo ""
|
||||
echo -e "${CYAN}========== GoFrame Docker Services Manager ==========${NC}"
|
||||
echo ""
|
||||
echo " 1) Start Service"
|
||||
echo " 2) Stop Service"
|
||||
echo " 3) Restart Service"
|
||||
echo " 4) Remove Service"
|
||||
echo " 5) View Logs"
|
||||
echo " 6) View Status"
|
||||
echo " 7) Service Info"
|
||||
echo " 8) Clean All Containers"
|
||||
echo " 9) Pull Images"
|
||||
echo " 0) Exit"
|
||||
echo ""
|
||||
read -p "Select operation [0-9]: " choice
|
||||
|
||||
case $choice in
|
||||
1)
|
||||
select_service_menu "start" "Start"
|
||||
;;
|
||||
2)
|
||||
select_service_menu "stop" "Stop"
|
||||
;;
|
||||
3)
|
||||
select_service_menu "restart" "Restart"
|
||||
;;
|
||||
4)
|
||||
select_service_menu "remove" "Remove"
|
||||
;;
|
||||
5)
|
||||
select_service_menu "logs" "View Logs"
|
||||
;;
|
||||
6)
|
||||
show_status
|
||||
;;
|
||||
7)
|
||||
show_service_info
|
||||
;;
|
||||
8)
|
||||
read -p "Confirm removing all goframe containers? [y/N]: " confirm
|
||||
if [[ "$confirm" =~ ^[Yy]$ ]]; then
|
||||
clean_all
|
||||
fi
|
||||
;;
|
||||
9)
|
||||
select_service_menu "pull" "Pull Images"
|
||||
;;
|
||||
0)
|
||||
echo "Goodbye!"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
print_error "Invalid selection"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
# Main function
|
||||
main() {
|
||||
check_docker
|
||||
|
||||
if [ $# -eq 0 ]; then
|
||||
interactive_menu
|
||||
exit 0
|
||||
fi
|
||||
|
||||
local command=$1
|
||||
local target=$2
|
||||
local extra=$3
|
||||
|
||||
case $command in
|
||||
start)
|
||||
if [ -z "$target" ]; then
|
||||
print_error "Please specify service name or service group"
|
||||
exit 1
|
||||
fi
|
||||
if is_compose_service "$target"; then
|
||||
start_compose_service "$target"
|
||||
else
|
||||
for service in $(parse_services "$target"); do
|
||||
start_service "$service"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
stop)
|
||||
if [ -z "$target" ]; then
|
||||
print_error "Please specify service name or service group"
|
||||
exit 1
|
||||
fi
|
||||
if is_compose_service "$target"; then
|
||||
stop_compose_service "$target"
|
||||
else
|
||||
for service in $(parse_services "$target"); do
|
||||
stop_service "$service"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
restart)
|
||||
if [ -z "$target" ]; then
|
||||
print_error "Please specify service name or service group"
|
||||
exit 1
|
||||
fi
|
||||
if is_compose_service "$target"; then
|
||||
stop_compose_service "$target"
|
||||
start_compose_service "$target"
|
||||
else
|
||||
for service in $(parse_services "$target"); do
|
||||
stop_service "$service"
|
||||
start_service "$service"
|
||||
done
|
||||
fi
|
||||
;;
|
||||
remove|rm)
|
||||
if [ -z "$target" ]; then
|
||||
print_error "Please specify service name or service group"
|
||||
exit 1
|
||||
fi
|
||||
for service in $(parse_services "$target"); do
|
||||
remove_service "$service"
|
||||
done
|
||||
;;
|
||||
logs)
|
||||
if [ -z "$target" ]; then
|
||||
print_error "Please specify service name"
|
||||
exit 1
|
||||
fi
|
||||
logs_service "$target" "${extra:-100}"
|
||||
;;
|
||||
status|ps)
|
||||
show_status
|
||||
;;
|
||||
info|list)
|
||||
show_service_info
|
||||
;;
|
||||
clean)
|
||||
clean_all
|
||||
;;
|
||||
pull)
|
||||
pull_images "$target"
|
||||
;;
|
||||
help|--help|-h)
|
||||
show_help
|
||||
;;
|
||||
*)
|
||||
print_error "Unknown command: $command"
|
||||
show_help
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
main "$@"
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -1,3 +0,0 @@
|
||||
[submodule "examples"]
|
||||
path = examples
|
||||
url = git@github.com:gogf/examples.git
|
||||
|
||||
@ -26,6 +26,8 @@ for file in `find ${workdir} -name go.mod`; do
|
||||
fi
|
||||
|
||||
cd $goModPath
|
||||
# Remove indirect dependencies
|
||||
sed -i '/\/\/ indirect/d' go.mod
|
||||
go mod tidy
|
||||
# Remove toolchain line if exists
|
||||
sed -i '' '/^toolchain/d' go.mod
|
||||
|
||||
@ -80,6 +80,8 @@ for file in `find ${workdir} -name go.mod`; do
|
||||
go mod edit -replace github.com/gogf/gf/contrib/drivers/pgsql/v2=../../contrib/drivers/pgsql
|
||||
go mod edit -replace github.com/gogf/gf/contrib/drivers/sqlite/v2=../../contrib/drivers/sqlite
|
||||
fi
|
||||
# Remove indirect dependencies
|
||||
sed -i '/\/\/ indirect/d' go.mod
|
||||
go mod tidy
|
||||
# Remove toolchain line if exists
|
||||
$SED_INPLACE '/^toolchain/d' go.mod
|
||||
@ -88,6 +90,8 @@ for file in `find ${workdir} -name go.mod`; do
|
||||
# it may not be possible to successfully upgrade. Please confirm before submitting the code
|
||||
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf"
|
||||
go list -f "{{if and (not .Indirect) (not .Main)}}{{.Path}}@${newVersion}{{end}}" -m all | grep "^github.com/gogf/gf" | xargs -L1 go get -v
|
||||
# Remove indirect dependencies
|
||||
sed -i '/\/\/ indirect/d' go.mod
|
||||
go mod tidy
|
||||
# Remove toolchain line if exists
|
||||
$SED_INPLACE '/^toolchain/d' go.mod
|
||||
|
||||
@ -3,11 +3,13 @@
|
||||
Thanks for taking the time to join our community and start contributing!
|
||||
|
||||
## With issues
|
||||
|
||||
- Use the search tool before opening a new issue.
|
||||
- Please provide source code and commit sha if you found a bug.
|
||||
- Review existing issues and provide feedback or react to them.
|
||||
|
||||
## With pull requests
|
||||
|
||||
- Open your pull request against `master`
|
||||
- Your pull request should have no more than two commits, if not you should squash them.
|
||||
- It should pass all tests in the available continuous integrations systems such as GitHub CI.
|
||||
|
||||
43
Makefile
43
Makefile
@ -6,10 +6,29 @@ tidy:
|
||||
./.make_tidy.sh
|
||||
|
||||
# execute "golangci-lint" to check code style
|
||||
# go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest
|
||||
.PHONY: lint
|
||||
lint:
|
||||
golangci-lint run -c .golangci.yml
|
||||
|
||||
# make branch to=v2.4.0
|
||||
.PHONY: branch
|
||||
branch:
|
||||
@set -e; \
|
||||
newVersion=$(to); \
|
||||
if [ -z "$$newVersion" ]; then \
|
||||
echo "Error: 'to' variable is required. Usage: make branch to=vX.Y.Z"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
branchName=fix/$$newVersion; \
|
||||
echo "Switching to master branch..."; \
|
||||
git checkout master; \
|
||||
echo "Pulling latest changes from master..."; \
|
||||
git pull origin master; \
|
||||
echo "Creating and switching to branch $$branchName from master..."; \
|
||||
git checkout -b $$branchName; \
|
||||
echo "Branch $$branchName created successfully!"
|
||||
|
||||
# make version to=v2.4.0
|
||||
.PHONY: version
|
||||
version:
|
||||
@ -18,6 +37,20 @@ version:
|
||||
./.make_version.sh ./ $$newVersion; \
|
||||
echo "make version to=$(to) done"
|
||||
|
||||
# make tag to=v2.4.0
|
||||
.PHONY: tag
|
||||
tag:
|
||||
@set -e; \
|
||||
newVersion=$(to); \
|
||||
echo "Switching to master branch..."; \
|
||||
git checkout master; \
|
||||
echo "Pulling latest changes from master..."; \
|
||||
git pull origin master; \
|
||||
echo "Creating annotated tag $$newVersion..."; \
|
||||
git tag -a $$newVersion -m "Release $$newVersion"; \
|
||||
echo "Pushing tag $$newVersion..."; \
|
||||
git push origin $$newVersion; \
|
||||
echo "Tag $$newVersion created and pushed successfully!"
|
||||
|
||||
# update submodules
|
||||
.PHONY: subup
|
||||
@ -43,3 +76,13 @@ subsync: subup
|
||||
git push origin; \
|
||||
fi; \
|
||||
cd ..;
|
||||
|
||||
# manage docker services for local development
|
||||
# usage: make docker or make docker cmd=start svc=mysql
|
||||
.PHONY: docker
|
||||
docker:
|
||||
@if [ -z "$(cmd)" ]; then \
|
||||
./.github/workflows/scripts/docker-services.sh; \
|
||||
else \
|
||||
./.github/workflows/scripts/docker-services.sh $(cmd) $(svc) $(extra); \
|
||||
fi
|
||||
|
||||
25
README.MD
25
README.MD
@ -1,3 +1,4 @@
|
||||
English | [简体中文](README.zh_CN.MD)
|
||||
|
||||
<div align=center>
|
||||
<img src="https://goframe.org/img/logo_full.png" width="300" alt="goframe gf logo"/>
|
||||
@ -23,24 +24,30 @@
|
||||
|
||||
A powerful framework for faster, easier, and more efficient project development.
|
||||
|
||||
## Installation
|
||||
|
||||
# Documentation
|
||||
```bash
|
||||
go get -u github.com/gogf/gf/v2
|
||||
```
|
||||
|
||||
- GoFrame Official Site: [https://goframe.org](https://goframe.org)
|
||||
- GoFrame Official Site(en): [https://goframe.org/en](https://goframe.org/en)
|
||||
- GoFrame Mirror Site(中文): [https://goframe.org.cn](https://goframe.org.cn)
|
||||
- GoFrame Mirror Site(github pages): [https://pages.goframe.org](https://pages.goframe.org)
|
||||
## Documentation
|
||||
|
||||
- Official Site: [https://goframe.org](https://goframe.org)
|
||||
- Official Site(en): [https://goframe.org/en](https://goframe.org/en)
|
||||
- 国内镜像: [https://goframe.org.cn](https://goframe.org.cn)
|
||||
- Mirror Site: [Github Pages](https://pages.goframe.org)
|
||||
- Mirror Site: [Offline Docs](https://github.com/gogf/goframe.org-pdf?tab=readme-ov-file#%E6%9C%80%E6%96%B0%E7%89%88%E6%9C%AC)
|
||||
- GoDoc API: [https://pkg.go.dev/github.com/gogf/gf/v2](https://pkg.go.dev/github.com/gogf/gf/v2)
|
||||
- Doc Source: [https://github.com/gogf/gf-site](https://github.com/gogf/gf-site)
|
||||
|
||||
|
||||
# Contributors
|
||||
## Contributors
|
||||
|
||||
💖 [Thanks to all the contributors who made GoFrame possible](https://github.com/gogf/gf/graphs/contributors) 💖
|
||||
|
||||
<a href="https://github.com/gogf/gf/graphs/contributors">
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.9.3" alt="goframe contributors"/>
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.9.8" alt="goframe contributors"/>
|
||||
</a>
|
||||
|
||||
# License
|
||||
## License
|
||||
|
||||
`GoFrame` is licensed under the [MIT License](LICENSE), 100% free and open-source, forever.
|
||||
|
||||
53
README.zh_CN.MD
Normal file
53
README.zh_CN.MD
Normal file
@ -0,0 +1,53 @@
|
||||
[English](README.MD) | 简体中文
|
||||
|
||||
<div align=center>
|
||||
<img src="https://goframe.org/img/logo_full.png" width="300" alt="goframe gf logo"/>
|
||||
|
||||
[](https://pkg.go.dev/github.com/gogf/gf/v2)
|
||||
[](https://github.com/gogf/gf/actions/workflows/ci-main.yml)
|
||||
[](https://scorecard.dev/viewer/?uri=github.com/gogf/gf)
|
||||
[](https://bestpractices.coreinfrastructure.org/projects/9233)
|
||||
[](https://goreportcard.com/report/github.com/gogf/gf/v2)
|
||||
[](https://codecov.io/gh/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
[](https://github.com/gogf/gf)
|
||||
|
||||
[](https://github.com/gogf/gf/releases)
|
||||
[](https://github.com/gogf/gf/pulls)
|
||||
[](https://github.com/gogf/gf/pulls?q=is%3Apr+is%3Aclosed)
|
||||
[](https://github.com/gogf/gf/issues)
|
||||
[](https://github.com/gogf/gf/issues?q=is%3Aissue+is%3Aclosed)
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
一个强大的框架,为了更快、更轻松、更高效的项目开发。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
go get -u github.com/gogf/gf/v2
|
||||
```
|
||||
|
||||
## 文档
|
||||
|
||||
- 官方网站: [https://goframe.org](https://goframe.org)
|
||||
- 官方网站(en): [https://goframe.org/en](https://goframe.org/en)
|
||||
- 国内镜像: [https://goframe.org.cn](https://goframe.org.cn)
|
||||
- 镜像网站: [Github Pages](https://pages.goframe.org)
|
||||
- 镜像网站: [离线文档](https://github.com/gogf/goframe.org-pdf?tab=readme-ov-file#%E6%9C%80%E6%96%B0%E7%89%88%E6%9C%AC)
|
||||
- Go包文档: [https://pkg.go.dev/github.com/gogf/gf/v2](https://pkg.go.dev/github.com/gogf/gf/v2)
|
||||
- 文档源码: [https://github.com/gogf/gf-site](https://github.com/gogf/gf-site)
|
||||
|
||||
## 贡献者
|
||||
|
||||
💖 [感谢所有使 GoFrame 成为可能的贡献者](https://github.com/gogf/gf/graphs/contributors) 💖
|
||||
|
||||
<a href="https://github.com/gogf/gf/graphs/contributors">
|
||||
<img src="https://goframe.org/img/contributors.svg?version=v2.9.5" alt="goframe contributors"/>
|
||||
</a>
|
||||
|
||||
## 许可证
|
||||
|
||||
`GoFrame` 采用 [MIT License](LICENSE) 许可,100% 免费和开源,永久保持。
|
||||
@ -1,3 +1,5 @@
|
||||
English | [简体中文](README.zh_CN.MD)
|
||||
|
||||
# gf
|
||||
|
||||
`gf` is a powerful CLI tool for building [GoFrame](https://goframe.org) application with convenience.
|
||||
@ -21,18 +23,18 @@ You can also install `gf` tool using pre-built binaries: <https://github.com/gog
|
||||
|
||||
3. Database support
|
||||
|
||||
| DB | builtin support | remarks |
|
||||
|:----------:|:---------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------:|
|
||||
| mysql | yes | - |
|
||||
| mariadb | yes | - |
|
||||
| tidb | yes | - |
|
||||
| mssql | yes | - |
|
||||
| oracle | yes | - |
|
||||
| pgsql | yes | - |
|
||||
| sqlite | yes | - |
|
||||
| sqlitecgo | no | to support sqlite database on 32bit architecture systems, manually add package import to the [source codes](./internal/cmd/cmd_gen_dao.go) and do the building. |
|
||||
| clickhouse | no | manually add package import to the [source codes](./internal/cmd/cmd_gen_dao.go) and do the building. |
|
||||
| dm | no | manually add package import to the [source codes](./internal/cmd/cmd_gen_dao.go) and do the building. |
|
||||
| DB | builtin support | remarks |
|
||||
| :--------: | :-------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
| mysql | yes | - |
|
||||
| mariadb | yes | - |
|
||||
| tidb | yes | - |
|
||||
| mssql | yes | - |
|
||||
| oracle | yes | - |
|
||||
| pgsql | yes | - |
|
||||
| sqlite | yes | - |
|
||||
| sqlitecgo | no | to support sqlite database on 32bit architecture systems, manually add package import to the [source codes](./internal/cmd/cmd_gen_dao.go) and do the building. |
|
||||
| clickhouse | yes | - |
|
||||
| dm | no | manually add package import to the [source codes](./internal/cmd/cmd_gen_dao.go) and do the building. |
|
||||
|
||||
## 2) Manually Install
|
||||
|
||||
@ -43,30 +45,31 @@ go install github.com/gogf/gf/cmd/gf/v2@v2.5.5 # certain version(should be >= v2
|
||||
|
||||
## 2. Commands
|
||||
|
||||
```html
|
||||
$ gf
|
||||
```shell
|
||||
$ gf -h
|
||||
USAGE
|
||||
gf COMMAND [OPTION]
|
||||
|
||||
COMMAND
|
||||
up upgrade GoFrame version/tool to latest one in current project
|
||||
env show current Golang environment variables
|
||||
fix auto fixing codes after upgrading to new GoFrame version
|
||||
run running go codes with hot-compiled-like feature
|
||||
gen automatically generate go files for dao/do/entity/pb/pbentity
|
||||
tpl template parsing and building commands
|
||||
init create and initialize an empty GoFrame project
|
||||
pack packing any file/directory to a resource file, or a go file
|
||||
build cross-building go project for lots of platforms
|
||||
docker build docker image for current GoFrame project
|
||||
install install gf binary to system (might need root/admin permission)
|
||||
version show version information of current binary
|
||||
up upgrade GoFrame version/tool to latest one in current project
|
||||
env show current Golang environment variables
|
||||
fix auto fixing codes after upgrading to new GoFrame version
|
||||
run running go codes with hot-compiled-like feature
|
||||
gen automatically generate go files for dao/do/entity/pb/pbentity
|
||||
tpl template parsing and building commands
|
||||
init create and initialize an empty GoFrame project
|
||||
pack packing any file/directory to a resource file, or a go file
|
||||
build cross-building go project for lots of platforms
|
||||
docker build docker image for current GoFrame project
|
||||
install install gf binary to system (might need root/admin permission)
|
||||
version show version information of current binary
|
||||
doc download https://pages.goframe.org/ to run locally
|
||||
|
||||
OPTION
|
||||
-y, --yes all yes for all command without prompt ask
|
||||
-v, --version show version information of current binary
|
||||
-d, --debug show internal detailed debugging information
|
||||
-h, --help more information about this command
|
||||
-y, --yes all yes for all command without prompt ask
|
||||
-v, --version show version information of current binary
|
||||
-d, --debug show internal detailed debugging information
|
||||
-h, --help more information about this command
|
||||
|
||||
ADDITIONAL
|
||||
Use "gf COMMAND -h" for details about a command.
|
||||
|
||||
82
cmd/gf/README.zh_CN.MD
Normal file
82
cmd/gf/README.zh_CN.MD
Normal file
@ -0,0 +1,82 @@
|
||||
[English](README.MD) | 简体中文
|
||||
|
||||
# gf
|
||||
|
||||
`gf` 是一个强大的 CLI 工具,用于便捷地构建 [GoFrame](https://goframe.org) 应用程序。
|
||||
|
||||
## 1. 安装
|
||||
|
||||
## 1) 预编译二进制文件
|
||||
|
||||
您也可以使用预构建的二进制文件安装 `gf` 工具:<https://github.com/gogf/gf/releases>
|
||||
|
||||
1. `Mac` & `Linux`
|
||||
|
||||
```shell
|
||||
wget -O gf https://github.com/gogf/gf/releases/latest/download/gf_$(go env GOOS)_$(go env GOARCH) && chmod +x gf && ./gf install -y && rm ./gf
|
||||
```
|
||||
|
||||
> 如果您使用 `zsh`,您可能需要通过命令 `alias gf=gf` 重命名别名以解决 `gf` 和 `git fetch` 之间的冲突。
|
||||
|
||||
2. `Windows`
|
||||
手动下载,在命令行中执行,然后按照说明操作。
|
||||
|
||||
3. 数据库支持
|
||||
|
||||
| 数据库 | 内置支持 | 说明 |
|
||||
| :--------: | :-------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
| mysql | 是 | - |
|
||||
| mariadb | 是 | - |
|
||||
| tidb | 是 | - |
|
||||
| mssql | 是 | - |
|
||||
| oracle | 是 | - |
|
||||
| pgsql | 是 | - |
|
||||
| sqlite | 是 | - |
|
||||
| sqlitecgo | 否 | 要在 32 位架构系统上支持 sqlite 数据库,请手动向[源代码](./internal/cmd/cmd_gen_dao.go)添加包导入并进行构建。 |
|
||||
| clickhouse | 是 | - |
|
||||
| dm | 否 | 手动向[源代码](./internal/cmd/cmd_gen_dao.go)添加包导入并进行构建。 |
|
||||
|
||||
## 2) 手动安装
|
||||
|
||||
```shell
|
||||
go install github.com/gogf/gf/cmd/gf/v2@latest # 最新版本
|
||||
go install github.com/gogf/gf/cmd/gf/v2@v2.5.5 # 特定版本(应该 >= v2.5.5)
|
||||
```
|
||||
|
||||
## 2. 命令
|
||||
|
||||
```shell
|
||||
$ gf -h
|
||||
用法
|
||||
gf 命令 [选项]
|
||||
|
||||
命令
|
||||
up 升级项目中的 GoFrame 版本/工具到最新版本
|
||||
env 显示当前 Golang 环境变量
|
||||
fix 升级到新 GoFrame 版本后自动修复代码
|
||||
run 运行 go 代码,具有热编译功能
|
||||
gen 自动生成 dao/do/entity/pb/pbentity 的 go 文件
|
||||
tpl 模板解析和构建命令
|
||||
init 创建并初始化一个空的 GoFrame 项目
|
||||
pack 将任何文件/目录打包到资源文件或 go 文件
|
||||
build 为多个平台交叉编译 go 项目
|
||||
docker 为当前 GoFrame 项目构建 docker 镜像
|
||||
install 将 gf 二进制文件安装到系统(可能需要 root/admin 权限)
|
||||
version 显示当前二进制文件的版本信息
|
||||
doc 下载 https://pages.goframe.org/ 本地运行
|
||||
|
||||
选项
|
||||
-y, --yes 对所有命令都使用 yes,不再提示
|
||||
-v, --version 显示当前二进制文件的版本信息
|
||||
-d, --debug 显示内部详细的调试信息
|
||||
-h, --help 显示此命令的更多信息
|
||||
|
||||
附加信息
|
||||
使用 "gf 命令 -h" 获取有关命令的详细信息。
|
||||
```
|
||||
|
||||
## 3. 常见问题
|
||||
|
||||
### 1). 命令 `gf run` 返回 `pipe: too many open files`
|
||||
|
||||
请使用 `ulimit -n 65535` 扩大系统配置以增加当前终端 shell 会话的最大打开文件数,然后再运行 `gf run`。
|
||||
@ -3,18 +3,18 @@ module github.com/gogf/gf/cmd/gf/v2
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.3
|
||||
github.com/gogf/gf/v2 v2.9.3
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.8
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.8
|
||||
github.com/gogf/gf/v2 v2.9.8
|
||||
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f
|
||||
github.com/olekukonko/tablewriter v1.0.9
|
||||
github.com/olekukonko/tablewriter v1.1.0
|
||||
github.com/schollz/progressbar/v3 v3.15.0
|
||||
golang.org/x/mod v0.26.0
|
||||
golang.org/x/tools v0.35.0
|
||||
golang.org/x/mod v0.25.0
|
||||
golang.org/x/tools v0.26.0
|
||||
)
|
||||
|
||||
require (
|
||||
@ -23,7 +23,7 @@ require (
|
||||
github.com/ClickHouse/clickhouse-go/v2 v2.0.15 // indirect
|
||||
github.com/clbanning/mxj/v2 v2.7.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/emirpasic/gods/v2 v2.0.0-alpha // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||
@ -37,7 +37,7 @@ require (
|
||||
github.com/grokify/html-strip-tags-go v0.1.0 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/magiconair/properties v1.8.10 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/microsoft/go-mssqldb v1.7.1 // indirect
|
||||
@ -51,16 +51,16 @@ require (
|
||||
github.com/shopspring/decimal v1.3.1 // indirect
|
||||
github.com/sijms/go-ora/v2 v2.7.10 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.37.0 // indirect
|
||||
golang.org/x/crypto v0.41.0 // indirect
|
||||
golang.org/x/net v0.43.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
go.opentelemetry.io/otel v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||
golang.org/x/crypto v0.38.0 // indirect
|
||||
golang.org/x/net v0.40.0 // indirect
|
||||
golang.org/x/sync v0.14.0 // indirect
|
||||
golang.org/x/sys v0.35.0 // indirect
|
||||
golang.org/x/term v0.34.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
golang.org/x/term v0.32.0 // indirect
|
||||
golang.org/x/text v0.25.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.22.5 // indirect
|
||||
modernc.org/mathutil v1.5.0 // indirect
|
||||
|
||||
@ -27,8 +27,8 @@ 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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/emirpasic/gods/v2 v2.0.0-alpha h1:dwFlh8pBg1VMOXWGipNMRt8v96dKAIvBehtCt6OtunU=
|
||||
github.com/emirpasic/gods/v2 v2.0.0-alpha/go.mod h1:W0y4M2dtBB9U5z3YlghmpuUhiaZT2h6yoeE+C1sCp6A=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
@ -46,20 +46,20 @@ github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiU
|
||||
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
|
||||
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.3 h1:/Nw0Tg7X4zlF8x72e2slQidiY0J+kqDpLuejNSmaLWk=
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.3/go.mod h1:NkdRgePcrg6/PD7SUqedtfr3a4E4n3uwVLZ+Xdnq2VU=
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.3 h1:kfDQVyHpbpUBS4cZ/8YbAnzqh6KaKP019nXl0FTplZE=
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.3/go.mod h1:c/rS7hbTqfTsZdqt6jOE59jeqsPrnYTaUwW2XB+N0kI=
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.3 h1:P4jrnp+Vmh3kDeaH/kyHPI6rfoMmQD+sPJa716aMbS0=
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.3/go.mod h1:yEhfx78wgpxUJhH9C9bWJ7I3JLcVCzUg11A4ORYTKeg=
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.3 h1:TKpjp/jFF2tiOMsKH2PTxZbGFctsi8+CN+dsTA70VEc=
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.3/go.mod h1:v10xiQ7LA2dF4RNHa2pojCPgAoXCJEKK1Iw0DRvMwzQ=
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.3 h1:8QgjRauacL7nOKxEHxNiHGL+041ke9lXHe93NIvPYw8=
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.3/go.mod h1:umGqltjrzpY2Il2GF0GX1/TQAk8Xz6vYQM4/q3BuqIo=
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.3 h1:xXOneBClGz9UQmgjc1qRRufPPTtbASDJv32oSdFz+D0=
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.3/go.mod h1:97jRMN7LgWrNgJB3DorP0zlSchGicLO2W6gXk2tffW8=
|
||||
github.com/gogf/gf/v2 v2.9.3 h1:qjN4s55FfUzxZ1AE8vUHNDX3V0eIOUGXhF2DjRTVZQ4=
|
||||
github.com/gogf/gf/v2 v2.9.3/go.mod h1:w6rcfD13SmO7FKI80k9LSLiSMGqpMYp50Nfkrrc2sEE=
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.8 h1:L72OB2HPuZSHtJ2ipBzI+62rGGDRdwYjequ1v+zctpg=
|
||||
github.com/gogf/gf/contrib/drivers/clickhouse/v2 v2.9.8/go.mod h1:D0UySg70Bd264F5AScYmz1Hl8vjzlUJ7YvqBJc5OFbo=
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.8 h1:DT5zHfo9/VkbJ+TF7kUasvv4dbU5uctoj+JGbrzgdYE=
|
||||
github.com/gogf/gf/contrib/drivers/mssql/v2 v2.9.8/go.mod h1:cDd91Zd8LxFF+xxOflRRqw0WTTCpAJ0nf0KKRA+nvTE=
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8 h1:XZ4Ya/50xpjf81+4genr33iJXR2dxJmqYKxGyXlLRqA=
|
||||
github.com/gogf/gf/contrib/drivers/mysql/v2 v2.9.8/go.mod h1:wtm2NJb/L3CbDOmyUc7TsOpWHTCMakg1QRG7B/oKrRs=
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.8 h1:ZrqABJsUnhNDz8VAem1XXONBTywl6r+GHQH05i+4W1g=
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 v2.9.8/go.mod h1:YTFyeVk2Rgu/JMUhFxkjYzWaBc+yZ6wAvY54XVZoNko=
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.8 h1:Dc227FD1uf9nNBPFEjMEgIoAJbAgeYeNrOrjviDgPzY=
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 v2.9.8/go.mod h1:o3EpB4Ti3+x/axzRMJg2k7TrLiWZiSTxP0v64LBkk5k=
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.8 h1:LHEhzsBfIo8xHvOUuLDQW1q7Qix1vnBabH/iivCRghs=
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 v2.9.8/go.mod h1:SX6dRONaJGafzCoMIrn8CkRM4fIvtmJRt/aYclUHy3Q=
|
||||
github.com/gogf/gf/v2 v2.9.8 h1:El0HwksTzeRk0DQV4Lh7S9DbsIwKInhHSHGcH7qJumM=
|
||||
github.com/gogf/gf/v2 v2.9.8/go.mod h1:Svl1N+E8G/QshU2DUbh/3J/AJauqCgUnxHurXWR4Qx0=
|
||||
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f h1:7xfXR/BhG3JDqO1s45n65Oyx9t4E/UqDOXep6jXdLCM=
|
||||
github.com/gogf/selfupdate v0.0.0-20231215043001-5c48c528462f/go.mod h1:HnYoio6S7VaFJdryKcD/r9HgX+4QzYfr00XiXUo/xz0=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
@ -100,8 +100,9 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
@ -116,8 +117,8 @@ github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5
|
||||
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
|
||||
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
|
||||
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
|
||||
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
|
||||
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
|
||||
github.com/olekukonko/tablewriter v1.1.0 h1:N0LHrshF4T39KvI96fn6GT8HEjXRXYNDrDjKFDB7RIY=
|
||||
github.com/olekukonko/tablewriter v1.1.0/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
|
||||
github.com/paulmach/orb v0.7.1 h1:Zha++Z5OX/l168sqHK3k4z18LDvr+YAO/VjK0ReQ9rU=
|
||||
github.com/paulmach/orb v0.7.1/go.mod h1:FWRlTgl88VI1RBx/MkrwWDRhQ96ctqMCh8boXhmqB/A=
|
||||
github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=
|
||||
@ -134,8 +135,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qq
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/schollz/progressbar/v3 v3.15.0 h1:cNZmcNiVyea6oofBTg80ZhVXxf3wG/JoAhqCCwopkQo=
|
||||
github.com/schollz/progressbar/v3 v3.15.0/go.mod h1:ncBdc++eweU0dQoeZJ3loXoAc+bjaallHRIm8pVVeQM=
|
||||
github.com/shirou/gopsutil v2.19.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
@ -150,8 +151,8 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||
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/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tklauser/go-sysconf v0.3.10/go.mod h1:C8XykCvCb+Gn0oNCWPIlcb0RuglQTYaQ2hGm7jmxEFk=
|
||||
github.com/tklauser/numcpus v0.4.0/go.mod h1:1+UI3pD8NW14VMwdgJNJ1ESk2UnwhAnz5hMwiKKqXCQ=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
@ -160,38 +161,40 @@ github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQ
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.7.0/go.mod h1:5BdUoMIz5WEs0vt0CUEMtSSaTSHBBVwrhnz7+nrD5xk=
|
||||
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
|
||||
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
|
||||
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.7.0/go.mod h1:fzLSB9nqR2eXzxPXb2JW9IKE+ScyXA48yyE4TNvoHqU=
|
||||
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
|
||||
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
|
||||
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
|
||||
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
|
||||
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
||||
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
|
||||
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@ -201,24 +204,25 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20210228012217-479acdf4ea46/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.24.0/go.mod h1:lOBK/LVxemqiMij05LGJ0tzNr8xlmwBRJ81PX6wVLH8=
|
||||
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
|
||||
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
|
||||
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
|
||||
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
|
||||
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
|
||||
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
|
||||
golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ=
|
||||
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@ -14,5 +14,9 @@ replace (
|
||||
github.com/gogf/gf/contrib/drivers/oracle/v2 => ../../contrib/drivers/oracle
|
||||
github.com/gogf/gf/contrib/drivers/pgsql/v2 => ../../contrib/drivers/pgsql
|
||||
github.com/gogf/gf/contrib/drivers/sqlite/v2 => ../../contrib/drivers/sqlite
|
||||
github.com/gogf/gf/contrib/drivers/mariadb/v2 => ../../contrib/drivers/mariadb
|
||||
github.com/gogf/gf/contrib/drivers/tidb/v2 => ../../contrib/drivers/tidb
|
||||
github.com/gogf/gf/contrib/drivers/oceanbase/v2 => ../../contrib/drivers/oceanbase
|
||||
github.com/gogf/gf/contrib/drivers/gaussdb/v2 => ../../contrib/drivers/gaussdb
|
||||
github.com/gogf/gf/v2 => ../../
|
||||
)
|
||||
|
||||
@ -30,12 +30,10 @@ import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
var (
|
||||
Build = cBuild{
|
||||
nodeNameInConfigFile: "gfcli.build",
|
||||
packedGoFileName: "internal/packed/build_pack_data.go",
|
||||
}
|
||||
)
|
||||
var Build = cBuild{
|
||||
nodeNameInConfigFile: "gfcli.build",
|
||||
packedGoFileName: "internal/packed/build_pack_data.go",
|
||||
}
|
||||
|
||||
type cBuild struct {
|
||||
g.Meta `name:"build" brief:"{cBuildBrief}" dc:"{cBuildDc}" eg:"{cBuildEg}" ad:"{cBuildAd}"`
|
||||
@ -65,45 +63,67 @@ It provides much more features for building binary:
|
||||
`
|
||||
cBuildAd = `
|
||||
PLATFORMS
|
||||
aix ppc64
|
||||
android 386,amd64,arm,arm64
|
||||
darwin amd64,arm64
|
||||
dragonfly amd64
|
||||
freebsd 386,amd64,arm
|
||||
linux 386,amd64,arm,arm64,ppc64,ppc64le,mips,mipsle,mips64,mips64le
|
||||
illumos amd64
|
||||
ios arm64
|
||||
js wasm
|
||||
linux 386,amd64,arm,arm64,loong64,mips,mipsle,mips64,mips64le,ppc64,ppc64le,riscv64,s390x
|
||||
netbsd 386,amd64,arm
|
||||
openbsd 386,amd64,arm
|
||||
windows 386,amd64
|
||||
openbsd 386,amd64,arm,arm64
|
||||
plan9 386,amd64,arm
|
||||
solaris amd64
|
||||
wasip1 wasm
|
||||
windows 386,amd64,arm,arm64
|
||||
`
|
||||
// https://golang.google.cn/doc/install/source
|
||||
cBuildPlatforms = `
|
||||
aix ppc64
|
||||
android 386
|
||||
android amd64
|
||||
android arm
|
||||
android arm64
|
||||
darwin amd64
|
||||
darwin arm64
|
||||
ios amd64
|
||||
ios arm64
|
||||
dragonfly amd64
|
||||
freebsd 386
|
||||
freebsd amd64
|
||||
freebsd arm
|
||||
illumos amd64
|
||||
ios arm64
|
||||
js wasm
|
||||
linux 386
|
||||
linux amd64
|
||||
linux arm
|
||||
linux arm64
|
||||
linux ppc64
|
||||
linux ppc64le
|
||||
linux loong64
|
||||
linux mips
|
||||
linux mipsle
|
||||
linux mips64
|
||||
linux mips64le
|
||||
linux ppc64
|
||||
linux ppc64le
|
||||
linux riscv64
|
||||
linux s390x
|
||||
netbsd 386
|
||||
netbsd amd64
|
||||
netbsd arm
|
||||
openbsd 386
|
||||
openbsd amd64
|
||||
openbsd arm
|
||||
windows 386
|
||||
windows amd64
|
||||
android arm
|
||||
dragonfly amd64
|
||||
openbsd arm64
|
||||
plan9 386
|
||||
plan9 amd64
|
||||
plan9 arm
|
||||
solaris amd64
|
||||
wasip1 wasm
|
||||
windows 386
|
||||
windows amd64
|
||||
windows arm
|
||||
windows arm64
|
||||
`
|
||||
)
|
||||
|
||||
|
||||
@ -7,9 +7,11 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
@ -20,6 +22,7 @@ import (
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gtag"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/geninit"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/allyes"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
|
||||
@ -44,6 +47,13 @@ const (
|
||||
gf init my-project
|
||||
gf init my-mono-repo -m
|
||||
gf init my-mono-repo -a
|
||||
gf init my-project -u
|
||||
gf init my-project -g "github.com/myorg/myproject"
|
||||
gf init -r github.com/gogf/template-single my-project
|
||||
gf init -r github.com/gogf/examples/httpserver/jwt my-jwt
|
||||
gf init -r github.com/gogf/gf/cmd/gf/v2@v2.9.7 mygf
|
||||
gf init -r github.com/gogf/gf/cmd/gf/v2 mygf -s
|
||||
gf init -i
|
||||
`
|
||||
cInitNameBrief = `
|
||||
name for the project. It will create a folder with NAME in current directory.
|
||||
@ -55,6 +65,16 @@ The NAME will also be the module name for the project.
|
||||
cInitGitignore = ".gitignore"
|
||||
)
|
||||
|
||||
// defaultTemplates is the list of predefined templates for interactive selection
|
||||
var defaultTemplates = []struct {
|
||||
Name string
|
||||
Repo string
|
||||
Desc string
|
||||
}{
|
||||
{"template-single", "github.com/gogf/template-single", "Single project template"},
|
||||
{"template-mono", "github.com/gogf/template-mono", "Mono-repo project template"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
gtag.Sets(g.MapStrStr{
|
||||
`cInitBrief`: cInitBrief,
|
||||
@ -64,17 +84,86 @@ func init() {
|
||||
}
|
||||
|
||||
type cInitInput struct {
|
||||
g.Meta `name:"init"`
|
||||
Name string `name:"NAME" arg:"true" v:"required" brief:"{cInitNameBrief}"`
|
||||
Mono bool `name:"mono" short:"m" brief:"initialize a mono-repo instead a single-repo" orphan:"true"`
|
||||
MonoApp bool `name:"monoApp" short:"a" brief:"initialize a mono-repo-app instead a single-repo" orphan:"true"`
|
||||
Update bool `name:"update" short:"u" brief:"update to the latest goframe version" orphan:"true"`
|
||||
Module string `name:"module" short:"g" brief:"custom go module"`
|
||||
g.Meta `name:"init"`
|
||||
Name string `name:"NAME" arg:"true" brief:"{cInitNameBrief}"`
|
||||
Mono bool `name:"mono" short:"m" brief:"initialize a mono-repo instead a single-repo" orphan:"true"`
|
||||
MonoApp bool `name:"monoApp" short:"a" brief:"initialize a mono-repo-app instead a single-repo" orphan:"true"`
|
||||
Update bool `name:"update" short:"u" brief:"update to the latest goframe version" orphan:"true"`
|
||||
Module string `name:"module" short:"g" brief:"custom go module"`
|
||||
Repo string `name:"repo" short:"r" brief:"remote repository URL for template download"`
|
||||
SelectVer bool `name:"select" short:"s" brief:"enable interactive version selection for remote template" orphan:"true"`
|
||||
Interactive bool `name:"interactive" short:"i" brief:"enable interactive mode to select template" orphan:"true"`
|
||||
}
|
||||
|
||||
type cInitOutput struct{}
|
||||
|
||||
func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err error) {
|
||||
// Check if using remote template mode
|
||||
if in.Repo != "" || in.Interactive {
|
||||
return c.initFromRemote(ctx, in)
|
||||
}
|
||||
|
||||
// If no name provided and no remote mode, enter interactive mode
|
||||
if in.Name == "" {
|
||||
return c.initInteractive(ctx, in)
|
||||
}
|
||||
|
||||
// Default: use built-in template
|
||||
return c.initFromBuiltin(ctx, in)
|
||||
}
|
||||
|
||||
// initFromRemote initializes project from remote repository
|
||||
func (c cInit) initFromRemote(ctx context.Context, in cInitInput) (out *cInitOutput, err error) {
|
||||
repo := in.Repo
|
||||
name := in.Name
|
||||
|
||||
// If interactive mode and no repo specified, let user select
|
||||
if in.Interactive && repo == "" {
|
||||
var modPath string
|
||||
var upgradeDeps bool
|
||||
repo, name, modPath, upgradeDeps, err = interactiveSelectTemplate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if modPath != "" {
|
||||
in.Module = modPath
|
||||
}
|
||||
if upgradeDeps {
|
||||
in.Update = true
|
||||
}
|
||||
}
|
||||
|
||||
if repo == "" {
|
||||
return nil, fmt.Errorf("repository URL is required for remote template mode")
|
||||
}
|
||||
|
||||
// Default name to repo basename if empty
|
||||
if name == "" {
|
||||
name = gfile.Basename(repo)
|
||||
mlog.Printf("Using repository basename as project name: %s", name)
|
||||
}
|
||||
|
||||
mlog.Print("initializing from remote template...")
|
||||
|
||||
opts := &geninit.ProcessOptions{
|
||||
SelectVersion: in.SelectVer,
|
||||
ModulePath: in.Module,
|
||||
UpgradeDeps: in.Update,
|
||||
}
|
||||
|
||||
if err = geninit.Process(ctx, repo, name, opts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mlog.Print("initialization done!")
|
||||
if name != "" && name != "." {
|
||||
mlog.Printf(`you can now run "cd %s && gf run main.go" to start your journey, enjoy!`, name)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// initFromBuiltin initializes project from built-in template
|
||||
func (c cInit) initFromBuiltin(ctx context.Context, in cInitInput) (out *cInitOutput, err error) {
|
||||
var overwrote = false
|
||||
if !gfile.IsEmpty(in.Name) && !allyes.Check() {
|
||||
s := gcmd.Scanf(`the folder "%s" is not empty, files might be overwrote, continue? [y/n]: `, in.Name)
|
||||
@ -149,6 +238,9 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
|
||||
return
|
||||
}
|
||||
|
||||
// Format the generated Go files.
|
||||
utils.GoFmt(in.Name)
|
||||
|
||||
// Update the GoFrame version.
|
||||
if in.Update {
|
||||
mlog.Print("update goframe...")
|
||||
@ -180,3 +272,170 @@ func (c cInit) Index(ctx context.Context, in cInitInput) (out *cInitOutput, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// initInteractive enters interactive mode when no arguments provided
|
||||
func (c cInit) initInteractive(ctx context.Context, in cInitInput) (out *cInitOutput, err error) {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
// Ask user which mode to use
|
||||
fmt.Println("\nPlease select initialization mode:")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
fmt.Println(" [1] Built-in template (default)")
|
||||
fmt.Println(" [2] Remote template")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
|
||||
fmt.Print("Select mode [1-2] (default: 1): ")
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
mlog.Fatalf("failed to read input: %v", err)
|
||||
return
|
||||
}
|
||||
input = strings.TrimSpace(input)
|
||||
|
||||
if input == "2" {
|
||||
in.Interactive = true
|
||||
return c.initFromRemote(ctx, in)
|
||||
}
|
||||
|
||||
// Built-in template mode
|
||||
fmt.Println("\nPlease select project type:")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
fmt.Println(" [1] Single project (default)")
|
||||
fmt.Println(" [2] Mono-repo project")
|
||||
fmt.Println(" [3] Mono-repo app")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
|
||||
fmt.Print("Select type [1-3] (default: 1): ")
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
mlog.Fatalf("failed to read input: %v", err)
|
||||
return
|
||||
}
|
||||
input = strings.TrimSpace(input)
|
||||
|
||||
switch input {
|
||||
case "2":
|
||||
in.Mono = true
|
||||
case "3":
|
||||
in.MonoApp = true
|
||||
}
|
||||
|
||||
// Get project name
|
||||
for {
|
||||
fmt.Print("Enter project name: ")
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
mlog.Fatalf("failed to read input: %v", err)
|
||||
return
|
||||
}
|
||||
in.Name = strings.TrimSpace(input)
|
||||
if in.Name != "" {
|
||||
break
|
||||
}
|
||||
fmt.Println("Project name cannot be empty")
|
||||
}
|
||||
|
||||
// Get module path (optional)
|
||||
fmt.Printf("Enter Go module path (leave empty to use \"%s\"): ", in.Name)
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
mlog.Fatalf("failed to read input: %v", err)
|
||||
return
|
||||
}
|
||||
in.Module = strings.TrimSpace(input)
|
||||
|
||||
// Ask about update
|
||||
fmt.Print("Update to latest GoFrame version? [y/N]: ")
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
mlog.Fatalf("failed to read input: %v", err)
|
||||
return
|
||||
}
|
||||
input = strings.TrimSpace(strings.ToLower(input))
|
||||
in.Update = input == "y" || input == "yes"
|
||||
|
||||
fmt.Println()
|
||||
return c.initFromBuiltin(ctx, in)
|
||||
}
|
||||
|
||||
// interactiveSelectTemplate prompts user to select a template interactively
|
||||
func interactiveSelectTemplate() (repo, name, modPath string, upgradeDeps bool, err error) {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
// 1. Select template
|
||||
fmt.Println("\nPlease select a project template:")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
for i, t := range defaultTemplates {
|
||||
fmt.Printf(" [%d] %s - %s\n", i+1, t.Name, t.Desc)
|
||||
}
|
||||
fmt.Printf(" [%d] Custom repository URL\n", len(defaultTemplates)+1)
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
|
||||
for {
|
||||
fmt.Printf("Select template [1-%d]: ", len(defaultTemplates)+1)
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to read template selection: %w", err)
|
||||
}
|
||||
input = strings.TrimSpace(input)
|
||||
|
||||
idx, e := strconv.Atoi(input)
|
||||
if e != nil || idx < 1 || idx > len(defaultTemplates)+1 {
|
||||
fmt.Printf("Invalid selection, please enter a number between 1-%d\n", len(defaultTemplates)+1)
|
||||
continue
|
||||
}
|
||||
|
||||
if idx <= len(defaultTemplates) {
|
||||
repo = defaultTemplates[idx-1].Repo
|
||||
fmt.Printf("Selected: %s\n\n", repo)
|
||||
} else {
|
||||
// Custom URL
|
||||
fmt.Print("Enter repository URL: ")
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to read repository URL: %w", err)
|
||||
}
|
||||
repo = strings.TrimSpace(input)
|
||||
if repo == "" {
|
||||
fmt.Println("Repository URL cannot be empty")
|
||||
continue
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// 2. Enter project name
|
||||
for {
|
||||
fmt.Print("Enter project name: ")
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to read project name: %w", err)
|
||||
}
|
||||
name = strings.TrimSpace(input)
|
||||
if name == "" {
|
||||
fmt.Println("Project name cannot be empty")
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// 3. Enter module path (optional)
|
||||
fmt.Printf("Enter Go module path (leave empty to use \"%s\"): ", name)
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to read module path: %w", err)
|
||||
}
|
||||
modPath = strings.TrimSpace(input)
|
||||
|
||||
// 4. Ask about upgrade
|
||||
fmt.Print("Upgrade dependencies to latest (go get -u)? [y/N]: ")
|
||||
input, err = reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", "", "", false, fmt.Errorf("failed to read upgrade confirmation: %w", err)
|
||||
}
|
||||
input = strings.TrimSpace(strings.ToLower(input))
|
||||
upgradeDeps = input == "y" || input == "yes"
|
||||
|
||||
fmt.Println()
|
||||
return repo, name, modPath, upgradeDeps, nil
|
||||
}
|
||||
|
||||
@ -27,20 +27,24 @@ import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
var (
|
||||
Run = cRun{}
|
||||
)
|
||||
var Run = cRun{}
|
||||
|
||||
type cRun struct {
|
||||
g.Meta `name:"run" usage:"{cRunUsage}" brief:"{cRunBrief}" eg:"{cRunEg}" dc:"{cRunDc}"`
|
||||
}
|
||||
|
||||
type watchPath struct {
|
||||
Path string
|
||||
Recursive bool
|
||||
}
|
||||
|
||||
type cRunApp struct {
|
||||
File string // Go run file name.
|
||||
Path string // Directory storing built binary.
|
||||
Options string // Extra "go run" options.
|
||||
Args string // Custom arguments.
|
||||
WatchPaths []string // Watch paths for live reload.
|
||||
File string // Go run file name.
|
||||
Path string // Directory storing built binary.
|
||||
Options string // Extra "go run" options.
|
||||
Args string // Custom arguments.
|
||||
WatchPaths []string // Watch paths for live reload.
|
||||
IgnorePatterns []string // Custom ignore patterns.
|
||||
}
|
||||
|
||||
const (
|
||||
@ -50,45 +54,47 @@ const (
|
||||
gf run main.go
|
||||
gf run main.go --args "server -p 8080"
|
||||
gf run main.go -mod=vendor
|
||||
gf run main.go -w "manifest/config/*.yaml"
|
||||
gf run main.go -w internal,api
|
||||
gf run main.go -i ".git,node_modules"
|
||||
`
|
||||
cRunDc = `
|
||||
The "run" command is used for running go codes with hot-compiled-like feature,
|
||||
which compiles and runs the go codes asynchronously when codes change.
|
||||
`
|
||||
cRunFileBrief = `building file path.`
|
||||
cRunPathBrief = `output directory path for built binary file. it's "./" in default`
|
||||
cRunExtraBrief = `the same options as "go run"/"go build" except some options as follows defined`
|
||||
cRunArgsBrief = `custom arguments for your process`
|
||||
cRunWatchPathsBrief = `watch additional paths for live reload, separated by ",". i.e. "manifest/config/*.yaml"`
|
||||
cRunFileBrief = `building file path.`
|
||||
cRunPathBrief = `output directory path for built binary file. it's "./" in default`
|
||||
cRunExtraBrief = `the same options as "go run"/"go build" except some options as follows defined`
|
||||
cRunArgsBrief = `custom arguments for your process`
|
||||
cRunWatchPathsBrief = `watch additional paths for live reload, separated by ",". i.e. "internal,api"`
|
||||
cRunIgnorePatternBrief = `custom ignore patterns for watch, separated by ",". i.e. ".git,node_modules". default patterns: node_modules, vendor, .*, _*. Glob syntax: "*" matches any chars, "?" matches single char, "[abc]" matches char class. Note: patterns match directory names only, not paths`
|
||||
)
|
||||
|
||||
var (
|
||||
process *gproc.Process
|
||||
)
|
||||
var process *gproc.Process
|
||||
|
||||
func init() {
|
||||
gtag.Sets(g.MapStrStr{
|
||||
`cRunUsage`: cRunUsage,
|
||||
`cRunBrief`: cRunBrief,
|
||||
`cRunEg`: cRunEg,
|
||||
`cRunDc`: cRunDc,
|
||||
`cRunFileBrief`: cRunFileBrief,
|
||||
`cRunPathBrief`: cRunPathBrief,
|
||||
`cRunExtraBrief`: cRunExtraBrief,
|
||||
`cRunArgsBrief`: cRunArgsBrief,
|
||||
`cRunWatchPathsBrief`: cRunWatchPathsBrief,
|
||||
`cRunUsage`: cRunUsage,
|
||||
`cRunBrief`: cRunBrief,
|
||||
`cRunEg`: cRunEg,
|
||||
`cRunDc`: cRunDc,
|
||||
`cRunFileBrief`: cRunFileBrief,
|
||||
`cRunPathBrief`: cRunPathBrief,
|
||||
`cRunExtraBrief`: cRunExtraBrief,
|
||||
`cRunArgsBrief`: cRunArgsBrief,
|
||||
`cRunWatchPathsBrief`: cRunWatchPathsBrief,
|
||||
`cRunIgnorePatternBrief`: cRunIgnorePatternBrief,
|
||||
})
|
||||
}
|
||||
|
||||
type (
|
||||
cRunInput struct {
|
||||
g.Meta `name:"run" config:"gfcli.run"`
|
||||
File string `name:"FILE" arg:"true" brief:"{cRunFileBrief}" v:"required"`
|
||||
Path string `name:"path" short:"p" brief:"{cRunPathBrief}" d:"./"`
|
||||
Extra string `name:"extra" short:"e" brief:"{cRunExtraBrief}"`
|
||||
Args string `name:"args" short:"a" brief:"{cRunArgsBrief}"`
|
||||
WatchPaths []string `name:"watchPaths" short:"w" brief:"{cRunWatchPathsBrief}"`
|
||||
g.Meta `name:"run" config:"gfcli.run"`
|
||||
File string `name:"FILE" arg:"true" brief:"{cRunFileBrief}" v:"required"`
|
||||
Path string `name:"path" short:"p" brief:"{cRunPathBrief}" d:"./"`
|
||||
Extra string `name:"extra" short:"e" brief:"{cRunExtraBrief}"`
|
||||
Args string `name:"args" short:"a" brief:"{cRunArgsBrief}"`
|
||||
WatchPaths []string `name:"watchPaths" short:"w" brief:"{cRunWatchPathsBrief}"`
|
||||
IgnorePatterns []string `name:"ignorePatterns" short:"i" brief:"{cRunIgnorePatternBrief}"`
|
||||
}
|
||||
cRunOutput struct{}
|
||||
)
|
||||
@ -105,22 +111,35 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err
|
||||
mlog.Fatalf(`command "go" not found in your environment, please install golang first to proceed this command`)
|
||||
}
|
||||
|
||||
if len(in.WatchPaths) == 1 {
|
||||
in.WatchPaths = strings.Split(in.WatchPaths[0], ",")
|
||||
// Parse comma-separated values in WatchPaths
|
||||
if len(in.WatchPaths) > 0 {
|
||||
in.WatchPaths = parseCommaSeparatedArgs(in.WatchPaths)
|
||||
mlog.Printf("watchPaths: %v", in.WatchPaths)
|
||||
}
|
||||
|
||||
// Parse comma-separated values in IgnorePatterns
|
||||
if len(in.IgnorePatterns) > 0 {
|
||||
in.IgnorePatterns = parseCommaSeparatedArgs(in.IgnorePatterns)
|
||||
mlog.Printf("ignorePatterns: %v", in.IgnorePatterns)
|
||||
}
|
||||
|
||||
app := &cRunApp{
|
||||
File: in.File,
|
||||
Path: filepath.FromSlash(in.Path),
|
||||
Options: in.Extra,
|
||||
Args: in.Args,
|
||||
WatchPaths: in.WatchPaths,
|
||||
File: in.File,
|
||||
Path: filepath.FromSlash(in.Path),
|
||||
Options: in.Extra,
|
||||
Args: in.Args,
|
||||
WatchPaths: in.WatchPaths,
|
||||
IgnorePatterns: in.IgnorePatterns,
|
||||
}
|
||||
dirty := gtype.NewBool()
|
||||
|
||||
var outputPath = app.genOutputPath()
|
||||
outputPath := app.genOutputPath()
|
||||
callbackFunc := func(event *gfsnotify.Event) {
|
||||
if !event.IsWrite() && !event.IsCreate() && !event.IsRemove() && !event.IsRename() {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the file extension is 'go'.
|
||||
if gfile.ExtName(event.Path) != "go" {
|
||||
return
|
||||
}
|
||||
@ -138,15 +157,11 @@ func (c cRun) Index(ctx context.Context, in cRunInput) (out *cRunOutput, err err
|
||||
})
|
||||
}
|
||||
|
||||
if len(app.WatchPaths) > 0 {
|
||||
for _, path := range app.WatchPaths {
|
||||
_, err = gfsnotify.Add(gfile.RealPath(path), callbackFunc)
|
||||
if err != nil {
|
||||
mlog.Fatal(err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_, err = gfsnotify.Add(gfile.RealPath("."), callbackFunc)
|
||||
// Get directories to watch (recursive or non-recursive monitoring).
|
||||
watchPaths := app.getWatchPaths()
|
||||
for _, wp := range watchPaths {
|
||||
option := gfsnotify.WatchOption{NoRecursive: !wp.Recursive}
|
||||
_, err = gfsnotify.Add(wp.Path, callbackFunc, option)
|
||||
if err != nil {
|
||||
mlog.Fatal(err)
|
||||
}
|
||||
@ -249,35 +264,181 @@ func (app *cRunApp) End(ctx context.Context, sig os.Signal, outputPath string) {
|
||||
}
|
||||
|
||||
func (app *cRunApp) genOutputPath() (outputPath string) {
|
||||
var renamePath string
|
||||
outputPath = gfile.Join(app.Path, gfile.Name(app.File))
|
||||
if runtime.GOOS == "windows" {
|
||||
outputPath += ".exe"
|
||||
if gfile.Exists(outputPath) {
|
||||
renamePath = outputPath + "~"
|
||||
renamePath := outputPath + "~"
|
||||
if err := gfile.Rename(outputPath, renamePath); err != nil {
|
||||
mlog.Print(err)
|
||||
}
|
||||
// Clean up the renamed old binary file
|
||||
defer func() {
|
||||
if gfile.Exists(renamePath) {
|
||||
_ = gfile.Remove(renamePath)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
return filepath.FromSlash(outputPath)
|
||||
}
|
||||
|
||||
func matchWatchPaths(watchPaths []string, eventPath string) bool {
|
||||
for _, path := range watchPaths {
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
mlog.Printf("match watchPath '%s' error: %s", path, err.Error())
|
||||
// getWatchPaths uses DFS to find the minimal set of directories to watch.
|
||||
// Rule: if a directory and all its descendants have no ignored subdirectories, watch it;
|
||||
// otherwise, recurse into valid children and watch the current directory non-recursively.
|
||||
func (app *cRunApp) getWatchPaths() []watchPath {
|
||||
roots := []string{"."}
|
||||
if len(app.WatchPaths) > 0 {
|
||||
roots = app.WatchPaths
|
||||
}
|
||||
|
||||
// Use custom ignore patterns if provided, otherwise use default.
|
||||
ignorePatterns := defaultIgnorePatterns
|
||||
if len(app.IgnorePatterns) > 0 {
|
||||
ignorePatterns = app.IgnorePatterns
|
||||
}
|
||||
|
||||
var watchPaths []watchPath
|
||||
|
||||
for _, root := range roots {
|
||||
absRoot := gfile.RealPath(root)
|
||||
if absRoot == "" {
|
||||
mlog.Printf("watch path '%s' not found, skipping", root)
|
||||
continue
|
||||
}
|
||||
matched, err := filepath.Match(absPath, eventPath)
|
||||
if err != nil {
|
||||
mlog.Printf("match watchPath '%s' error: %s", path, err.Error())
|
||||
if isIgnoredDirName(absRoot, ignorePatterns) {
|
||||
continue
|
||||
}
|
||||
if matched {
|
||||
app.collectWatchPaths(absRoot, ignorePatterns, &watchPaths)
|
||||
}
|
||||
|
||||
if len(watchPaths) == 0 {
|
||||
mlog.Printf("no directories to watch, using current directory")
|
||||
if absCur := gfile.RealPath("."); absCur != "" {
|
||||
return []watchPath{{Path: absCur, Recursive: true}}
|
||||
}
|
||||
return []watchPath{{Path: ".", Recursive: true}}
|
||||
}
|
||||
|
||||
mlog.Printf("watching %d paths", len(watchPaths))
|
||||
for _, wp := range watchPaths {
|
||||
recursiveStr := "recursive"
|
||||
if !wp.Recursive {
|
||||
recursiveStr = "non-recursive"
|
||||
}
|
||||
mlog.Debugf(" - %s (%s)", wp.Path, recursiveStr)
|
||||
}
|
||||
return watchPaths
|
||||
}
|
||||
|
||||
// collectWatchPaths performs a DFS traversal to collect the minimal set of directories to watch.
|
||||
// Returns true if the directory or any of its descendants contains ignored directories.
|
||||
// Rule: if a directory has no ignored descendants at any depth, watch it recursively;
|
||||
// otherwise, watch it non-recursively and recurse into valid children.
|
||||
func (app *cRunApp) collectWatchPaths(dir string, ignorePatterns []string, watchPaths *[]watchPath) bool {
|
||||
entries, err := gfile.ScanDir(dir, "*", false)
|
||||
if err != nil {
|
||||
mlog.Printf("scan directory '%s' error: %s", dir, err.Error())
|
||||
// If we can't scan the directory, add it to watch list as fallback
|
||||
*watchPaths = append(*watchPaths, watchPath{Path: dir, Recursive: true})
|
||||
return false
|
||||
}
|
||||
|
||||
// First pass: identify valid subdirectories and check for directly ignored children
|
||||
var validSubDirs []string
|
||||
hasIgnoredChild := false
|
||||
for _, entry := range entries {
|
||||
if !gfile.IsDir(entry) {
|
||||
continue
|
||||
}
|
||||
if isIgnoredDirName(entry, ignorePatterns) {
|
||||
hasIgnoredChild = true
|
||||
} else {
|
||||
validSubDirs = append(validSubDirs, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// If already has ignored child, we know this dir needs non-recursive watch
|
||||
if hasIgnoredChild {
|
||||
*watchPaths = append(*watchPaths, watchPath{Path: dir, Recursive: false})
|
||||
for _, subDir := range validSubDirs {
|
||||
app.collectWatchPaths(subDir, ignorePatterns, watchPaths)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// No ignored children, but need to check descendants recursively
|
||||
// Collect results from all subdirectories first
|
||||
subResults := make([]bool, len(validSubDirs))
|
||||
subWatchPaths := make([][]watchPath, len(validSubDirs))
|
||||
hasIgnoredDescendant := false
|
||||
|
||||
for i, subDir := range validSubDirs {
|
||||
var subPaths []watchPath
|
||||
subResults[i] = app.collectWatchPaths(subDir, ignorePatterns, &subPaths)
|
||||
subWatchPaths[i] = subPaths
|
||||
if subResults[i] {
|
||||
hasIgnoredDescendant = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasIgnoredDescendant {
|
||||
// No ignored descendants at any depth, watch this directory recursively
|
||||
*watchPaths = append(*watchPaths, watchPath{Path: dir, Recursive: true})
|
||||
return false
|
||||
}
|
||||
|
||||
// Has ignored descendants, watch current directory non-recursively
|
||||
// and add all collected subdirectory watch paths
|
||||
*watchPaths = append(*watchPaths, watchPath{Path: dir, Recursive: false})
|
||||
for _, subPaths := range subWatchPaths {
|
||||
*watchPaths = append(*watchPaths, subPaths...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// defaultIgnorePatterns contains glob patterns for directory names that should be ignored when watching.
|
||||
// These directories typically contain third-party code or non-source files.
|
||||
// Supported glob syntax (filepath.Match):
|
||||
// - "*" matches any sequence of non-separator characters
|
||||
// - "?" matches any single non-separator character
|
||||
// - "[abc]" matches any character in the bracket
|
||||
// - "[a-z]" matches any character in the range
|
||||
// - "[^abc]" or "[!abc]" matches any character not in the bracket
|
||||
//
|
||||
// Note: patterns match directory base names only, not full paths (no "/" or path separators allowed).
|
||||
var defaultIgnorePatterns = []string{
|
||||
"node_modules",
|
||||
"vendor",
|
||||
".*", // All hidden directories (covers .git, .svn, .hg, .idea, .vscode, etc.)
|
||||
"_*", // Directories starting with underscore
|
||||
}
|
||||
|
||||
// isIgnoredDirName checks if a directory name matches any ignored pattern.
|
||||
// It accepts either a full path or just the directory name, but only matches against the base name.
|
||||
// Note: patterns should not contain "/" as they only match directory names, not paths.
|
||||
func isIgnoredDirName(name string, ignorePatterns []string) bool {
|
||||
baseName := gfile.Basename(name)
|
||||
for _, pattern := range ignorePatterns {
|
||||
if matched, _ := filepath.Match(pattern, baseName); matched {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseCommaSeparatedArgs parses command line arguments that may contain comma-separated values.
|
||||
// It handles both single argument with commas (e.g., "a,b,c") and multiple arguments.
|
||||
func parseCommaSeparatedArgs(args []string) []string {
|
||||
var result []string
|
||||
for _, arg := range args {
|
||||
parts := strings.Split(arg, ",")
|
||||
for _, part := range parts {
|
||||
trimmed := strings.TrimSpace(part)
|
||||
if trimmed != "" {
|
||||
result = append(result, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@ -22,7 +22,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
apiFolder = gtest.DataPath("genctrl", "api")
|
||||
apiFolder = gtest.DataPath("genctrl", "default", "api")
|
||||
in = genctrl.CGenCtrlInput{
|
||||
SrcFolder: apiFolder,
|
||||
DstFolder: path,
|
||||
@ -39,7 +39,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(path)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
@ -49,7 +49,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
|
||||
genApi = apiFolder + filepath.FromSlash("/article/article.go")
|
||||
genApiExpect = apiFolder + filepath.FromSlash("/article/article_expect.go")
|
||||
)
|
||||
defer gfile.Remove(genApi)
|
||||
defer gfile.RemoveAll(genApi)
|
||||
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
|
||||
|
||||
// files
|
||||
@ -67,7 +67,7 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
|
||||
})
|
||||
|
||||
// content
|
||||
testPath := gtest.DataPath("genctrl", "controller")
|
||||
testPath := gtest.DataPath("genctrl", "default", "controller")
|
||||
expectFiles := []string{
|
||||
testPath + filepath.FromSlash("/article/article.go"),
|
||||
testPath + filepath.FromSlash("/article/article_new.go"),
|
||||
@ -84,6 +84,104 @@ func Test_Gen_Ctrl_Default(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func Test_Gen_Ctrl_Default_Multi(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
path = gfile.Temp(guid.S())
|
||||
apiFolder = gtest.DataPath("genctrl", "multi", "api")
|
||||
in = genctrl.CGenCtrlInput{
|
||||
SrcFolder: apiFolder,
|
||||
DstFolder: path,
|
||||
WatchFile: "",
|
||||
SdkPath: "",
|
||||
SdkStdVersion: false,
|
||||
SdkNoV1: false,
|
||||
Clear: false,
|
||||
Merge: false,
|
||||
}
|
||||
)
|
||||
|
||||
err := gutil.FillStructWithDefault(&in)
|
||||
t.AssertNil(err)
|
||||
|
||||
err = gfile.Mkdir(path)
|
||||
t.AssertNil(err)
|
||||
defer gfile.RemoveAll(path)
|
||||
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
// apiInterface file
|
||||
var (
|
||||
genApiSlice = []string{
|
||||
apiFolder + filepath.FromSlash("/admin/article/article.go"),
|
||||
apiFolder + filepath.FromSlash("/admin/user/user.go"),
|
||||
apiFolder + filepath.FromSlash("/app/user/user.go"),
|
||||
apiFolder + filepath.FromSlash("/app/user/user_ext/user_ext.go"),
|
||||
}
|
||||
genApiSliceExpect = []string{
|
||||
apiFolder + filepath.FromSlash("/admin/article/article_expect.go"),
|
||||
apiFolder + filepath.FromSlash("/admin/user/user_expect.go"),
|
||||
apiFolder + filepath.FromSlash("/app/user/user_expect.go"),
|
||||
apiFolder + filepath.FromSlash("/app/user/user_ext/user_ext_expect.go"),
|
||||
}
|
||||
)
|
||||
|
||||
for i := range genApiSlice {
|
||||
t.Assert(gfile.GetContents(genApiSlice[i]), gfile.GetContents(genApiSliceExpect[i]))
|
||||
gfile.RemoveAll(genApiSlice[i])
|
||||
}
|
||||
|
||||
// files
|
||||
files, err := gfile.ScanDir(path, "*.go", true)
|
||||
t.AssertNil(err)
|
||||
t.Assert(files, []string{
|
||||
path + filepath.FromSlash("/admin/article/article.go"),
|
||||
path + filepath.FromSlash("/admin/article/article_new.go"),
|
||||
path + filepath.FromSlash("/admin/article/article_v1_create.go"),
|
||||
|
||||
path + filepath.FromSlash("/admin/user/user.go"),
|
||||
path + filepath.FromSlash("/admin/user/user_new.go"),
|
||||
path + filepath.FromSlash("/admin/user/user_v1_create.go"),
|
||||
|
||||
path + filepath.FromSlash("/app/user/user.go"),
|
||||
path + filepath.FromSlash("/app/user/user_ext/user_ext.go"),
|
||||
path + filepath.FromSlash("/app/user/user_ext/user_ext_new.go"),
|
||||
path + filepath.FromSlash("/app/user/user_ext/user_ext_v1_create.go"),
|
||||
path + filepath.FromSlash("/app/user/user_ext/user_ext_v1_update.go"),
|
||||
|
||||
path + filepath.FromSlash("/app/user/user_new.go"),
|
||||
path + filepath.FromSlash("/app/user/user_v1_create.go"),
|
||||
path + filepath.FromSlash("/app/user/user_v1_update.go"),
|
||||
})
|
||||
|
||||
// content
|
||||
testPath := gtest.DataPath("genctrl", "multi", "controller")
|
||||
expectFiles := []string{
|
||||
testPath + filepath.FromSlash("/admin/article/article.go"),
|
||||
testPath + filepath.FromSlash("/admin/article/article_new.go"),
|
||||
testPath + filepath.FromSlash("/admin/article/article_v1_create.go"),
|
||||
|
||||
testPath + filepath.FromSlash("/admin/user/user.go"),
|
||||
testPath + filepath.FromSlash("/admin/user/user_new.go"),
|
||||
testPath + filepath.FromSlash("/admin/user/user_v1_create.go"),
|
||||
|
||||
testPath + filepath.FromSlash("/app/user/user.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_ext/user_ext.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_ext/user_ext_new.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_ext/user_ext_v1_create.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_ext/user_ext_v1_update.go"),
|
||||
|
||||
testPath + filepath.FromSlash("/app/user/user_new.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_v1_create.go"),
|
||||
testPath + filepath.FromSlash("/app/user/user_v1_update.go"),
|
||||
}
|
||||
for i := range files {
|
||||
t.Assert(gfile.GetContents(files[i]), gfile.GetContents(expectFiles[i]))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func expectFilesContent(t *gtest.T, paths []string, expectPaths []string) {
|
||||
for i, expectFile := range expectPaths {
|
||||
val := gfile.GetContents(paths[i])
|
||||
@ -98,8 +196,8 @@ func Test_Gen_Ctrl_UseMerge_AddNewFile(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
ctrlPath = gfile.Temp(guid.S())
|
||||
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
apiFolder = gtest.DataPath("genctrl-merge", "add_new_file", "api")
|
||||
// ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
apiFolder = gtest.DataPath("genctrl", "merge", "add_new_file", "api")
|
||||
in = genctrl.CGenCtrlInput{
|
||||
SrcFolder: apiFolder,
|
||||
DstFolder: ctrlPath,
|
||||
@ -118,7 +216,7 @@ type DictTypeAddRes struct {
|
||||
|
||||
err := gfile.Mkdir(ctrlPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(ctrlPath)
|
||||
defer gfile.RemoveAll(ctrlPath)
|
||||
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
@ -127,7 +225,7 @@ type DictTypeAddRes struct {
|
||||
genApi = filepath.Join(apiFolder, "/dict/dict.go")
|
||||
genApiExpect = filepath.Join(apiFolder, "/dict/dict_expect.go")
|
||||
)
|
||||
defer gfile.Remove(genApi)
|
||||
defer gfile.RemoveAll(genApi)
|
||||
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
|
||||
|
||||
genCtrlFiles, err := gfile.ScanDir(ctrlPath, "*.go", true)
|
||||
@ -138,7 +236,7 @@ type DictTypeAddRes struct {
|
||||
filepath.Join(ctrlPath, "/dict/dict_v1_dict_type.go"),
|
||||
})
|
||||
|
||||
expectCtrlPath := gtest.DataPath("genctrl-merge", "add_new_file", "controller")
|
||||
expectCtrlPath := gtest.DataPath("genctrl", "merge", "add_new_file", "controller")
|
||||
expectFiles := []string{
|
||||
filepath.Join(expectCtrlPath, "/dict/dict.go"),
|
||||
filepath.Join(expectCtrlPath, "/dict/dict_new.go"),
|
||||
@ -152,7 +250,7 @@ type DictTypeAddRes struct {
|
||||
newApiFilePath := filepath.Join(apiFolder, "/dict/v1/test_new.go")
|
||||
err = gfile.PutContents(newApiFilePath, testNewApiFile)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(newApiFilePath)
|
||||
defer gfile.RemoveAll(newApiFilePath)
|
||||
|
||||
// Then execute the command
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
@ -179,8 +277,8 @@ func Test_Gen_Ctrl_UseMerge_AddNewCtrl(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
ctrlPath = gfile.Temp(guid.S())
|
||||
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
apiFolder = gtest.DataPath("genctrl-merge", "add_new_ctrl", "api")
|
||||
// ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
apiFolder = gtest.DataPath("genctrl", "merge", "add_new_ctrl", "api")
|
||||
in = genctrl.CGenCtrlInput{
|
||||
SrcFolder: apiFolder,
|
||||
DstFolder: ctrlPath,
|
||||
@ -190,7 +288,7 @@ func Test_Gen_Ctrl_UseMerge_AddNewCtrl(t *testing.T) {
|
||||
|
||||
err := gfile.Mkdir(ctrlPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(ctrlPath)
|
||||
defer gfile.RemoveAll(ctrlPath)
|
||||
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
@ -199,7 +297,7 @@ func Test_Gen_Ctrl_UseMerge_AddNewCtrl(t *testing.T) {
|
||||
genApi = filepath.Join(apiFolder, "/dict/dict.go")
|
||||
genApiExpect = filepath.Join(apiFolder, "/dict/dict_expect.go")
|
||||
)
|
||||
defer gfile.Remove(genApi)
|
||||
defer gfile.RemoveAll(genApi)
|
||||
t.Assert(gfile.GetContents(genApi), gfile.GetContents(genApiExpect))
|
||||
|
||||
genCtrlFiles, err := gfile.ScanDir(ctrlPath, "*.go", true)
|
||||
@ -210,7 +308,7 @@ func Test_Gen_Ctrl_UseMerge_AddNewCtrl(t *testing.T) {
|
||||
filepath.Join(ctrlPath, "/dict/dict_v1_dict_type.go"),
|
||||
})
|
||||
|
||||
expectCtrlPath := gtest.DataPath("genctrl-merge", "add_new_ctrl", "controller")
|
||||
expectCtrlPath := gtest.DataPath("genctrl", "merge", "add_new_ctrl", "controller")
|
||||
expectFiles := []string{
|
||||
filepath.Join(expectCtrlPath, "/dict/dict.go"),
|
||||
filepath.Join(expectCtrlPath, "/dict/dict_new.go"),
|
||||
@ -236,7 +334,7 @@ type DictTypeAddRes struct {
|
||||
err = gfile.PutContentsAppend(dictModuleFileName, testNewApiFile)
|
||||
t.AssertNil(err)
|
||||
|
||||
//==================================
|
||||
// ==================================
|
||||
// Then execute the command
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
@ -262,7 +360,7 @@ func Test_Gen_Ctrl_UseMerge_Issue3460(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
var (
|
||||
ctrlPath = gfile.Temp(guid.S())
|
||||
//ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
// ctrlPath = gtest.DataPath("issue", "3460", "controller")
|
||||
apiFolder = gtest.DataPath("issue", "3460", "api")
|
||||
in = genctrl.CGenCtrlInput{
|
||||
SrcFolder: apiFolder,
|
||||
@ -278,7 +376,7 @@ func Test_Gen_Ctrl_UseMerge_Issue3460(t *testing.T) {
|
||||
|
||||
err := gfile.Mkdir(ctrlPath)
|
||||
t.AssertNil(err)
|
||||
defer gfile.Remove(ctrlPath)
|
||||
defer gfile.RemoveAll(ctrlPath)
|
||||
|
||||
_, err = genctrl.CGenCtrl{}.Ctrl(ctx, in)
|
||||
t.AssertNil(err)
|
||||
|
||||
@ -66,6 +66,7 @@ func Test_Gen_Dao_Issue2572(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: nil,
|
||||
FieldMapping: nil,
|
||||
}
|
||||
@ -155,6 +156,7 @@ func Test_Gen_Dao_Issue2616(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: nil,
|
||||
FieldMapping: nil,
|
||||
}
|
||||
@ -266,6 +268,7 @@ func Test_Gen_Dao_Issue2746(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: nil,
|
||||
FieldMapping: nil,
|
||||
}
|
||||
@ -338,6 +341,7 @@ func Test_Gen_Dao_Issue3459(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: nil,
|
||||
}
|
||||
)
|
||||
|
||||
@ -69,6 +69,7 @@ func Test_Gen_Dao_Default(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: nil,
|
||||
FieldMapping: nil,
|
||||
}
|
||||
@ -161,6 +162,7 @@ func Test_Gen_Dao_TypeMapping(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: map[gendao.DBFieldTypeName]gendao.CustomAttributeType{
|
||||
"int": {
|
||||
Type: "int64",
|
||||
@ -263,6 +265,7 @@ func Test_Gen_Dao_FieldMapping(t *testing.T) {
|
||||
NoJsonTag: false,
|
||||
NoModelComment: false,
|
||||
Clear: false,
|
||||
GenTable: false,
|
||||
TypeMapping: map[gendao.DBFieldTypeName]gendao.CustomAttributeType{
|
||||
"int": {
|
||||
Type: "int64",
|
||||
|
||||
336
cmd/gf/internal/cmd/cmd_z_unit_run_test.go
Normal file
336
cmd/gf/internal/cmd/cmd_z_unit_run_test.go
Normal file
@ -0,0 +1,336 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
)
|
||||
|
||||
func Test_cRunApp_getWatchPaths_Basic(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{"."},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
for _, v := range watchPaths {
|
||||
t.Log(v)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_EmptyWatchPaths(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should default to current directory "."
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_CustomIgnorePattern(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{"testdata"},
|
||||
IgnorePatterns: []string{"2572"},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Ensure the "2572" directory is not watched directly.
|
||||
for _, wp := range watchPaths {
|
||||
t.Log("watch path:", wp)
|
||||
t.Assert(strings.HasSuffix(wp.Path, "2572"), false)
|
||||
}
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_WithIgnoredDirectories(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory structure for testing
|
||||
tempDir := gfile.Temp("gf_run_test")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create directory structure:
|
||||
// tempDir/
|
||||
// ├── src/
|
||||
// │ ├── api/
|
||||
// │ └── internal/
|
||||
// ├── vendor/ <-- ignored
|
||||
// └── node_modules/ <-- ignored
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "api"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "internal"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "vendor"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "node_modules"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should watch tempDir non-recursively (to catch top-level files) and src recursively
|
||||
t.Assert(len(watchPaths), 2)
|
||||
// First path is tempDir (non-recursive)
|
||||
t.Assert(watchPaths[0].Path, tempDir)
|
||||
t.Assert(watchPaths[0].Recursive, false)
|
||||
// Second path is src (recursive, since it has no ignored descendants)
|
||||
t.Assert(watchPaths[1].Path, filepath.Join(tempDir, "src"))
|
||||
t.Assert(watchPaths[1].Recursive, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_NoIgnoredDirectories(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory structure without ignored directories
|
||||
tempDir := gfile.Temp("gf_run_test_no_ignore")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create directory structure without ignored patterns:
|
||||
// tempDir/
|
||||
// ├── src/
|
||||
// │ ├── api/
|
||||
// │ └── internal/
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "api"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "internal"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should watch the root directory recursively since no ignored directories exist
|
||||
t.Assert(len(watchPaths), 1)
|
||||
t.Assert(watchPaths[0].Path, tempDir)
|
||||
t.Assert(watchPaths[0].Recursive, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_CustomIgnorePatterns(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory structure
|
||||
tempDir := gfile.Temp("gf_run_test_custom_ignore")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create directory structure:
|
||||
// tempDir/
|
||||
// ├── src/
|
||||
// │ ├── api/
|
||||
// │ └── internal/
|
||||
// ├── build/ <-- ignored
|
||||
// └── dist/ <-- ignored
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "api"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "src", "internal"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "build"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "dist"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
IgnorePatterns: []string{"build", "dist"},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should watch tempDir non-recursively and src recursively
|
||||
t.Assert(len(watchPaths), 2)
|
||||
t.Assert(watchPaths[0].Path, tempDir)
|
||||
t.Assert(watchPaths[0].Recursive, false)
|
||||
t.Assert(watchPaths[1].Path, filepath.Join(tempDir, "src"))
|
||||
t.Assert(watchPaths[1].Recursive, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_DeepNestedStructure(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a deep nested directory structure
|
||||
tempDir := gfile.Temp("gf_run_test_deep")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create deep directory structure:
|
||||
// tempDir/
|
||||
// ├── a/
|
||||
// │ ├── b/
|
||||
// │ │ └── c/
|
||||
// │ └── vendor/ <-- ignored
|
||||
// └── d/
|
||||
gfile.Mkdir(filepath.Join(tempDir, "a", "b", "c"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "a", "vendor"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "d"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should watch individual valid directories due to ignored vendor directory
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
|
||||
// Verify that vendor directory is not in watch list
|
||||
for _, wp := range watchPaths {
|
||||
t.Assert(strings.Contains(wp.Path, "vendor"), false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_MultipleRoots(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create multiple temporary directories
|
||||
tempDir1 := gfile.Temp("gf_run_test_multi1")
|
||||
tempDir2 := gfile.Temp("gf_run_test_multi2")
|
||||
defer gfile.Remove(tempDir1)
|
||||
defer gfile.Remove(tempDir2)
|
||||
|
||||
gfile.Mkdir(filepath.Join(tempDir1, "src"))
|
||||
gfile.Mkdir(filepath.Join(tempDir2, "api"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir1, tempDir2},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should watch both root directories recursively
|
||||
t.Assert(len(watchPaths), 2)
|
||||
|
||||
// Both directories should be in the watch list
|
||||
foundDir1, foundDir2 := false, false
|
||||
for _, wp := range watchPaths {
|
||||
if wp.Path == tempDir1 {
|
||||
foundDir1 = true
|
||||
t.Assert(wp.Recursive, true)
|
||||
}
|
||||
if wp.Path == tempDir2 {
|
||||
foundDir2 = true
|
||||
t.Assert(wp.Recursive, true)
|
||||
}
|
||||
}
|
||||
t.Assert(foundDir1, true)
|
||||
t.Assert(foundDir2, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_NonExistentDirectory(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{"/non/existent/path"},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Should fall back to current directory when no valid paths found
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
|
||||
// Should contain current directory
|
||||
currentDir, _ := os.Getwd()
|
||||
foundCurrentDir := false
|
||||
for _, wp := range watchPaths {
|
||||
if wp.Path == currentDir {
|
||||
foundCurrentDir = true
|
||||
break
|
||||
}
|
||||
}
|
||||
t.Assert(foundCurrentDir, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_isIgnoredDirName(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Test default ignore patterns
|
||||
t.Assert(isIgnoredDirName("node_modules", defaultIgnorePatterns), true)
|
||||
t.Assert(isIgnoredDirName("vendor", defaultIgnorePatterns), true)
|
||||
t.Assert(isIgnoredDirName(".git", defaultIgnorePatterns), true)
|
||||
t.Assert(isIgnoredDirName("_private", defaultIgnorePatterns), true)
|
||||
t.Assert(isIgnoredDirName("src", defaultIgnorePatterns), false)
|
||||
t.Assert(isIgnoredDirName("api", defaultIgnorePatterns), false)
|
||||
|
||||
// Test custom ignore patterns
|
||||
customPatterns := []string{"build", "dist", "*.tmp"}
|
||||
t.Assert(isIgnoredDirName("build", customPatterns), true)
|
||||
t.Assert(isIgnoredDirName("dist", customPatterns), true)
|
||||
t.Assert(isIgnoredDirName("test.tmp", customPatterns), true)
|
||||
t.Assert(isIgnoredDirName("src", customPatterns), false)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_DeeplyNestedIgnore(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create a temporary directory structure with deeply nested ignored directory
|
||||
tempDir := gfile.Temp("gf_run_test_deeply_nested")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
// Create directory structure:
|
||||
// tempDir/
|
||||
// ├── a/
|
||||
// │ ├── b/
|
||||
// │ │ ├── c/
|
||||
// │ │ │ └── vendor/ <-- deeply nested ignored (4 levels)
|
||||
// │ │ └── d/
|
||||
// │ └── e/
|
||||
// └── f/
|
||||
gfile.Mkdir(filepath.Join(tempDir, "a", "b", "c", "vendor"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "a", "b", "d"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "a", "e"))
|
||||
gfile.Mkdir(filepath.Join(tempDir, "f"))
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Expected watch paths:
|
||||
// 1. tempDir (non-recursive) - has ignored descendant
|
||||
// 2. a (non-recursive) - has ignored descendant in b/c/vendor
|
||||
// 3. b (non-recursive) - has ignored descendant in c/vendor
|
||||
// 4. c (non-recursive) - has ignored child vendor
|
||||
// 5. d (recursive) - no ignored descendants
|
||||
// 6. e (recursive) - no ignored descendants
|
||||
// 7. f (recursive) - no ignored descendants
|
||||
|
||||
t.AssertGT(len(watchPaths), 0)
|
||||
|
||||
// Verify vendor is not in watch paths
|
||||
for _, wp := range watchPaths {
|
||||
t.Assert(strings.Contains(wp.Path, "vendor"), false)
|
||||
}
|
||||
|
||||
// Find specific paths and verify their recursive flags
|
||||
foundF := false
|
||||
for _, wp := range watchPaths {
|
||||
if wp.Path == filepath.Join(tempDir, "f") {
|
||||
foundF = true
|
||||
t.Assert(wp.Recursive, true) // f should be recursive (no ignored descendants)
|
||||
}
|
||||
}
|
||||
t.Assert(foundF, true)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_cRunApp_getWatchPaths_EmptyDirectory(t *testing.T) {
|
||||
gtest.C(t, func(t *gtest.T) {
|
||||
// Create an empty temporary directory
|
||||
tempDir := gfile.Temp("gf_run_test_empty")
|
||||
defer gfile.Remove(tempDir)
|
||||
|
||||
gfile.Mkdir(tempDir)
|
||||
|
||||
app := &cRunApp{
|
||||
WatchPaths: []string{tempDir},
|
||||
}
|
||||
watchPaths := app.getWatchPaths()
|
||||
|
||||
// Empty directory should be watched recursively (no ignored descendants)
|
||||
t.Assert(len(watchPaths), 1)
|
||||
t.Assert(watchPaths[0].Path, tempDir)
|
||||
t.Assert(watchPaths[0].Recursive, true)
|
||||
})
|
||||
}
|
||||
@ -89,28 +89,11 @@ func (c CGenCtrl) Ctrl(ctx context.Context, in CGenCtrlInput) (out *CGenCtrlOutp
|
||||
if !gfile.Exists(in.SrcFolder) {
|
||||
mlog.Fatalf(`source folder path "%s" does not exist`, in.SrcFolder)
|
||||
}
|
||||
// retrieve all api modules.
|
||||
apiModuleFolderPaths, err := gfile.ScanDir(in.SrcFolder, "*", false)
|
||||
|
||||
err = c.generateByModules(in)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, apiModuleFolderPath := range apiModuleFolderPaths {
|
||||
if !gfile.IsDir(apiModuleFolderPath) {
|
||||
continue
|
||||
}
|
||||
// generate go files by api module.
|
||||
var (
|
||||
module = gfile.Basename(apiModuleFolderPath)
|
||||
dstModuleFolderPath = gfile.Join(in.DstFolder, module)
|
||||
)
|
||||
err = c.generateByModule(
|
||||
apiModuleFolderPath, dstModuleFolderPath, in.SdkPath,
|
||||
in.SdkStdVersion, in.SdkNoV1, in.Clear, in.Merge,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
mlog.Print(`done!`)
|
||||
return
|
||||
@ -163,6 +146,56 @@ func (c CGenCtrl) generateByWatchFile(watchFile, sdkPath string, sdkStdVersion,
|
||||
)
|
||||
}
|
||||
|
||||
// generateByModules recursively calls generateByModule for multi-level modules generation.
|
||||
func (c CGenCtrl) generateByModules(in CGenCtrlInput) (err error) {
|
||||
// read root folder, example: api/user or api/app
|
||||
moduleFolderPaths, err := gfile.ScanDir(in.SrcFolder, "*", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, moduleFolder := range moduleFolderPaths {
|
||||
if !gfile.IsDir(moduleFolder) {
|
||||
continue
|
||||
}
|
||||
|
||||
// read children folder, example: api/user/v1 or api/app/user
|
||||
childrenFolderPaths, err := gfile.ScanDir(moduleFolder, "*", false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, childrenFolderPath := range childrenFolderPaths {
|
||||
if !gfile.IsDir(childrenFolderPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
inCopy = in
|
||||
module = gfile.Basename(moduleFolder)
|
||||
)
|
||||
inCopy.SrcFolder = gfile.Join(in.SrcFolder, module)
|
||||
inCopy.DstFolder = gfile.Join(in.DstFolder, module)
|
||||
err = c.generateByModules(inCopy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// generate go files by api module.
|
||||
var (
|
||||
module = gfile.Basename(moduleFolder)
|
||||
dstModuleFolderPath = gfile.Join(in.DstFolder, module)
|
||||
)
|
||||
err = c.generateByModule(
|
||||
moduleFolder, dstModuleFolderPath, in.SdkPath,
|
||||
in.SdkStdVersion, in.SdkNoV1, in.Clear, in.Merge,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// parseApiModule parses certain api and generate associated go files by certain module, not all api modules.
|
||||
func (c CGenCtrl) generateByModule(
|
||||
apiModuleFolderPath, dstModuleFolderPath, sdkPath string,
|
||||
|
||||
@ -8,6 +8,9 @@ package genctrl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@ -144,8 +147,8 @@ func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, ite
|
||||
"{MethodName}": item.MethodName,
|
||||
"{MethodComment}": item.GetComment(),
|
||||
})
|
||||
|
||||
if gstr.Contains(gfile.GetContents(methodFilePath), fmt.Sprintf(`func (c *%v) %v(`, ctrlName, item.MethodName)) {
|
||||
// Use AST-based checking for more accurate method detection
|
||||
if methodExists(methodFilePath, ctrlName, item.MethodName) {
|
||||
return
|
||||
}
|
||||
if err = gfile.PutContentsAppend(methodFilePath, gstr.TrimLeft(content)); err != nil {
|
||||
@ -170,7 +173,6 @@ func (c *controllerGenerator) doGenerateCtrlItem(dstModuleFolderPath string, ite
|
||||
|
||||
// use -merge
|
||||
func (c *controllerGenerator) doGenerateCtrlMergeItem(dstModuleFolderPath string, apiItems []apiItem, doneApiSet *gset.StrSet) (err error) {
|
||||
|
||||
type controllerFileItem struct {
|
||||
module string
|
||||
version string
|
||||
@ -193,13 +195,23 @@ func (c *controllerGenerator) doGenerateCtrlMergeItem(dstModuleFolderPath string
|
||||
ctrlFileItemMap[api.FileName] = ctrlFileItem
|
||||
}
|
||||
|
||||
ctrlName := fmt.Sprintf(`Controller%s`, gstr.UcFirst(api.Version))
|
||||
ctrl := gstr.TrimLeft(gstr.ReplaceByMap(consts.TemplateGenCtrlControllerMethodFuncMerge, g.MapStrStr{
|
||||
"{Module}": api.Module,
|
||||
"{CtrlName}": fmt.Sprintf(`Controller%s`, gstr.UcFirst(api.Version)),
|
||||
"{CtrlName}": ctrlName,
|
||||
"{Version}": api.Version,
|
||||
"{MethodName}": api.MethodName,
|
||||
"{MethodComment}": api.GetComment(),
|
||||
}))
|
||||
|
||||
ctrlFilePath := gfile.Join(dstModuleFolderPath, fmt.Sprintf(
|
||||
`%s_%s_%s.go`, ctrlFileItem.module, ctrlFileItem.version, api.FileName,
|
||||
))
|
||||
// Use AST-based checking for more accurate method detection
|
||||
if methodExists(ctrlFilePath, ctrlName, api.MethodName) {
|
||||
return
|
||||
}
|
||||
|
||||
ctrlFileItem.controllers.WriteString(ctrl)
|
||||
doneApiSet.Add(api.String())
|
||||
}
|
||||
@ -229,3 +241,41 @@ func (c *controllerGenerator) doGenerateCtrlMergeItem(dstModuleFolderPath string
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// methodExists checks if a method with the given receiver type and name exists in the file.
|
||||
// It uses AST parsing to accurately detect method definitions regardless of formatting.
|
||||
// This handles various code formatting styles including multi-line method signatures.
|
||||
func methodExists(filePath, ctrlName, methodName string) bool {
|
||||
fset := token.NewFileSet()
|
||||
node, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
// If parsing fails (e.g., file doesn't exist or invalid syntax), return false
|
||||
return false
|
||||
}
|
||||
for _, decl := range node.Decls {
|
||||
funcDecl, ok := decl.(*ast.FuncDecl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Check if it's a method (has receiver)
|
||||
if funcDecl.Recv != nil && len(funcDecl.Recv.List) > 0 {
|
||||
// Extract receiver type name
|
||||
// Handle both *T and T patterns
|
||||
recvType := ""
|
||||
switch t := funcDecl.Recv.List[0].Type.(type) {
|
||||
case *ast.StarExpr:
|
||||
if ident, ok := t.X.(*ast.Ident); ok {
|
||||
recvType = ident.Name
|
||||
}
|
||||
case *ast.Ident:
|
||||
recvType = t.Name
|
||||
}
|
||||
|
||||
// Check if both receiver type and method name match
|
||||
if recvType == ctrlName && funcDecl.Name.Name == methodName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
BIN
cmd/gf/internal/cmd/gendao.zip
Normal file
BIN
cmd/gf/internal/cmd/gendao.zip
Normal file
Binary file not shown.
@ -47,8 +47,10 @@ type (
|
||||
JsonCase string `name:"jsonCase" short:"j" brief:"{CGenDaoBriefJsonCase}" d:"CamelLower"`
|
||||
ImportPrefix string `name:"importPrefix" short:"i" brief:"{CGenDaoBriefImportPrefix}"`
|
||||
DaoPath string `name:"daoPath" short:"d" brief:"{CGenDaoBriefDaoPath}" d:"dao"`
|
||||
TablePath string `name:"tablePath" short:"tp" brief:"{CGenDaoBriefTablePath}" d:"table"`
|
||||
DoPath string `name:"doPath" short:"o" brief:"{CGenDaoBriefDoPath}" d:"model/do"`
|
||||
EntityPath string `name:"entityPath" short:"e" brief:"{CGenDaoBriefEntityPath}" d:"model/entity"`
|
||||
TplDaoTablePath string `name:"tplDaoTablePath" short:"t0" brief:"{CGenDaoBriefTplDaoTablePath}"`
|
||||
TplDaoIndexPath string `name:"tplDaoIndexPath" short:"t1" brief:"{CGenDaoBriefTplDaoIndexPath}"`
|
||||
TplDaoInternalPath string `name:"tplDaoInternalPath" short:"t2" brief:"{CGenDaoBriefTplDaoInternalPath}"`
|
||||
TplDaoDoPath string `name:"tplDaoDoPath" short:"t3" brief:"{CGenDaoBriefTplDaoDoPathPath}"`
|
||||
@ -61,6 +63,7 @@ type (
|
||||
NoJsonTag bool `name:"noJsonTag" short:"k" brief:"{CGenDaoBriefNoJsonTag}" orphan:"true"`
|
||||
NoModelComment bool `name:"noModelComment" short:"m" brief:"{CGenDaoBriefNoModelComment}" orphan:"true"`
|
||||
Clear bool `name:"clear" short:"a" brief:"{CGenDaoBriefClear}" orphan:"true"`
|
||||
GenTable bool `name:"genTable" short:"gt" brief:"{CGenDaoBriefGenTable}" orphan:"true"`
|
||||
|
||||
TypeMapping map[DBFieldTypeName]CustomAttributeType `name:"typeMapping" short:"y" brief:"{CGenDaoBriefTypeMapping}" orphan:"true"`
|
||||
FieldMapping map[DBTableFieldName]CustomAttributeType `name:"fieldMapping" short:"fm" brief:"{CGenDaoBriefFieldMapping}" orphan:"true"`
|
||||
@ -101,6 +104,10 @@ var (
|
||||
"smallmoney": {
|
||||
Type: "float64",
|
||||
},
|
||||
"uuid": {
|
||||
Type: "uuid.UUID",
|
||||
Import: "github.com/google/uuid",
|
||||
},
|
||||
}
|
||||
|
||||
// tablewriter Options
|
||||
@ -190,8 +197,29 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
// Table excluding.
|
||||
if in.TablesEx != "" {
|
||||
array := garray.NewStrArrayFrom(tableNames)
|
||||
for _, v := range gstr.SplitAndTrim(in.TablesEx, ",") {
|
||||
array.RemoveValue(v)
|
||||
for _, p := range gstr.SplitAndTrim(in.TablesEx, ",") {
|
||||
if gstr.Contains(p, "*") || gstr.Contains(p, "?") {
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"\r": "",
|
||||
"\n": "",
|
||||
})
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"*": "\r",
|
||||
"?": "\n",
|
||||
})
|
||||
p = gregex.Quote(p)
|
||||
p = gstr.ReplaceByMap(p, map[string]string{
|
||||
"\r": ".*",
|
||||
"\n": ".",
|
||||
})
|
||||
for _, v := range array.Clone().Slice() {
|
||||
if gregex.IsMatchString(p, v) {
|
||||
array.RemoveValue(v)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
array.RemoveValue(p)
|
||||
}
|
||||
}
|
||||
tableNames = array.Slice()
|
||||
}
|
||||
@ -258,6 +286,14 @@ func doGenDaoForArray(ctx context.Context, index int, in CGenDaoInput) {
|
||||
NewTableNames: newTableNames,
|
||||
ShardingTableSet: shardingNewTableSet,
|
||||
})
|
||||
// Table: table fields.
|
||||
generateTable(ctx, CGenDaoInternalInput{
|
||||
CGenDaoInput: in,
|
||||
DB: db,
|
||||
TableNames: tableNames,
|
||||
NewTableNames: newTableNames,
|
||||
ShardingTableSet: shardingNewTableSet,
|
||||
})
|
||||
// Do.
|
||||
generateDo(ctx, CGenDaoInternalInput{
|
||||
CGenDaoInput: in,
|
||||
|
||||
@ -98,7 +98,6 @@ func generateStructFieldDefinition(
|
||||
err error
|
||||
localTypeName gdb.LocalType
|
||||
localTypeNameStr string
|
||||
jsonTag = gstr.CaseConvert(field.Name, gstr.CaseTypeMatch(in.JsonCase))
|
||||
)
|
||||
|
||||
if in.TypeMapping != nil && len(in.TypeMapping) > 0 {
|
||||
@ -156,6 +155,8 @@ func generateStructFieldDefinition(
|
||||
" #" + formatFieldName(newFiledName, FieldNameCaseCamel),
|
||||
" #" + localTypeNameStr,
|
||||
}
|
||||
|
||||
jsonTag := gstr.CaseConvert(newFiledName, gstr.CaseTypeMatch(in.JsonCase))
|
||||
attrLines = append(attrLines, fmt.Sprintf(` #%sjson:"%s"`, tagKey, jsonTag))
|
||||
// orm tag
|
||||
if !in.IsDo {
|
||||
|
||||
147
cmd/gf/internal/cmd/gendao/gendao_table.go
Normal file
147
cmd/gf/internal/cmd/gendao/gendao_table.go
Normal file
@ -0,0 +1,147 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package gendao
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/os/gview"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/consts"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/utils"
|
||||
)
|
||||
|
||||
// generateTable generates dao files for given tables.
|
||||
func generateTable(ctx context.Context, in CGenDaoInternalInput) {
|
||||
dirPathTable := gfile.Join(in.Path, in.TablePath)
|
||||
if !in.GenTable {
|
||||
if gfile.Exists(dirPathTable) {
|
||||
in.genItems.AppendDirPath(dirPathTable)
|
||||
}
|
||||
return
|
||||
}
|
||||
in.genItems.AppendDirPath(dirPathTable)
|
||||
for i := 0; i < len(in.TableNames); i++ {
|
||||
var (
|
||||
realTableName = in.TableNames[i]
|
||||
newTableName = in.NewTableNames[i]
|
||||
)
|
||||
generateTableSingle(ctx, generateTableSingleInput{
|
||||
CGenDaoInternalInput: in,
|
||||
TableName: realTableName,
|
||||
NewTableName: newTableName,
|
||||
DirPathTable: dirPathTable,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// generateTableSingleInput is the input parameter for generateTableSingle.
|
||||
type generateTableSingleInput struct {
|
||||
CGenDaoInternalInput
|
||||
// TableName specifies the table name of the table.
|
||||
TableName string
|
||||
// NewTableName specifies the prefix-stripped or custom edited name of the table.
|
||||
NewTableName string
|
||||
DirPathTable string
|
||||
}
|
||||
|
||||
// generateTableSingle generates dao files for a single table.
|
||||
func generateTableSingle(ctx context.Context, in generateTableSingleInput) {
|
||||
// Generating table data preparing.
|
||||
fieldMap, err := in.DB.TableFields(ctx, in.TableName)
|
||||
if err != nil {
|
||||
mlog.Fatalf(`fetching tables fields failed for table "%s": %+v`, in.TableName, err)
|
||||
}
|
||||
|
||||
tableNameSnakeCase := gstr.CaseSnake(in.NewTableName)
|
||||
fileName := gstr.Trim(tableNameSnakeCase, "-_.")
|
||||
if len(fileName) > 5 && fileName[len(fileName)-5:] == "_test" {
|
||||
// Add suffix to avoid the table name which contains "_test",
|
||||
// which would make the go file a testing file.
|
||||
fileName += "_table"
|
||||
}
|
||||
path := filepath.FromSlash(gfile.Join(in.DirPathTable, fileName+".go"))
|
||||
in.genItems.AppendGeneratedFilePath(path)
|
||||
if in.OverwriteDao || !gfile.Exists(path) {
|
||||
var (
|
||||
ctx = context.Background()
|
||||
tplContent = getTemplateFromPathOrDefault(
|
||||
in.TplDaoTablePath, consts.TemplateGenTableContent,
|
||||
)
|
||||
)
|
||||
tplView.ClearAssigns()
|
||||
tplView.Assigns(gview.Params{
|
||||
tplVarGroupName: in.Group,
|
||||
tplVarTableName: in.TableName,
|
||||
tplVarTableNameCamelCase: formatFieldName(in.NewTableName, FieldNameCaseCamel),
|
||||
tplVarPackageName: filepath.Base(in.TablePath),
|
||||
tplVarTableFields: generateTableFields(fieldMap),
|
||||
})
|
||||
indexContent, err := tplView.ParseContent(ctx, tplContent)
|
||||
if err != nil {
|
||||
mlog.Fatalf("parsing template content failed: %v", err)
|
||||
}
|
||||
if err = gfile.PutContents(path, strings.TrimSpace(indexContent)); err != nil {
|
||||
mlog.Fatalf("writing content to '%s' failed: %v", path, err)
|
||||
} else {
|
||||
utils.GoFmt(path)
|
||||
mlog.Print("generated:", gfile.RealPath(path))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// generateTableFields generates and returns the field definition content for specified table.
|
||||
func generateTableFields(fields map[string]*gdb.TableField) string {
|
||||
var buf bytes.Buffer
|
||||
fieldNames := make([]string, 0, len(fields))
|
||||
for fieldName := range fields {
|
||||
fieldNames = append(fieldNames, fieldName)
|
||||
}
|
||||
sort.Slice(fieldNames, func(i, j int) bool {
|
||||
return fields[fieldNames[i]].Index < fields[fieldNames[j]].Index // asc
|
||||
})
|
||||
for index, fieldName := range fieldNames {
|
||||
field := fields[fieldName]
|
||||
buf.WriteString(" " + strconv.Quote(field.Name) + ": {\n")
|
||||
buf.WriteString(" Index: " + gconv.String(field.Index) + ",\n")
|
||||
buf.WriteString(" Name: " + strconv.Quote(field.Name) + ",\n")
|
||||
buf.WriteString(" Type: " + strconv.Quote(field.Type) + ",\n")
|
||||
buf.WriteString(" Null: " + gconv.String(field.Null) + ",\n")
|
||||
buf.WriteString(" Key: " + strconv.Quote(field.Key) + ",\n")
|
||||
buf.WriteString(" Default: " + generateDefaultValue(field.Default) + ",\n")
|
||||
buf.WriteString(" Extra: " + strconv.Quote(field.Extra) + ",\n")
|
||||
buf.WriteString(" Comment: " + strconv.Quote(field.Comment) + ",\n")
|
||||
buf.WriteString(" },")
|
||||
if index != len(fieldNames)-1 {
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// generateDefaultValue generates and returns the default value definition for specified field.
|
||||
func generateDefaultValue(value interface{}) string {
|
||||
if value == nil {
|
||||
return "nil"
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return strconv.Quote(v)
|
||||
default:
|
||||
return gconv.String(v)
|
||||
}
|
||||
}
|
||||
@ -60,6 +60,7 @@ CONFIGURATION SUPPORT
|
||||
CGenDaoBriefGJsonSupport = `use gJsonSupport to use *gjson.Json instead of string for generated json fields of tables`
|
||||
CGenDaoBriefImportPrefix = `custom import prefix for generated go files`
|
||||
CGenDaoBriefDaoPath = `directory path for storing generated dao files under path`
|
||||
CGenDaoBriefTablePath = `directory path for storing generated table files under path`
|
||||
CGenDaoBriefDoPath = `directory path for storing generated do files under path`
|
||||
CGenDaoBriefEntityPath = `directory path for storing generated entity files under path`
|
||||
CGenDaoBriefOverwriteDao = `overwrite all dao files both inside/outside internal folder`
|
||||
@ -69,6 +70,7 @@ CONFIGURATION SUPPORT
|
||||
CGenDaoBriefNoJsonTag = `no json tag will be added for each field`
|
||||
CGenDaoBriefNoModelComment = `no model comment will be added for each field`
|
||||
CGenDaoBriefClear = `delete all generated go files that do not exist in database`
|
||||
CGenDaoBriefGenTable = `generate table files`
|
||||
CGenDaoBriefTypeMapping = `custom local type mapping for generated struct attributes relevant to fields of table`
|
||||
CGenDaoBriefFieldMapping = `custom local type mapping for generated struct attributes relevant to specific fields of table`
|
||||
CGenDaoBriefShardingPattern = `sharding pattern for table name, e.g. "users_?" will be replace tables "users_001,users_002,..." to "users" dao`
|
||||
@ -98,6 +100,7 @@ generated json tag case for model struct, cases are as follows:
|
||||
tplVarTableNameCamelLowerCase = `TplTableNameCamelLowerCase`
|
||||
tplVarTableSharding = `TplTableSharding`
|
||||
tplVarTableShardingPrefix = `TplTableShardingPrefix`
|
||||
tplVarTableFields = `TplTableFields`
|
||||
tplVarPackageImports = `TplPackageImports`
|
||||
tplVarImportPrefix = `TplImportPrefix`
|
||||
tplVarStructDefine = `TplStructDefine`
|
||||
@ -126,6 +129,7 @@ func init() {
|
||||
`CGenDaoBriefStdTime`: CGenDaoBriefStdTime,
|
||||
`CGenDaoBriefWithTime`: CGenDaoBriefWithTime,
|
||||
`CGenDaoBriefDaoPath`: CGenDaoBriefDaoPath,
|
||||
`CGenDaoBriefTablePath`: CGenDaoBriefTablePath,
|
||||
`CGenDaoBriefDoPath`: CGenDaoBriefDoPath,
|
||||
`CGenDaoBriefEntityPath`: CGenDaoBriefEntityPath,
|
||||
`CGenDaoBriefGJsonSupport`: CGenDaoBriefGJsonSupport,
|
||||
@ -137,6 +141,7 @@ func init() {
|
||||
`CGenDaoBriefNoJsonTag`: CGenDaoBriefNoJsonTag,
|
||||
`CGenDaoBriefNoModelComment`: CGenDaoBriefNoModelComment,
|
||||
`CGenDaoBriefClear`: CGenDaoBriefClear,
|
||||
`CGenDaoBriefGenTable`: CGenDaoBriefGenTable,
|
||||
`CGenDaoBriefTypeMapping`: CGenDaoBriefTypeMapping,
|
||||
`CGenDaoBriefFieldMapping`: CGenDaoBriefFieldMapping,
|
||||
`CGenDaoBriefShardingPattern`: CGenDaoBriefShardingPattern,
|
||||
|
||||
269
cmd/gf/internal/cmd/geninit/geninit.go
Normal file
269
cmd/gf/internal/cmd/geninit/geninit.go
Normal file
@ -0,0 +1,269 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// ProcessOptions contains options for the Process function
|
||||
type ProcessOptions struct {
|
||||
SelectVersion bool // Enable interactive version selection
|
||||
ModulePath string // Custom go.mod module path (e.g., github.com/xxx/xxx)
|
||||
UpgradeDeps bool // Upgrade dependencies to latest (go get -u ./...)
|
||||
}
|
||||
|
||||
// Process handles the template generation flow from remote repository
|
||||
func Process(ctx context.Context, repo, name string, opts *ProcessOptions) error {
|
||||
if opts == nil {
|
||||
opts = &ProcessOptions{}
|
||||
}
|
||||
|
||||
// 0. Check Go environment first
|
||||
mlog.Print("Checking Go environment...")
|
||||
goEnv, err := CheckGoEnv(ctx)
|
||||
if err != nil {
|
||||
mlog.Printf("Go environment check failed: %v", err)
|
||||
return err
|
||||
}
|
||||
mlog.Printf("Go environment OK (version: %s)", goEnv.GOVERSION)
|
||||
|
||||
// Check if this is a git subdirectory URL
|
||||
if IsSubdirRepo(repo) {
|
||||
return processGitSubdir(ctx, repo, name, opts)
|
||||
}
|
||||
|
||||
// Try Go module download first, fallback to git subdirectory if it fails
|
||||
// This handles edge cases where the heuristic may be incorrect
|
||||
err = processGoModule(ctx, repo, name, opts)
|
||||
if err != nil {
|
||||
mlog.Printf("Go module download failed, trying git subdirectory mode: %v", err)
|
||||
mlog.Print("Note: If this is a git subdirectory, you can force git mode by using a full git URL")
|
||||
|
||||
// If Go module download fails, try git subdirectory as fallback
|
||||
// This handles cases where the heuristic incorrectly classified a git subdir as Go module
|
||||
if IsSubdirRepo(repo) {
|
||||
mlog.Print("Falling back to git subdirectory download...")
|
||||
return processGitSubdir(ctx, repo, name, opts)
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// processGoModule handles standard Go module download via go get
|
||||
func processGoModule(ctx context.Context, repo, name string, opts *ProcessOptions) error {
|
||||
// Extract module path (without version)
|
||||
modulePath := repo
|
||||
specifiedVersion := ""
|
||||
if gstr.Contains(repo, "@") {
|
||||
parts := gstr.Split(repo, "@")
|
||||
modulePath = parts[0]
|
||||
specifiedVersion = parts[1]
|
||||
}
|
||||
|
||||
// Default name to repo basename if empty
|
||||
if name == "" {
|
||||
name = filepath.Base(modulePath)
|
||||
}
|
||||
|
||||
// Determine the target module path for go.mod
|
||||
targetModulePath := name
|
||||
if opts.ModulePath != "" {
|
||||
targetModulePath = opts.ModulePath
|
||||
}
|
||||
|
||||
// 1. Determine version to use
|
||||
var targetVersion string
|
||||
if specifiedVersion != "" {
|
||||
// User specified version, try to use it first
|
||||
targetVersion = specifiedVersion
|
||||
mlog.Printf("Using specified version: %s", targetVersion)
|
||||
} else if opts.SelectVersion {
|
||||
// Interactive version selection
|
||||
mlog.Print("Fetching available versions...")
|
||||
versionInfo, err := GetModuleVersions(ctx, modulePath)
|
||||
if err != nil {
|
||||
mlog.Printf("Failed to get versions: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
targetVersion, err = SelectVersion(ctx, versionInfo.Versions, modulePath)
|
||||
if err != nil {
|
||||
mlog.Printf("Version selection failed: %v", err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Default: use latest version
|
||||
mlog.Print("Fetching latest version...")
|
||||
latest, err := GetLatestVersion(ctx, modulePath)
|
||||
if err != nil {
|
||||
mlog.Printf("Failed to get latest version, will try @latest tag: %v", err)
|
||||
targetVersion = "latest"
|
||||
} else {
|
||||
targetVersion = latest
|
||||
mlog.Printf("Latest version: %s", targetVersion)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Download Template with determined version
|
||||
repoWithVersion := modulePath + "@" + targetVersion
|
||||
srcDir, err := downloadTemplate(ctx, repoWithVersion)
|
||||
if err != nil {
|
||||
// If specified version download failed, offer to select from available versions
|
||||
if specifiedVersion != "" {
|
||||
mlog.Printf("Failed to download specified version '%s': %v", specifiedVersion, err)
|
||||
mlog.Print("Fetching available versions...")
|
||||
|
||||
versionInfo, verErr := GetModuleVersions(ctx, modulePath)
|
||||
if verErr != nil {
|
||||
mlog.Printf("Failed to get available versions: %v", verErr)
|
||||
return err // Return original download error
|
||||
}
|
||||
|
||||
if len(versionInfo.Versions) == 0 {
|
||||
mlog.Print("No versions available for this module")
|
||||
return err
|
||||
}
|
||||
|
||||
// Let user select from available versions
|
||||
selectedVersion, selErr := SelectVersion(ctx, versionInfo.Versions, modulePath)
|
||||
if selErr != nil {
|
||||
mlog.Printf("Version selection failed: %v", selErr)
|
||||
return selErr
|
||||
}
|
||||
|
||||
// Retry download with selected version
|
||||
targetVersion = selectedVersion
|
||||
repoWithVersion = modulePath + "@" + targetVersion
|
||||
srcDir, err = downloadTemplate(ctx, repoWithVersion)
|
||||
if err != nil {
|
||||
mlog.Printf("Download failed: %v", err)
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
mlog.Printf("Download failed: %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
mlog.Debugf("Template located at: %s", srcDir)
|
||||
|
||||
// 3. Generate Project
|
||||
if err := generateProject(ctx, srcDir, name, modulePath, targetModulePath); err != nil {
|
||||
mlog.Printf("Generation failed: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. Handle dependencies
|
||||
var projectDir string
|
||||
if name == "." {
|
||||
projectDir = gfile.Pwd()
|
||||
} else {
|
||||
projectDir = filepath.Join(gfile.Pwd(), name)
|
||||
}
|
||||
if opts.UpgradeDeps {
|
||||
// Upgrade all dependencies to latest
|
||||
if err := upgradeDependencies(ctx, projectDir); err != nil {
|
||||
mlog.Printf("Failed to upgrade dependencies: %v", err)
|
||||
}
|
||||
} else {
|
||||
// Default: just tidy dependencies
|
||||
if err := tidyDependencies(ctx, projectDir); err != nil {
|
||||
mlog.Printf("Failed to tidy dependencies: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// processGitSubdir handles git subdirectory download via sparse checkout
|
||||
func processGitSubdir(ctx context.Context, repo, name string, opts *ProcessOptions) error {
|
||||
mlog.Print("Detected subdirectory URL, using git sparse checkout...")
|
||||
|
||||
// Check if git is available
|
||||
gitVersion, err := CheckGitEnv(ctx)
|
||||
if err != nil {
|
||||
mlog.Printf("Git is required for subdirectory templates: %v", err)
|
||||
return err
|
||||
}
|
||||
mlog.Printf("Git available (%s)", gitVersion)
|
||||
|
||||
// Download via git sparse checkout
|
||||
srcDir, gitInfo, err := downloadGitSubdir(ctx, repo)
|
||||
if err != nil {
|
||||
mlog.Printf("Git download failed: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Clean up temp directory after generation
|
||||
// The temp dir is parent of parent of srcDir (tempDir/repo/subpath)
|
||||
tempDir := filepath.Dir(filepath.Dir(srcDir))
|
||||
if tempDir != "" && gfile.Exists(tempDir) && gstr.Contains(tempDir, "gf-init-git") {
|
||||
defer func() {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory %s: %v", tempDir, err)
|
||||
} else {
|
||||
mlog.Debugf("Cleaned up temp directory: %s", tempDir)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Default name to subpath basename if empty
|
||||
if name == "" {
|
||||
name = filepath.Base(gitInfo.SubPath)
|
||||
}
|
||||
|
||||
// Get original module name from go.mod (might be "main" or something else)
|
||||
oldModule := GetModuleNameFromGoMod(srcDir)
|
||||
if oldModule == "" {
|
||||
// Fallback: construct from git info
|
||||
oldModule = gitInfo.Host + "/" + gitInfo.Owner + "/" + gitInfo.Repo + "/" + gitInfo.SubPath
|
||||
}
|
||||
|
||||
// Determine the target module path for go.mod
|
||||
targetModulePath := name
|
||||
if opts.ModulePath != "" {
|
||||
targetModulePath = opts.ModulePath
|
||||
}
|
||||
|
||||
mlog.Debugf("Template located at: %s", srcDir)
|
||||
mlog.Debugf("Original module: %s", oldModule)
|
||||
|
||||
// Generate Project
|
||||
if err := generateProject(ctx, srcDir, name, oldModule, targetModulePath); err != nil {
|
||||
mlog.Printf("Generation failed: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Handle dependencies
|
||||
var projectDir string
|
||||
if name == "." {
|
||||
projectDir = gfile.Pwd()
|
||||
} else {
|
||||
projectDir = filepath.Join(gfile.Pwd(), name)
|
||||
}
|
||||
if opts.UpgradeDeps {
|
||||
// Upgrade all dependencies to latest
|
||||
if err := upgradeDependencies(ctx, projectDir); err != nil {
|
||||
mlog.Printf("Failed to upgrade dependencies: %v", err)
|
||||
}
|
||||
} else {
|
||||
// Default: just tidy dependencies
|
||||
if err := tidyDependencies(ctx, projectDir); err != nil {
|
||||
mlog.Printf("Failed to tidy dependencies: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
125
cmd/gf/internal/cmd/geninit/geninit_ast.go
Normal file
125
cmd/gf/internal/cmd/geninit/geninit_ast.go
Normal file
@ -0,0 +1,125 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/printer"
|
||||
"go/token"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// ASTReplacer handles import path replacement using Go AST
|
||||
type ASTReplacer struct {
|
||||
oldModule string
|
||||
newModule string
|
||||
fset *token.FileSet
|
||||
}
|
||||
|
||||
// NewASTReplacer creates a new AST-based import replacer
|
||||
func NewASTReplacer(oldModule, newModule string) *ASTReplacer {
|
||||
return &ASTReplacer{
|
||||
oldModule: oldModule,
|
||||
newModule: newModule,
|
||||
fset: token.NewFileSet(),
|
||||
}
|
||||
}
|
||||
|
||||
// ReplaceInFile replaces import paths in a single Go file
|
||||
func (r *ASTReplacer) ReplaceInFile(ctx context.Context, filePath string) error {
|
||||
// Read file content
|
||||
content := gfile.GetContents(filePath)
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parse the file
|
||||
file, err := parser.ParseFile(r.fset, filePath, content, parser.ParseComments)
|
||||
if err != nil {
|
||||
mlog.Debugf("Failed to parse %s: %v", filePath, err)
|
||||
return nil // Skip files that can't be parsed
|
||||
}
|
||||
|
||||
// Track if any changes were made
|
||||
changed := false
|
||||
|
||||
// Traverse and modify imports
|
||||
ast.Inspect(file, func(n ast.Node) bool {
|
||||
switch x := n.(type) {
|
||||
case *ast.ImportSpec:
|
||||
if x.Path != nil {
|
||||
importPath := strings.Trim(x.Path.Value, `"`)
|
||||
if strings.HasPrefix(importPath, r.oldModule) {
|
||||
// Replace only the leading module prefix for clarity and correctness.
|
||||
newPath := r.newModule + strings.TrimPrefix(importPath, r.oldModule)
|
||||
x.Path.Value = `"` + newPath + `"`
|
||||
changed = true
|
||||
mlog.Debugf("Replaced import: %s -> %s in %s", importPath, newPath, filePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write back to file without formatting.
|
||||
// Formatting will be handled by formatGoFiles after all replacements are done.
|
||||
var buf bytes.Buffer
|
||||
if err := printer.Fprint(&buf, r.fset, file); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return gfile.PutContents(filePath, buf.String())
|
||||
}
|
||||
|
||||
// ReplaceInDir replaces import paths in all Go files in a directory (recursively)
|
||||
func (r *ASTReplacer) ReplaceInDir(ctx context.Context, dir string) error {
|
||||
mlog.Printf("Replacing imports: %s -> %s", r.oldModule, r.newModule)
|
||||
|
||||
// Find all .go files
|
||||
files, err := findGoFiles(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
if err := r.ReplaceInFile(ctx, file); err != nil {
|
||||
mlog.Printf("Failed to process %s: %v", file, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// findGoFiles recursively finds all .go files in a directory
|
||||
func findGoFiles(dir string) ([]string, error) {
|
||||
var files []string
|
||||
|
||||
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() && strings.HasSuffix(path, ".go") {
|
||||
files = append(files, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
return files, err
|
||||
}
|
||||
111
cmd/gf/internal/cmd/geninit/geninit_downloader.go
Normal file
111
cmd/gf/internal/cmd/geninit/geninit_downloader.go
Normal file
@ -0,0 +1,111 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// downloadTemplate fetches the remote repository using go get
|
||||
func downloadTemplate(ctx context.Context, repo string) (string, error) {
|
||||
// 1. Create a temporary directory workspace
|
||||
tempDir := gfile.Temp("gf-init-cli")
|
||||
if tempDir == "" {
|
||||
return "", fmt.Errorf("failed to create temporary directory")
|
||||
}
|
||||
if err := gfile.Mkdir(tempDir); err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory %s: %v", tempDir, err)
|
||||
}
|
||||
}() // Clean up the temp workspace
|
||||
|
||||
mlog.Debugf("Using temp workspace: %s", tempDir)
|
||||
|
||||
// 2. Initialize a temp go module to perform go get
|
||||
// We run commands inside the temp directory
|
||||
if err := runCmd(ctx, tempDir, "go", "mod", "init", "temp"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 3. Run go get <repo>
|
||||
// Try different version strategies: original -> @latest -> @master
|
||||
moduleName := repo
|
||||
if gstr.Contains(repo, "@") {
|
||||
moduleName = gstr.Split(repo, "@")[0]
|
||||
}
|
||||
|
||||
var downloadErrs []string
|
||||
versionsToTry := []string{repo}
|
||||
if !gstr.Contains(repo, "@") {
|
||||
versionsToTry = append(versionsToTry, repo+"@latest", repo+"@master")
|
||||
}
|
||||
|
||||
var successRepo string
|
||||
for _, tryRepo := range versionsToTry {
|
||||
mlog.Printf("Downloading template %s...", tryRepo)
|
||||
if err := runCmd(ctx, tempDir, "go", "get", tryRepo); err == nil {
|
||||
successRepo = tryRepo
|
||||
break
|
||||
} else {
|
||||
downloadErrs = append(downloadErrs, fmt.Sprintf("%s: %v", tryRepo, err))
|
||||
mlog.Debugf("Failed to download %s, trying next...", tryRepo)
|
||||
}
|
||||
}
|
||||
|
||||
if successRepo == "" {
|
||||
errMsg := "all download attempts failed"
|
||||
if len(downloadErrs) > 0 {
|
||||
errMsg = strings.Join(downloadErrs, "; ")
|
||||
}
|
||||
return "", fmt.Errorf("failed to download repo %s: %s", repo, errMsg)
|
||||
}
|
||||
|
||||
// 4. Find the local path using go list -m -json <repo>
|
||||
listCmd := exec.CommandContext(ctx, "go", "list", "-m", "-json", moduleName)
|
||||
listCmd.Dir = tempDir
|
||||
output, err := listCmd.Output()
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
return "", fmt.Errorf("go list failed: %s", string(exitErr.Stderr))
|
||||
}
|
||||
return "", fmt.Errorf("failed to locate module path: %w", err)
|
||||
}
|
||||
|
||||
var modInfo struct {
|
||||
Dir string `json:"Dir"`
|
||||
}
|
||||
if err := json.Unmarshal(output, &modInfo); err != nil {
|
||||
return "", fmt.Errorf("failed to parse go list output: %w", err)
|
||||
}
|
||||
|
||||
if modInfo.Dir == "" {
|
||||
return "", fmt.Errorf("module directory not found for %s", repo)
|
||||
}
|
||||
|
||||
return modInfo.Dir, nil
|
||||
}
|
||||
|
||||
func runCmd(ctx context.Context, dir string, name string, args ...string) error {
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
90
cmd/gf/internal/cmd/geninit/geninit_env.go
Normal file
90
cmd/gf/internal/cmd/geninit/geninit_env.go
Normal file
@ -0,0 +1,90 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// GoEnv represents Go environment variables
|
||||
type GoEnv struct {
|
||||
GOVERSION string `json:"GOVERSION"`
|
||||
GOROOT string `json:"GOROOT"`
|
||||
GOPATH string `json:"GOPATH"`
|
||||
GOMODCACHE string `json:"GOMODCACHE"`
|
||||
GOPROXY string `json:"GOPROXY"`
|
||||
GO111MODULE string `json:"GO111MODULE"`
|
||||
}
|
||||
|
||||
// CheckGoEnv verifies Go is installed and properly configured
|
||||
func CheckGoEnv(ctx context.Context) (*GoEnv, error) {
|
||||
// 1. Check if go binary exists
|
||||
goPath, err := exec.LookPath("go")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("go is not installed or not in PATH: %w", err)
|
||||
}
|
||||
mlog.Debugf("Found go binary at: %s", goPath)
|
||||
|
||||
// 2. Get go env as JSON
|
||||
cmd := exec.CommandContext(ctx, "go", "env", "-json")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
return nil, fmt.Errorf("go env failed: %s", string(exitErr.Stderr))
|
||||
}
|
||||
return nil, fmt.Errorf("failed to run go env: %w", err)
|
||||
}
|
||||
|
||||
// 3. Parse JSON output
|
||||
var env GoEnv
|
||||
if err := json.Unmarshal(output, &env); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse go env output: %w", err)
|
||||
}
|
||||
|
||||
// 4. Validate critical environment variables
|
||||
if env.GOROOT == "" {
|
||||
return nil, fmt.Errorf("GOROOT is not set")
|
||||
}
|
||||
if env.GOMODCACHE == "" && env.GOPATH == "" {
|
||||
return nil, fmt.Errorf("neither GOMODCACHE nor GOPATH is set")
|
||||
}
|
||||
|
||||
mlog.Debugf("Go Version: %s", env.GOVERSION)
|
||||
mlog.Debugf("GOROOT: %s", env.GOROOT)
|
||||
mlog.Debugf("GOMODCACHE: %s", env.GOMODCACHE)
|
||||
mlog.Debugf("GOPROXY: %s", env.GOPROXY)
|
||||
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// CheckGitEnv verifies Git is installed and returns its version
|
||||
func CheckGitEnv(ctx context.Context) (string, error) {
|
||||
// 1. Check if git binary exists
|
||||
gitPath, err := exec.LookPath("git")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("git is not installed or not in PATH: %w", err)
|
||||
}
|
||||
mlog.Debugf("Found git binary at: %s", gitPath)
|
||||
|
||||
// 2. Get git version
|
||||
cmd := exec.CommandContext(ctx, "git", "--version")
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get git version: %w", err)
|
||||
}
|
||||
|
||||
version := strings.TrimSpace(string(output))
|
||||
mlog.Debugf("Git version: %s", version)
|
||||
|
||||
return version, nil
|
||||
}
|
||||
146
cmd/gf/internal/cmd/geninit/geninit_generator.go
Normal file
146
cmd/gf/internal/cmd/geninit/geninit_generator.go
Normal file
@ -0,0 +1,146 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// generateProject copies the template to the destination and performs cleanup
|
||||
// oldModule: original module path from template
|
||||
// newModule: target module path for go.mod (can be different from project name)
|
||||
func generateProject(ctx context.Context, srcPath, name, oldModule, newModule string) error {
|
||||
pwd := gfile.Pwd()
|
||||
|
||||
dstPath := filepath.Join(pwd, name)
|
||||
if name == "." {
|
||||
dstPath = pwd
|
||||
}
|
||||
|
||||
if gfile.Exists(dstPath) && !gfile.IsEmpty(dstPath) {
|
||||
return fmt.Errorf("target directory %s is not empty", dstPath)
|
||||
}
|
||||
|
||||
mlog.Printf("Generating project in %s...", dstPath)
|
||||
|
||||
// 1. Copy files
|
||||
if err := gfile.Copy(srcPath, dstPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 2. Clean up .git directory
|
||||
gitDir := filepath.Join(dstPath, ".git")
|
||||
if gfile.Exists(gitDir) {
|
||||
if err := gfile.Remove(gitDir); err != nil {
|
||||
mlog.Debugf("Failed to remove .git directory: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Clean up go.work and go.work.sum (workspace files should not be in generated project)
|
||||
for _, workFile := range []string{"go.work", "go.work.sum"} {
|
||||
workPath := filepath.Join(dstPath, workFile)
|
||||
if gfile.Exists(workPath) {
|
||||
if err := gfile.Remove(workPath); err != nil {
|
||||
mlog.Printf("Failed to remove %s: %v", workFile, err)
|
||||
} else {
|
||||
mlog.Debugf("Removed %s", workFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Update go.mod module name
|
||||
goModPath := filepath.Join(dstPath, "go.mod")
|
||||
if gfile.Exists(goModPath) {
|
||||
content := gfile.GetContents(goModPath)
|
||||
lines := gstr.Split(content, "\n")
|
||||
if len(lines) > 0 && gstr.HasPrefix(lines[0], "module ") {
|
||||
lines[0] = "module " + newModule
|
||||
newContent := gstr.Join(lines, "\n")
|
||||
if err := gfile.PutContents(goModPath, newContent); err != nil {
|
||||
mlog.Printf("Failed to update go.mod: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Use AST to replace import paths in all Go files
|
||||
if oldModule != "" && oldModule != newModule {
|
||||
replacer := NewASTReplacer(oldModule, newModule)
|
||||
if err := replacer.ReplaceInDir(ctx, dstPath); err != nil {
|
||||
return fmt.Errorf("failed to replace imports: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Format the generated Go files using go/format (not imports.Process)
|
||||
// Note: We use formatGoFiles instead of utils.GoFmt because imports.Process
|
||||
// may incorrectly "fix" local import paths by replacing them with cached module paths.
|
||||
formatGoFiles(dstPath)
|
||||
|
||||
mlog.Print("Project generated successfully!")
|
||||
return nil
|
||||
}
|
||||
|
||||
// tidyDependencies runs go mod tidy in the project directory
|
||||
func tidyDependencies(ctx context.Context, projectDir string) error {
|
||||
mlog.Print("Tidying dependencies (go mod tidy)...")
|
||||
if err := runCmd(ctx, projectDir, "go", "mod", "tidy"); err != nil {
|
||||
return fmt.Errorf("go mod tidy failed: %w", err)
|
||||
}
|
||||
mlog.Print("Dependencies tidied successfully!")
|
||||
return nil
|
||||
}
|
||||
|
||||
// upgradeDependencies runs go get -u ./... to upgrade all dependencies to latest
|
||||
func upgradeDependencies(ctx context.Context, projectDir string) error {
|
||||
mlog.Print("Upgrading dependencies to latest (go get -u ./...)...")
|
||||
if err := runCmd(ctx, projectDir, "go", "get", "-u", "./..."); err != nil {
|
||||
return fmt.Errorf("go get -u failed: %w", err)
|
||||
}
|
||||
// Run tidy again after upgrade
|
||||
if err := runCmd(ctx, projectDir, "go", "mod", "tidy"); err != nil {
|
||||
return fmt.Errorf("go mod tidy after upgrade failed: %w", err)
|
||||
}
|
||||
mlog.Print("Dependencies upgraded successfully!")
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatGoFiles formats all Go files in the directory using go/format.
|
||||
// Unlike imports.Process, this only formats code without modifying imports,
|
||||
// which prevents incorrect "fixing" of local import paths.
|
||||
func formatGoFiles(dir string) {
|
||||
files, err := findGoFiles(dir)
|
||||
if err != nil {
|
||||
mlog.Printf("Failed to find Go files for formatting: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
content := gfile.GetContents(file)
|
||||
if content == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
formatted, err := format.Source([]byte(content))
|
||||
if err != nil {
|
||||
mlog.Debugf("Failed to format %s: %v", file, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if string(formatted) != content {
|
||||
if err := gfile.PutContents(file, string(formatted)); err != nil {
|
||||
mlog.Debugf("Failed to write formatted file %s: %v", file, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
241
cmd/gf/internal/cmd/geninit/geninit_git_downloader.go
Normal file
241
cmd/gf/internal/cmd/geninit/geninit_git_downloader.go
Normal file
@ -0,0 +1,241 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// GitRepoInfo holds parsed git repository information
|
||||
type GitRepoInfo struct {
|
||||
Host string // e.g., github.com
|
||||
Owner string // e.g., gogf
|
||||
Repo string // e.g., examples
|
||||
Branch string // e.g., main (default: main)
|
||||
SubPath string // e.g., httpserver/jwt
|
||||
CloneURL string // e.g., https://github.com/gogf/examples.git
|
||||
}
|
||||
|
||||
// ParseGitURL parses a git URL and extracts repository info
|
||||
// Supports formats:
|
||||
// - github.com/owner/repo
|
||||
// - github.com/owner/repo/subdir/path
|
||||
// - github.com/owner/repo/tree/branch/subdir/path (from GitHub web URL)
|
||||
func ParseGitURL(url string) (*GitRepoInfo, error) {
|
||||
// Remove protocol prefix if present
|
||||
url = strings.TrimPrefix(url, "https://")
|
||||
url = strings.TrimPrefix(url, "http://")
|
||||
url = strings.TrimSuffix(url, ".git")
|
||||
|
||||
// Remove version suffix like @v1.0.0
|
||||
if idx := strings.Index(url, "@"); idx != -1 {
|
||||
url = url[:idx]
|
||||
}
|
||||
|
||||
parts := strings.Split(url, "/")
|
||||
if len(parts) < 3 {
|
||||
return nil, fmt.Errorf("invalid git URL: %s", url)
|
||||
}
|
||||
|
||||
info := &GitRepoInfo{
|
||||
Host: parts[0],
|
||||
Owner: parts[1],
|
||||
Repo: parts[2],
|
||||
Branch: "main", // default branch
|
||||
}
|
||||
|
||||
// Check for /tree/branch/ pattern (GitHub web URL)
|
||||
if len(parts) > 4 && parts[3] == "tree" {
|
||||
info.Branch = parts[4]
|
||||
if len(parts) > 5 {
|
||||
info.SubPath = strings.Join(parts[5:], "/")
|
||||
}
|
||||
} else if len(parts) > 3 {
|
||||
// Direct subpath: github.com/owner/repo/subdir/path
|
||||
info.SubPath = strings.Join(parts[3:], "/")
|
||||
}
|
||||
|
||||
info.CloneURL = fmt.Sprintf("https://%s/%s/%s.git", info.Host, info.Owner, info.Repo)
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// IsSubdirRepo checks if the URL points to a subdirectory of a repository
|
||||
// Returns false for Go module paths (which may have /vN suffix or nested module paths)
|
||||
// Note: This uses heuristics that may have false positives/negatives in edge cases
|
||||
func IsSubdirRepo(url string) bool {
|
||||
info, err := ParseGitURL(url)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if info.SubPath == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if this looks like a Go module path rather than a git subdirectory
|
||||
// Go modules can have nested paths like github.com/owner/repo/cmd/tool/v2
|
||||
// We should try to resolve it as a Go module first
|
||||
|
||||
// If the URL can be resolved as a Go module, it's not a subdir repo
|
||||
// We use a heuristic: check if the full path looks like a valid Go module
|
||||
// by checking if it ends with /vN (major version) or contains common module patterns
|
||||
|
||||
// Remove version suffix for checking
|
||||
cleanURL := url
|
||||
if before, _, ok := strings.Cut(url, "@"); ok {
|
||||
cleanURL = before
|
||||
}
|
||||
|
||||
// Check if the path ends with /vN (Go module major version)
|
||||
parts := strings.Split(cleanURL, "/")
|
||||
if len(parts) > 0 {
|
||||
lastPart := parts[len(parts)-1]
|
||||
if len(lastPart) >= 2 && lastPart[0] == 'v' {
|
||||
// Check if it's v2, v3, etc.
|
||||
if _, err := fmt.Sscanf(lastPart, "v%d", new(int)); err == nil {
|
||||
// This looks like a Go module with major version suffix
|
||||
// It could be either a versioned module or a subdir ending in vN
|
||||
// We'll treat it as a Go module and let go get handle it
|
||||
mlog.Debugf("URL %s detected as Go module (ends with /vN)", url)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For GitHub URLs, check if the subpath could be a nested Go module
|
||||
// Common patterns: cmd/*, internal/*, pkg/*, contrib/*
|
||||
subPathParts := strings.Split(info.SubPath, "/")
|
||||
if len(subPathParts) > 0 {
|
||||
firstPart := subPathParts[0]
|
||||
// These are common Go module nesting patterns
|
||||
if firstPart == "cmd" || firstPart == "contrib" || firstPart == "tools" {
|
||||
// This might be a nested Go module, not a simple subdirectory
|
||||
// Let go get try first
|
||||
mlog.Debugf("URL %s detected as Go module (starts with common pattern)", url)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
mlog.Debugf("URL %s detected as git subdirectory", url)
|
||||
return true
|
||||
}
|
||||
|
||||
// downloadGitSubdir downloads a subdirectory from a git repository using sparse checkout
|
||||
func downloadGitSubdir(ctx context.Context, repoURL string) (string, *GitRepoInfo, error) {
|
||||
info, err := ParseGitURL(repoURL)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
if info.SubPath == "" {
|
||||
return "", nil, fmt.Errorf("not a subdirectory URL: %s", repoURL)
|
||||
}
|
||||
|
||||
// Create temp directory for clone
|
||||
tempDir := gfile.Temp("gf-init-git")
|
||||
if tempDir == "" {
|
||||
return "", nil, fmt.Errorf("failed to create temporary directory")
|
||||
}
|
||||
if err := gfile.Mkdir(tempDir); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
cloneDir := filepath.Join(tempDir, info.Repo)
|
||||
mlog.Debugf("Using git temp workspace: %s", tempDir)
|
||||
mlog.Printf("Cloning %s (sparse checkout: %s)...", info.CloneURL, info.SubPath)
|
||||
|
||||
// 1. Clone with no checkout, filter, and sparse
|
||||
if err := runCmd(ctx, tempDir, "git", "clone", "--filter=blob:none", "--no-checkout", "--sparse", info.CloneURL); err != nil {
|
||||
// Fallback: try without filter for older git versions
|
||||
mlog.Debugf("Sparse clone failed, trying full clone...")
|
||||
if err := gfile.Remove(cloneDir); err != nil {
|
||||
mlog.Debugf("Failed to remove clone directory: %v", err)
|
||||
}
|
||||
if err := runCmd(ctx, tempDir, "git", "clone", "--no-checkout", info.CloneURL); err != nil {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("git clone failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Set sparse-checkout to the subpath
|
||||
if err := runCmd(ctx, cloneDir, "git", "sparse-checkout", "set", info.SubPath); err != nil {
|
||||
// Fallback for older git: use sparse-checkout init + set
|
||||
mlog.Debugf("sparse-checkout set failed, trying legacy method...")
|
||||
if err := runCmd(ctx, cloneDir, "git", "sparse-checkout", "init", "--cone"); err != nil {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("git sparse-checkout init (legacy) failed: %w", err)
|
||||
}
|
||||
if err := runCmd(ctx, cloneDir, "git", "sparse-checkout", "set", info.SubPath); err != nil {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("git sparse-checkout set (legacy) failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Checkout the branch
|
||||
if err := runCmd(ctx, cloneDir, "git", "checkout", info.Branch); err != nil {
|
||||
// Try master if main fails
|
||||
if info.Branch == "main" {
|
||||
mlog.Debugf("Branch 'main' not found, trying 'master'...")
|
||||
info.Branch = "master"
|
||||
if err := runCmd(ctx, cloneDir, "git", "checkout", "master"); err != nil {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("git checkout failed: %w", err)
|
||||
}
|
||||
} else {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("git checkout failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Return the path to the subdirectory
|
||||
subDirPath := filepath.Join(cloneDir, info.SubPath)
|
||||
if !gfile.Exists(subDirPath) {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
return "", nil, fmt.Errorf("subdirectory not found: %s", info.SubPath)
|
||||
}
|
||||
|
||||
mlog.Debugf("Subdirectory located at: %s", subDirPath)
|
||||
return subDirPath, info, nil
|
||||
}
|
||||
|
||||
// GetModuleNameFromGoMod reads module name from go.mod file
|
||||
func GetModuleNameFromGoMod(dir string) string {
|
||||
goModPath := filepath.Join(dir, "go.mod")
|
||||
if !gfile.Exists(goModPath) {
|
||||
return ""
|
||||
}
|
||||
|
||||
content := gfile.GetContents(goModPath)
|
||||
lines := gstr.Split(content, "\n")
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if after, ok := strings.CutPrefix(line, "module "); ok {
|
||||
return strings.TrimSpace(after)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
99
cmd/gf/internal/cmd/geninit/geninit_selector.go
Normal file
99
cmd/gf/internal/cmd/geninit/geninit_selector.go
Normal file
@ -0,0 +1,99 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// SelectVersion prompts user to select a version interactively
|
||||
func SelectVersion(ctx context.Context, versions []string, modulePath string) (string, error) {
|
||||
if len(versions) == 0 {
|
||||
return "", fmt.Errorf("no versions available for selection")
|
||||
}
|
||||
|
||||
if len(versions) == 1 {
|
||||
mlog.Printf("Only one version available: %s", versions[0])
|
||||
return versions[0], nil
|
||||
}
|
||||
|
||||
// Display available versions
|
||||
fmt.Printf("\nAvailable versions for %s:\n", modulePath)
|
||||
fmt.Println(strings.Repeat("-", 40))
|
||||
|
||||
// Show versions with index (newest first)
|
||||
maxDisplay := 20 // Limit display to avoid overwhelming output
|
||||
displayCount := len(versions)
|
||||
if displayCount > maxDisplay {
|
||||
displayCount = maxDisplay
|
||||
}
|
||||
|
||||
for i := 0; i < displayCount; i++ {
|
||||
marker := ""
|
||||
if i == 0 {
|
||||
marker = " (latest)"
|
||||
}
|
||||
fmt.Printf(" [%2d] %s%s\n", i+1, versions[i], marker)
|
||||
}
|
||||
|
||||
if len(versions) > maxDisplay {
|
||||
fmt.Printf(" ... and %d more versions\n", len(versions)-maxDisplay)
|
||||
}
|
||||
|
||||
fmt.Println(strings.Repeat("-", 40))
|
||||
|
||||
// Prompt for selection
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
for {
|
||||
fmt.Printf("Select version [1-%d] or enter version string (default: 1 for latest): ", displayCount)
|
||||
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
input = strings.TrimSpace(input)
|
||||
|
||||
// Default to latest
|
||||
if input == "" {
|
||||
fmt.Printf("Selected: %s (latest)\n", versions[0])
|
||||
return versions[0], nil
|
||||
}
|
||||
|
||||
// Try parsing as number first
|
||||
idx, err := strconv.Atoi(input)
|
||||
if err == nil {
|
||||
// Valid number - check if in range
|
||||
if idx >= 1 && idx <= len(versions) {
|
||||
// Allow selection from all versions, not just displayed ones
|
||||
selected := versions[idx-1]
|
||||
fmt.Printf("Selected: %s\n", selected)
|
||||
return selected, nil
|
||||
} else if idx < 1 || idx > displayCount {
|
||||
fmt.Printf("Invalid selection. Please enter a number between 1 and %d, or type a version string.\n", displayCount)
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
// Try matching the input as a version string (e.g., "v1.2.3")
|
||||
for _, v := range versions {
|
||||
if v == input || strings.Contains(v, input) {
|
||||
fmt.Printf("Selected: %s\n", v)
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
fmt.Printf("Version '%s' not found. Please select by number or type a valid version string.\n", input)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
138
cmd/gf/internal/cmd/geninit/geninit_version.go
Normal file
138
cmd/gf/internal/cmd/geninit/geninit_version.go
Normal file
@ -0,0 +1,138 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package geninit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/mod/semver"
|
||||
|
||||
"github.com/gogf/gf/v2/os/gfile"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
|
||||
)
|
||||
|
||||
// VersionInfo contains module version information
|
||||
type VersionInfo struct {
|
||||
Module string `json:"module"`
|
||||
Versions []string `json:"versions"`
|
||||
Latest string `json:"latest"`
|
||||
}
|
||||
|
||||
// GetModuleVersions fetches available versions for a Go module
|
||||
func GetModuleVersions(ctx context.Context, modulePath string) (*VersionInfo, error) {
|
||||
// Create a temporary directory for go list
|
||||
tempDir := gfile.Temp("gf-init-version")
|
||||
if tempDir == "" {
|
||||
return nil, fmt.Errorf("failed to create temporary directory for go list")
|
||||
}
|
||||
if err := gfile.Mkdir(tempDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err := gfile.Remove(tempDir); err != nil {
|
||||
mlog.Debugf("Failed to remove temp directory: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Initialize a temp go module
|
||||
if err := runCmd(ctx, tempDir, "go", "mod", "init", "temp"); err != nil {
|
||||
return nil, fmt.Errorf("failed to init temp module: %w", err)
|
||||
}
|
||||
|
||||
// Get versions using go list -m -versions
|
||||
cmd := exec.CommandContext(ctx, "go", "list", "-m", "-versions", modulePath)
|
||||
cmd.Dir = tempDir
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
// Try with @latest to see if module exists
|
||||
mlog.Debugf("go list -versions failed, trying @latest: %v", err)
|
||||
return getLatestOnly(ctx, tempDir, modulePath)
|
||||
}
|
||||
|
||||
// Parse output: "module/path v1.0.0 v1.1.0 v2.0.0"
|
||||
parts := strings.Fields(strings.TrimSpace(string(output)))
|
||||
if len(parts) < 1 {
|
||||
return nil, fmt.Errorf("no version information found for %s", modulePath)
|
||||
}
|
||||
|
||||
info := &VersionInfo{
|
||||
Module: parts[0],
|
||||
Versions: []string{},
|
||||
}
|
||||
|
||||
if len(parts) > 1 {
|
||||
info.Versions = parts[1:]
|
||||
// Sort versions in descending order (newest first)
|
||||
sort.Slice(info.Versions, func(i, j int) bool {
|
||||
return semver.Compare(info.Versions[i], info.Versions[j]) > 0
|
||||
})
|
||||
info.Latest = info.Versions[0]
|
||||
}
|
||||
|
||||
// If no tagged versions, try to get latest
|
||||
if len(info.Versions) == 0 {
|
||||
latestInfo, err := getLatestOnly(ctx, tempDir, modulePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info.Latest = latestInfo.Latest
|
||||
if latestInfo.Latest != "" {
|
||||
info.Versions = []string{latestInfo.Latest}
|
||||
}
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// getLatestOnly gets only the latest version when go list -versions fails
|
||||
func getLatestOnly(ctx context.Context, tempDir, modulePath string) (*VersionInfo, error) {
|
||||
// Try go list -m modulePath@latest
|
||||
cmd := exec.CommandContext(ctx, "go", "list", "-m", "-json", modulePath+"@latest")
|
||||
cmd.Dir = tempDir
|
||||
output, err := cmd.Output()
|
||||
if err != nil {
|
||||
// Try without @latest
|
||||
cmd = exec.CommandContext(ctx, "go", "list", "-m", "-json", modulePath)
|
||||
cmd.Dir = tempDir
|
||||
output, err = cmd.Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get module info for %s: %w", modulePath, err)
|
||||
}
|
||||
}
|
||||
|
||||
var modInfo struct {
|
||||
Path string `json:"Path"`
|
||||
Version string `json:"Version"`
|
||||
}
|
||||
if err := json.Unmarshal(output, &modInfo); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse module info: %w", err)
|
||||
}
|
||||
|
||||
return &VersionInfo{
|
||||
Module: modInfo.Path,
|
||||
Versions: []string{modInfo.Version},
|
||||
Latest: modInfo.Version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetLatestVersion returns the latest version of a module
|
||||
func GetLatestVersion(ctx context.Context, modulePath string) (string, error) {
|
||||
info, err := GetModuleVersions(ctx, modulePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info.Latest == "" {
|
||||
return "", fmt.Errorf("no version found for %s", modulePath)
|
||||
}
|
||||
return info.Latest, nil
|
||||
}
|
||||
@ -4,11 +4,11 @@ go 1.23.0
|
||||
|
||||
toolchain go1.24.6
|
||||
|
||||
require github.com/gogf/gf/v2 v2.9.3
|
||||
require github.com/gogf/gf/v2 v2.9.8
|
||||
|
||||
require (
|
||||
go.opentelemetry.io/otel v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.37.0 // indirect
|
||||
go.opentelemetry.io/otel v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
)
|
||||
|
||||
|
||||
40
cmd/gf/internal/cmd/testdata/build/varmap/go.sum
vendored
40
cmd/gf/internal/cmd/testdata/build/varmap/go.sum
vendored
@ -4,8 +4,8 @@ github.com/clbanning/mxj/v2 v2.7.0 h1:WA/La7UGCanFe5NpHF0Q3DNtnCsVoxbPKuyBNHWRyM
|
||||
github.com/clbanning/mxj/v2 v2.7.0/go.mod h1:hNiWqW14h+kc+MdF9C6/YoRfjEJoR3ou6tn/Qo+ve2s=
|
||||
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/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/emirpasic/gods/v2 v2.0.0-alpha h1:dwFlh8pBg1VMOXWGipNMRt8v96dKAIvBehtCt6OtunU=
|
||||
github.com/emirpasic/gods/v2 v2.0.0-alpha/go.mod h1:W0y4M2dtBB9U5z3YlghmpuUhiaZT2h6yoeE+C1sCp6A=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
@ -24,8 +24,8 @@ github.com/grokify/html-strip-tags-go v0.1.0 h1:03UrQLjAny8xci+R+qjCce/MYnpNXCtg
|
||||
github.com/grokify/html-strip-tags-go v0.1.0/go.mod h1:ZdzgfHEzAfz9X6Xe5eBLVblWIxXfYSQ40S/VKrAOGpc=
|
||||
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
@ -34,26 +34,26 @@ github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5
|
||||
github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y=
|
||||
github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI=
|
||||
github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g=
|
||||
github.com/olekukonko/tablewriter v1.0.9 h1:XGwRsYLC2bY7bNd93Dk51bcPZksWZmLYuaTHR0FqfL8=
|
||||
github.com/olekukonko/tablewriter v1.0.9/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
|
||||
github.com/olekukonko/tablewriter v1.1.0 h1:N0LHrshF4T39KvI96fn6GT8HEjXRXYNDrDjKFDB7RIY=
|
||||
github.com/olekukonko/tablewriter v1.1.0/go.mod h1:5c+EBPeSqvXnLLgkm9isDdzR3wjfBkHR9Nhfp3NWrzo=
|
||||
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/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
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/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
|
||||
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
|
||||
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
|
||||
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
|
||||
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
|
||||
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
|
||||
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
|
||||
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
|
||||
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
|
||||
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
|
||||
@ -1,13 +1,10 @@
|
||||
package testdata
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
"github.com/gogf/gf/v2/test/gtest"
|
||||
"github.com/gogf/gf/v2/util/guid"
|
||||
)
|
||||
|
||||
|
||||
@ -7,8 +7,8 @@ package article
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v2"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v2"
|
||||
)
|
||||
|
||||
type IArticleV1 interface {
|
||||
@ -5,7 +5,7 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v1"
|
||||
)
|
||||
|
||||
// Create add title.
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v2"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v2"
|
||||
)
|
||||
|
||||
func (c *ControllerV2) Create(ctx context.Context, req *v2.CreateReq) (res *v2.CreateRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/api/article/v2"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/default/api/article/v2"
|
||||
)
|
||||
|
||||
func (c *ControllerV2) Update(ctx context.Context, req *v2.UpdateReq) (res *v2.UpdateRes, err error) {
|
||||
@ -7,7 +7,7 @@ package dict
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict/v1"
|
||||
)
|
||||
|
||||
type IDictV1 interface {
|
||||
@ -7,7 +7,7 @@ package dict
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict/v1"
|
||||
)
|
||||
|
||||
type IDictV1 interface {
|
||||
@ -5,7 +5,7 @@
|
||||
package dict
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
|
||||
@ -7,7 +7,7 @@ package dict
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_ctrl/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_ctrl/api/dict/v1"
|
||||
)
|
||||
|
||||
type IDictV1 interface {
|
||||
@ -7,7 +7,7 @@ package dict
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_file/api/dict/v1"
|
||||
)
|
||||
|
||||
type IDictV1 interface {
|
||||
@ -5,7 +5,7 @@
|
||||
package dict
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_file/api/dict"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_file/api/dict/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) DictTypeAddPage(ctx context.Context, req *v1.DictTypeAddPageReq) (res *v1.DictTypeAddPageRes, err error) {
|
||||
@ -6,7 +6,7 @@ import (
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl-merge/add_new_file/api/dict/v1"
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/merge/add_new_file/api/dict/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) DictTypeAdd(ctx context.Context, req *v1.DictTypeAddReq) (res *v1.DictTypeAddRes, err error) {
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/article/article_expect.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/article/article_expect.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package article
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/article/v1"
|
||||
)
|
||||
|
||||
type IArticleV1 interface {
|
||||
Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error)
|
||||
}
|
||||
19
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/article/v1/edit.go
vendored
Normal file
19
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/article/v1/edit.go
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package v1
|
||||
|
||||
import "github.com/gogf/gf/v2/frame/g"
|
||||
|
||||
type (
|
||||
// CreateReq add title.
|
||||
CreateReq struct {
|
||||
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
CreateRes struct{}
|
||||
)
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/user/user_expect.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/user/user_expect.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/user/v1"
|
||||
)
|
||||
|
||||
type IUserV1 interface {
|
||||
Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error)
|
||||
}
|
||||
19
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/user/v1/edit.go
vendored
Normal file
19
cmd/gf/internal/cmd/testdata/genctrl/multi/api/admin/user/v1/edit.go
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package v1
|
||||
|
||||
import "github.com/gogf/gf/v2/frame/g"
|
||||
|
||||
type (
|
||||
// CreateReq add title.
|
||||
CreateReq struct {
|
||||
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
CreateRes struct{}
|
||||
)
|
||||
16
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_expect.go
vendored
Normal file
16
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_expect.go
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/v1"
|
||||
)
|
||||
|
||||
type IUserV1 interface {
|
||||
Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error)
|
||||
Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error)
|
||||
}
|
||||
16
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/user_ext_expect.go
vendored
Normal file
16
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/user_ext_expect.go
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
// =================================================================================
|
||||
// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
|
||||
// =================================================================================
|
||||
|
||||
package user_ext
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/v1"
|
||||
)
|
||||
|
||||
type IUserExtV1 interface {
|
||||
Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error)
|
||||
Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error)
|
||||
}
|
||||
28
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/v1/edit.go
vendored
Normal file
28
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/v1/edit.go
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package v1
|
||||
|
||||
import "github.com/gogf/gf/v2/frame/g"
|
||||
|
||||
type (
|
||||
// CreateReq add title.
|
||||
CreateReq struct {
|
||||
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
CreateRes struct{}
|
||||
)
|
||||
|
||||
type (
|
||||
UpdateReq struct {
|
||||
g.Meta `path:"/article/update" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
UpdateRes struct{}
|
||||
)
|
||||
28
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/v1/edit.go
vendored
Normal file
28
cmd/gf/internal/cmd/testdata/genctrl/multi/api/app/user/v1/edit.go
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package v1
|
||||
|
||||
import "github.com/gogf/gf/v2/frame/g"
|
||||
|
||||
type (
|
||||
// CreateReq add title.
|
||||
CreateReq struct {
|
||||
g.Meta `path:"/article/create" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
CreateRes struct{}
|
||||
)
|
||||
|
||||
type (
|
||||
UpdateReq struct {
|
||||
g.Meta `path:"/article/update" method:"post" tags:"ArticleService"`
|
||||
Title string `v:"required"`
|
||||
}
|
||||
|
||||
UpdateRes struct{}
|
||||
)
|
||||
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article.go
vendored
Normal file
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article.go
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package article
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article_new.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article_new.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package article
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/article"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
|
||||
func NewV1() article.IArticleV1 {
|
||||
return &ControllerV1{}
|
||||
}
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article_v1_create.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/article/article_v1_create.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
package article
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/article/v1"
|
||||
)
|
||||
|
||||
// Create add title.
|
||||
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user.go
vendored
Normal file
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user.go
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user_new.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user_new.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/user"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
|
||||
func NewV1() user.IUserV1 {
|
||||
return &ControllerV1{}
|
||||
}
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user_v1_create.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/admin/user/user_v1_create.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/admin/user/v1"
|
||||
)
|
||||
|
||||
// Create add title.
|
||||
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user.go
vendored
Normal file
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user.go
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext.go
vendored
Normal file
5
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext.go
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user_ext
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_new.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_new.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user_ext
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
|
||||
func NewV1() user_ext.IUserExtV1 {
|
||||
return &ControllerV1{}
|
||||
}
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_v1_create.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_v1_create.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
package user_ext
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/v1"
|
||||
)
|
||||
|
||||
// Create add title.
|
||||
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
14
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_v1_update.go
vendored
Normal file
14
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_ext/user_ext_v1_update.go
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
package user_ext
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/user_ext/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_new.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_new.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// =================================================================================
|
||||
// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
|
||||
// =================================================================================
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user"
|
||||
)
|
||||
|
||||
type ControllerV1 struct{}
|
||||
|
||||
func NewV1() user.IUserV1 {
|
||||
return &ControllerV1{}
|
||||
}
|
||||
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_v1_create.go
vendored
Normal file
15
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_v1_create.go
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/v1"
|
||||
)
|
||||
|
||||
// Create add title.
|
||||
func (c *ControllerV1) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
14
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_v1_update.go
vendored
Normal file
14
cmd/gf/internal/cmd/testdata/genctrl/multi/controller/app/user/user_v1_update.go
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
|
||||
"github.com/gogf/gf/cmd/gf/v2/internal/cmd/testdata/genctrl/multi/api/app/user/v1"
|
||||
)
|
||||
|
||||
func (c *ControllerV1) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
|
||||
return nil, gerror.NewCode(gcode.CodeNotImplemented)
|
||||
}
|
||||
35
cmd/gf/internal/consts/consts_gen_dao_template_table.go
Normal file
35
cmd/gf/internal/consts/consts_gen_dao_template_table.go
Normal file
@ -0,0 +1,35 @@
|
||||
// Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package consts
|
||||
|
||||
const TemplateGenTableContent = `
|
||||
// =================================================================================
|
||||
// This file is auto-generated by the GoFrame CLI tool. You may modify it as needed.
|
||||
// =================================================================================
|
||||
|
||||
package {{.TplPackageName}}
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/database/gdb"
|
||||
)
|
||||
|
||||
// {{.TplTableNameCamelCase}} defines the fields of table "{{.TplTableName}}" with their properties.
|
||||
// This map is used internally by GoFrame ORM to understand table structure.
|
||||
var {{.TplTableNameCamelCase}} = map[string]*gdb.TableField{
|
||||
{{.TplTableFields}}
|
||||
}
|
||||
|
||||
// Set{{.TplTableNameCamelCase}}TableFields registers the table fields definition to the database instance.
|
||||
// db: database instance that implements gdb.DB interface.
|
||||
// schema: optional schema/namespace name, especially for databases that support schemas.
|
||||
func Set{{.TplTableNameCamelCase}}TableFields(ctx context.Context, db gdb.DB, schema ...string) error {
|
||||
return db.GetCore().SetTableFields(ctx, "{{.TplTableName}}", {{.TplTableNameCamelCase}}, schema...)
|
||||
}
|
||||
|
||||
`
|
||||
@ -6,7 +6,10 @@
|
||||
|
||||
package garray
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// defaultComparatorInt for int comparison.
|
||||
func defaultComparatorInt(a, b int) int {
|
||||
@ -24,6 +27,14 @@ func defaultComparatorStr(a, b string) int {
|
||||
return strings.Compare(a, b)
|
||||
}
|
||||
|
||||
// defaultSorter is a generic sorting function that sorts a slice of comparable types
|
||||
// using the provided comparator function.
|
||||
func defaultSorter[T comparable](values []T, comparator func(a T, b T) int) {
|
||||
sort.Slice(values, func(i, j int) bool {
|
||||
return comparator(values[i], values[j]) < 0
|
||||
})
|
||||
}
|
||||
|
||||
// quickSortInt is the quick-sorting algorithm implements for int.
|
||||
func quickSortInt(values []int, comparator func(a, b int) int) {
|
||||
if len(values) <= 1 {
|
||||
@ -67,3 +78,51 @@ func quickSortStr(values []string, comparator func(a, b string) int) {
|
||||
quickSortStr(values[:head], comparator)
|
||||
quickSortStr(values[head+1:], comparator)
|
||||
}
|
||||
|
||||
// tToAnySlice converts []T to []any
|
||||
func tToAnySlice[T any](values []T) []any {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
anyValues := make([]any, len(values), cap(values))
|
||||
for k, v := range values {
|
||||
anyValues[k] = v
|
||||
}
|
||||
return anyValues
|
||||
}
|
||||
|
||||
// anyToTSlice is convert []any to []T
|
||||
func anyToTSlice[T any](values []any) []T {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
tValues := make([]T, len(values), cap(values))
|
||||
for k, v := range values {
|
||||
tValues[k], _ = v.(T)
|
||||
}
|
||||
return tValues
|
||||
}
|
||||
|
||||
// tToAnySlices converts [][]T to [][]any
|
||||
func tToAnySlices[T any](values [][]T) [][]any {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
anyValues := make([][]any, len(values), cap(values))
|
||||
for k, v := range values {
|
||||
anyValues[k] = tToAnySlice(v)
|
||||
}
|
||||
return anyValues
|
||||
}
|
||||
|
||||
// anyToTSlices converts [][]any to [][]T
|
||||
func anyToTSlices[T any](values [][]any) [][]T {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
tValues := make([][]T, len(values), cap(values))
|
||||
for k, v := range values {
|
||||
tValues[k] = anyToTSlice[T](v)
|
||||
}
|
||||
return tValues
|
||||
}
|
||||
|
||||
@ -7,28 +7,18 @@
|
||||
package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/internal/deepcopy"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
)
|
||||
|
||||
// Array is a golang array with rich features.
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type Array struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []any
|
||||
*TArray[any]
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// New creates and returns an empty array.
|
||||
@ -48,8 +38,7 @@ func NewArray(safe ...bool) *Array {
|
||||
// which is false in default.
|
||||
func NewArraySize(size int, cap int, safe ...bool) *Array {
|
||||
return &Array{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]any, size, cap),
|
||||
TArray: NewTArraySize[any](size, cap, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,8 +74,7 @@ func NewFromCopy(array []any, safe ...bool) *Array {
|
||||
// which is false in default.
|
||||
func NewArrayFrom(array []any, safe ...bool) *Array {
|
||||
return &Array{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: array,
|
||||
TArray: NewTArrayFrom(array, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -96,265 +84,149 @@ func NewArrayFrom(array []any, safe ...bool) *Array {
|
||||
func NewArrayFromCopy(array []any, safe ...bool) *Array {
|
||||
newArray := make([]any, len(array))
|
||||
copy(newArray, array)
|
||||
return &Array{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: newArray,
|
||||
}
|
||||
return NewArrayFrom(newArray, safe...)
|
||||
}
|
||||
|
||||
// lazyInit lazily initializes the array.
|
||||
func (a *Array) lazyInit() {
|
||||
a.once.Do(func() {
|
||||
if a.TArray == nil {
|
||||
a.TArray = NewTArray[any](false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns `nil`.
|
||||
func (a *Array) At(index int) (value any) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.At(index)
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *Array) Get(index int) (value any, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return nil, false
|
||||
}
|
||||
return a.array[index], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Get(index)
|
||||
}
|
||||
|
||||
// Set sets value to specified index.
|
||||
func (a *Array) Set(index int, value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
a.array[index] = value
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Set(index, value)
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *Array) SetArray(array []any) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
a.lazyInit()
|
||||
a.TArray.SetArray(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Replace replaces the array items by given `array` from the beginning of array.
|
||||
func (a *Array) Replace(array []any) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
max := len(array)
|
||||
if max > len(a.array) {
|
||||
max = len(a.array)
|
||||
}
|
||||
for i := 0; i < max; i++ {
|
||||
a.array[i] = array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Replace(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *Array) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += gconv.Int(v)
|
||||
}
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.Sum()
|
||||
}
|
||||
|
||||
// SortFunc sorts the array by custom function `less`.
|
||||
func (a *Array) SortFunc(less func(v1, v2 any) bool) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return less(a.array[i], a.array[j])
|
||||
})
|
||||
a.lazyInit()
|
||||
a.TArray.SortFunc(less)
|
||||
return a
|
||||
}
|
||||
|
||||
// InsertBefore inserts the `values` to the front of `index`.
|
||||
func (a *Array) InsertBefore(index int, values ...any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]any{}, a.array[index:]...)
|
||||
a.array = append(a.array[0:index], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertBefore(index, values...)
|
||||
}
|
||||
|
||||
// InsertAfter inserts the `values` to the back of `index`.
|
||||
func (a *Array) InsertAfter(index int, values ...any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]any{}, a.array[index+1:]...)
|
||||
a.array = append(a.array[0:index+1], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertAfter(index, values...)
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *Array) Remove(index int) (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *Array) doRemoveWithoutLock(index int) (value any, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return nil, false
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.Remove(index)
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *Array) RemoveValue(value any) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
a.lazyInit()
|
||||
return a.TArray.RemoveValue(value)
|
||||
}
|
||||
|
||||
// RemoveValues removes multiple items by `values`.
|
||||
func (a *Array) RemoveValues(values ...any) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.RemoveValues(values...)
|
||||
}
|
||||
|
||||
// PushLeft pushes one or multiple items to the beginning of array.
|
||||
func (a *Array) PushLeft(value ...any) *Array {
|
||||
a.mu.Lock()
|
||||
a.array = append(value, a.array...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushLeft(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PushRight pushes one or multiple items to the end of array.
|
||||
// It equals to Append.
|
||||
func (a *Array) PushRight(value ...any) *Array {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushRight(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *Array) PopRand() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRand()
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
func (a *Array) PopRands(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]any, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRands(size)
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *Array) PopLeft() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLeft()
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *Array) PopRight() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
return nil, false
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRight()
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
func (a *Array) PopLefts(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLefts(size)
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
func (a *Array) PopRights(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRights(size)
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
@ -365,26 +237,8 @@ func (a *Array) PopRights(size int) []any {
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *Array) Range(start int, end ...int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]any)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]any, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Range(start, end...)
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
@ -401,69 +255,29 @@ func (a *Array) Range(start int, end ...int) []any {
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *Array) SubSlice(offset int, length ...int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]any, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
} else {
|
||||
return a.array[offset:end]
|
||||
}
|
||||
a.lazyInit()
|
||||
return a.TArray.SubSlice(offset, length...)
|
||||
}
|
||||
|
||||
// Append is alias of PushRight, please See PushRight.
|
||||
func (a *Array) Append(value ...any) *Array {
|
||||
a.PushRight(value...)
|
||||
a.lazyInit()
|
||||
a.TArray.Append(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *Array) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
a.lazyInit()
|
||||
return a.TArray.Len()
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *Array) Slice() []any {
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array := make([]any, len(a.array))
|
||||
copy(array, a.array)
|
||||
return array
|
||||
} else {
|
||||
return a.array
|
||||
}
|
||||
a.lazyInit()
|
||||
return a.TArray.Slice()
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
@ -473,89 +287,49 @@ func (a *Array) Interfaces() []any {
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *Array) Clone() (newArray *Array) {
|
||||
a.mu.RLock()
|
||||
array := make([]any, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewArrayFrom(array, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &Array{TArray: a.TArray.Clone()}
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *Array) Clear() *Array {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]any, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.Clear()
|
||||
return a
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *Array) Contains(value any) bool {
|
||||
return a.Search(value) != -1
|
||||
a.lazyInit()
|
||||
return a.TArray.Contains(value)
|
||||
}
|
||||
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *Array) Search(value any) int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return a.doSearchWithoutLock(value)
|
||||
}
|
||||
|
||||
func (a *Array) doSearchWithoutLock(value any) int {
|
||||
if len(a.array) == 0 {
|
||||
return -1
|
||||
}
|
||||
result := -1
|
||||
for index, v := range a.array {
|
||||
if v == value {
|
||||
result = index
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
a.lazyInit()
|
||||
return a.TArray.Search(value)
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
// Example: [1,1,2,3,2] -> [1,2,3]
|
||||
func (a *Array) Unique() *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
var (
|
||||
ok bool
|
||||
temp any
|
||||
uniqueSet = make(map[any]struct{})
|
||||
uniqueArray = make([]any, 0, len(a.array))
|
||||
)
|
||||
for i := 0; i < len(a.array); i++ {
|
||||
temp = a.array[i]
|
||||
if _, ok = uniqueSet[temp]; ok {
|
||||
continue
|
||||
}
|
||||
uniqueSet[temp] = struct{}{}
|
||||
uniqueArray = append(uniqueArray, temp)
|
||||
}
|
||||
a.array = uniqueArray
|
||||
a.lazyInit()
|
||||
a.TArray.Unique()
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *Array) LockFunc(f func(array []any)) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.LockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *Array) RLockFunc(f func(array []any)) *Array {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.RLockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -564,48 +338,23 @@ func (a *Array) RLockFunc(f func(array []any)) *Array {
|
||||
// The difference between Merge and Append is Append supports only specified slice type,
|
||||
// but Merge supports more parameter types.
|
||||
func (a *Array) Merge(array any) *Array {
|
||||
a.lazyInit()
|
||||
return a.Append(gconv.Interfaces(array)...)
|
||||
}
|
||||
|
||||
// Fill fills an array with num entries of the value `value`,
|
||||
// keys starting at the `startIndex` parameter.
|
||||
func (a *Array) Fill(startIndex int, num int, value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if startIndex < 0 || startIndex > len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||
}
|
||||
for i := startIndex; i < startIndex+num; i++ {
|
||||
if i > len(a.array)-1 {
|
||||
a.array = append(a.array, value)
|
||||
} else {
|
||||
a.array[i] = value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Fill(startIndex, num, value)
|
||||
}
|
||||
|
||||
// Chunk splits an array into multiple arrays,
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *Array) Chunk(size int) [][]any {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]any
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
a.lazyInit()
|
||||
return a.TArray.Chunk(size)
|
||||
}
|
||||
|
||||
// Pad pads array to the specified length with `value`.
|
||||
@ -613,98 +362,47 @@ func (a *Array) Chunk(size int) [][]any {
|
||||
// If the absolute value of `size` is less than or equal to the length of the array
|
||||
// then no padding takes place.
|
||||
func (a *Array) Pad(size int, val any) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
|
||||
return a
|
||||
}
|
||||
n := size
|
||||
if size < 0 {
|
||||
n = -size
|
||||
}
|
||||
n -= len(a.array)
|
||||
tmp := make([]any, n)
|
||||
for i := 0; i < n; i++ {
|
||||
tmp[i] = val
|
||||
}
|
||||
if size > 0 {
|
||||
a.array = append(a.array, tmp...)
|
||||
} else {
|
||||
a.array = append(tmp, a.array...)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Pad(size, val)
|
||||
return a
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *Array) Rand() (value any, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Rand()
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *Array) Rands(size int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]any, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Rands(size)
|
||||
}
|
||||
|
||||
// Shuffle randomly shuffles the array.
|
||||
func (a *Array) Shuffle() *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range grand.Perm(len(a.array)) {
|
||||
a.array[i], a.array[v] = a.array[v], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Shuffle()
|
||||
return a
|
||||
}
|
||||
|
||||
// Reverse makes array with elements in reverse order.
|
||||
func (a *Array) Reverse() *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, j := 0, len(a.array)-1; i < j; i, j = i+1, j-1 {
|
||||
a.array[i], a.array[j] = a.array[j], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Reverse()
|
||||
return a
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *Array) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(gconv.String(v))
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.TArray.Join(glue)
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *Array) CountValues() map[any]int {
|
||||
m := make(map[any]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
a.lazyInit()
|
||||
return a.TArray.CountValues()
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
@ -715,25 +413,15 @@ func (a *Array) Iterator(f func(k int, v any) bool) {
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *Array) IteratorAsc(f func(k int, v any) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *Array) IteratorDesc(f func(k int, v any) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorDesc(f)
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
@ -741,118 +429,64 @@ func (a *Array) String() string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteByte('[')
|
||||
s := ""
|
||||
for k, v := range a.array {
|
||||
s = gconv.String(v)
|
||||
if gstr.IsNumeric(s) {
|
||||
buffer.WriteString(s)
|
||||
} else {
|
||||
buffer.WriteString(`"` + gstr.QuoteMeta(s, `"\`) + `"`)
|
||||
}
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteByte(',')
|
||||
}
|
||||
}
|
||||
buffer.WriteByte(']')
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.TArray.String()
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a Array) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
a.lazyInit()
|
||||
return a.TArray.MarshalJSON()
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
func (a *Array) UnmarshalJSON(b []byte) error {
|
||||
if a.array == nil {
|
||||
a.array = make([]any, 0)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
func (a *Array) UnmarshalValue(value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
return json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
a.array = gconv.SliceAny(value)
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalValue(value)
|
||||
}
|
||||
|
||||
// Filter iterates array and filters elements using custom callback function.
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *Array) Filter(filter func(index int, value any) bool) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Filter(filter)
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterNil removes all nil value of the array.
|
||||
func (a *Array) FilterNil() *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsNil(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.FilterNil()
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all empty value of the array.
|
||||
// Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.
|
||||
func (a *Array) FilterEmpty() *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsEmpty(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.FilterEmpty()
|
||||
return a
|
||||
}
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *Array) Walk(f func(value any) any) *Array {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Walk(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *Array) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
a.lazyInit()
|
||||
return a.TArray.IsEmpty()
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
@ -860,11 +494,8 @@ func (a *Array) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]any, len(a.array))
|
||||
for i, v := range a.array {
|
||||
newSlice[i] = deepcopy.Copy(v)
|
||||
a.lazyInit()
|
||||
return &Array{
|
||||
TArray: a.TArray.DeepCopy().(*TArray[any]),
|
||||
}
|
||||
return NewArrayFrom(newSlice, a.mu.IsSafe())
|
||||
}
|
||||
|
||||
@ -7,25 +7,19 @@
|
||||
package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
)
|
||||
|
||||
// IntArray is a golang int array with rich features.
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type IntArray struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []int
|
||||
*TArray[int]
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewIntArray creates and returns an empty array.
|
||||
@ -40,8 +34,7 @@ func NewIntArray(safe ...bool) *IntArray {
|
||||
// which is false in default.
|
||||
func NewIntArraySize(size int, cap int, safe ...bool) *IntArray {
|
||||
return &IntArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]int, size, cap),
|
||||
TArray: NewTArraySize[int](size, cap, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -65,8 +58,7 @@ func NewIntArrayRange(start, end, step int, safe ...bool) *IntArray {
|
||||
// which is false in default.
|
||||
func NewIntArrayFrom(array []int, safe ...bool) *IntArray {
|
||||
return &IntArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: array,
|
||||
TArray: NewTArrayFrom(array, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -76,78 +68,66 @@ func NewIntArrayFrom(array []int, safe ...bool) *IntArray {
|
||||
func NewIntArrayFromCopy(array []int, safe ...bool) *IntArray {
|
||||
newArray := make([]int, len(array))
|
||||
copy(newArray, array)
|
||||
return &IntArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: newArray,
|
||||
}
|
||||
return NewIntArrayFrom(newArray, safe...)
|
||||
}
|
||||
|
||||
// lazyInit lazily initializes the array.
|
||||
func (a *IntArray) lazyInit() {
|
||||
a.once.Do(func() {
|
||||
if a.TArray == nil {
|
||||
a.TArray = NewTArray[int](false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns `0`.
|
||||
func (a *IntArray) At(index int) (value int) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.At(index)
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *IntArray) Get(index int) (value int, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return 0, false
|
||||
}
|
||||
return a.array[index], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Get(index)
|
||||
}
|
||||
|
||||
// Set sets value to specified index.
|
||||
func (a *IntArray) Set(index int, value int) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
a.array[index] = value
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Set(index, value)
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *IntArray) SetArray(array []int) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
a.lazyInit()
|
||||
a.TArray.SetArray(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Replace replaces the array items by given `array` from the beginning of array.
|
||||
func (a *IntArray) Replace(array []int) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
max := len(array)
|
||||
if max > len(a.array) {
|
||||
max = len(a.array)
|
||||
}
|
||||
for i := 0; i < max; i++ {
|
||||
a.array[i] = array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Replace(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *IntArray) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += v
|
||||
}
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.Sum()
|
||||
}
|
||||
|
||||
// Sort sorts the array in increasing order.
|
||||
// The parameter `reverse` controls whether sort in increasing order(default) or decreasing order.
|
||||
func (a *IntArray) Sort(reverse ...bool) *IntArray {
|
||||
a.lazyInit()
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
if len(reverse) > 0 && reverse[0] {
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.array[i] >= a.array[j]
|
||||
@ -160,210 +140,101 @@ func (a *IntArray) Sort(reverse ...bool) *IntArray {
|
||||
|
||||
// SortFunc sorts the array by custom function `less`.
|
||||
func (a *IntArray) SortFunc(less func(v1, v2 int) bool) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return less(a.array[i], a.array[j])
|
||||
})
|
||||
a.lazyInit()
|
||||
a.TArray.SortFunc(less)
|
||||
return a
|
||||
}
|
||||
|
||||
// InsertBefore inserts the `values` to the front of `index`.
|
||||
func (a *IntArray) InsertBefore(index int, values ...int) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(
|
||||
gcode.CodeInvalidParameter,
|
||||
"index %d out of array range %d",
|
||||
index, len(a.array),
|
||||
)
|
||||
}
|
||||
rear := append([]int{}, a.array[index:]...)
|
||||
a.array = append(a.array[0:index], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertBefore(index, values...)
|
||||
}
|
||||
|
||||
// InsertAfter inserts the `value` to the back of `index`.
|
||||
func (a *IntArray) InsertAfter(index int, values ...int) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(
|
||||
gcode.CodeInvalidParameter,
|
||||
"index %d out of array range %d",
|
||||
index, len(a.array),
|
||||
)
|
||||
}
|
||||
rear := append([]int{}, a.array[index+1:]...)
|
||||
a.array = append(a.array[0:index+1], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertAfter(index, values...)
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *IntArray) Remove(index int) (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *IntArray) doRemoveWithoutLock(index int) (value int, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return 0, false
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.Remove(index)
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *IntArray) RemoveValue(value int) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
a.lazyInit()
|
||||
return a.TArray.RemoveValue(value)
|
||||
}
|
||||
|
||||
// RemoveValues removes multiple items by `values`.
|
||||
func (a *IntArray) RemoveValues(values ...int) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.RemoveValues(values...)
|
||||
}
|
||||
|
||||
// PushLeft pushes one or multiple items to the beginning of array.
|
||||
func (a *IntArray) PushLeft(value ...int) *IntArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(value, a.array...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushLeft(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PushRight pushes one or multiple items to the end of array.
|
||||
// It equals to Append.
|
||||
func (a *IntArray) PushRight(value ...int) *IntArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushRight(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *IntArray) PopLeft() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLeft()
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *IntArray) PopRight() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
return 0, false
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRight()
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *IntArray) PopRand() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRand()
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *IntArray) PopRands(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]int, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRands(size)
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *IntArray) PopLefts(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLefts(size)
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *IntArray) PopRights(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRights(size)
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
@ -374,26 +245,8 @@ func (a *IntArray) PopRights(size int) []int {
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *IntArray) Range(start int, end ...int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]int)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]int, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Range(start, end...)
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
@ -410,170 +263,84 @@ func (a *IntArray) Range(start int, end ...int) []int {
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *IntArray) SubSlice(offset int, length ...int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]int, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
} else {
|
||||
return a.array[offset:end]
|
||||
}
|
||||
a.lazyInit()
|
||||
return a.TArray.SubSlice(offset, length...)
|
||||
}
|
||||
|
||||
// Append is alias of PushRight,please See PushRight.
|
||||
func (a *IntArray) Append(value ...int) *IntArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.Append(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *IntArray) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
a.lazyInit()
|
||||
return a.TArray.Len()
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *IntArray) Slice() []int {
|
||||
array := ([]int)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array = make([]int, len(a.array))
|
||||
copy(array, a.array)
|
||||
} else {
|
||||
array = a.array
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Slice()
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
func (a *IntArray) Interfaces() []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array := make([]any, len(a.array))
|
||||
for k, v := range a.array {
|
||||
array[k] = v
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Interfaces()
|
||||
}
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *IntArray) Clone() (newArray *IntArray) {
|
||||
a.mu.RLock()
|
||||
array := make([]int, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewIntArrayFrom(array, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &IntArray{
|
||||
TArray: a.TArray.Clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *IntArray) Clear() *IntArray {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]int, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.Clear()
|
||||
return a
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *IntArray) Contains(value int) bool {
|
||||
return a.Search(value) != -1
|
||||
a.lazyInit()
|
||||
return a.TArray.Contains(value)
|
||||
}
|
||||
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *IntArray) Search(value int) int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return a.doSearchWithoutLock(value)
|
||||
}
|
||||
|
||||
func (a *IntArray) doSearchWithoutLock(value int) int {
|
||||
if len(a.array) == 0 {
|
||||
return -1
|
||||
}
|
||||
result := -1
|
||||
for index, v := range a.array {
|
||||
if v == value {
|
||||
result = index
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
a.lazyInit()
|
||||
return a.TArray.Search(value)
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
// Example: [1,1,2,3,2] -> [1,2,3]
|
||||
func (a *IntArray) Unique() *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
var (
|
||||
ok bool
|
||||
temp int
|
||||
uniqueSet = make(map[int]struct{})
|
||||
uniqueArray = make([]int, 0, len(a.array))
|
||||
)
|
||||
for i := 0; i < len(a.array); i++ {
|
||||
temp = a.array[i]
|
||||
if _, ok = uniqueSet[temp]; ok {
|
||||
continue
|
||||
}
|
||||
uniqueSet[temp] = struct{}{}
|
||||
uniqueArray = append(uniqueArray, temp)
|
||||
}
|
||||
a.array = uniqueArray
|
||||
a.lazyInit()
|
||||
a.TArray.Unique()
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *IntArray) LockFunc(f func(array []int)) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.LockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *IntArray) RLockFunc(f func(array []int)) *IntArray {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.RLockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -588,46 +355,16 @@ func (a *IntArray) Merge(array any) *IntArray {
|
||||
// Fill fills an array with num entries of the value `value`,
|
||||
// keys starting at the `startIndex` parameter.
|
||||
func (a *IntArray) Fill(startIndex int, num int, value int) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if startIndex < 0 || startIndex > len(a.array) {
|
||||
return gerror.NewCodef(
|
||||
gcode.CodeInvalidParameter,
|
||||
"index %d out of array range %d",
|
||||
startIndex, len(a.array),
|
||||
)
|
||||
}
|
||||
for i := startIndex; i < startIndex+num; i++ {
|
||||
if i > len(a.array)-1 {
|
||||
a.array = append(a.array, value)
|
||||
} else {
|
||||
a.array[i] = value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Fill(startIndex, num, value)
|
||||
}
|
||||
|
||||
// Chunk splits an array into multiple arrays,
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *IntArray) Chunk(size int) [][]int {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]int
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
a.lazyInit()
|
||||
return a.TArray.Chunk(size)
|
||||
}
|
||||
|
||||
// Pad pads array to the specified length with `value`.
|
||||
@ -635,98 +372,47 @@ func (a *IntArray) Chunk(size int) [][]int {
|
||||
// If the absolute value of `size` is less than or equal to the length of the array
|
||||
// then no padding takes place.
|
||||
func (a *IntArray) Pad(size int, value int) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
|
||||
return a
|
||||
}
|
||||
n := size
|
||||
if size < 0 {
|
||||
n = -size
|
||||
}
|
||||
n -= len(a.array)
|
||||
tmp := make([]int, n)
|
||||
for i := 0; i < n; i++ {
|
||||
tmp[i] = value
|
||||
}
|
||||
if size > 0 {
|
||||
a.array = append(a.array, tmp...)
|
||||
} else {
|
||||
a.array = append(tmp, a.array...)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Pad(size, value)
|
||||
return a
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *IntArray) Rand() (value int, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Rand()
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *IntArray) Rands(size int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]int, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Rands(size)
|
||||
}
|
||||
|
||||
// Shuffle randomly shuffles the array.
|
||||
func (a *IntArray) Shuffle() *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range grand.Perm(len(a.array)) {
|
||||
a.array[i], a.array[v] = a.array[v], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Shuffle()
|
||||
return a
|
||||
}
|
||||
|
||||
// Reverse makes array with elements in reverse order.
|
||||
func (a *IntArray) Reverse() *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, j := 0, len(a.array)-1; i < j; i, j = i+1, j-1 {
|
||||
a.array[i], a.array[j] = a.array[j], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Reverse()
|
||||
return a
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *IntArray) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(gconv.String(v))
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.TArray.Join(glue)
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *IntArray) CountValues() map[int]int {
|
||||
m := make(map[int]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
a.lazyInit()
|
||||
return a.TArray.CountValues()
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
@ -737,25 +423,15 @@ func (a *IntArray) Iterator(f func(k int, v int) bool) {
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *IntArray) IteratorAsc(f func(k int, v int) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *IntArray) IteratorDesc(f func(k int, v int) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorDesc(f)
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
@ -769,80 +445,49 @@ func (a *IntArray) String() string {
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a IntArray) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
a.lazyInit()
|
||||
return a.TArray.MarshalJSON()
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
func (a *IntArray) UnmarshalJSON(b []byte) error {
|
||||
if a.array == nil {
|
||||
a.array = make([]int, 0)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
func (a *IntArray) UnmarshalValue(value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
return json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
a.array = gconv.SliceInt(value)
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalValue(value)
|
||||
}
|
||||
|
||||
// Filter iterates array and filters elements using custom callback function.
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *IntArray) Filter(filter func(index int, value int) bool) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Filter(filter)
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all zero value of the array.
|
||||
func (a *IntArray) FilterEmpty() *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if a.array[i] == 0 {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.FilterEmpty()
|
||||
return a
|
||||
}
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *IntArray) Walk(f func(value int) int) *IntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Walk(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *IntArray) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
a.lazyInit()
|
||||
return a.TArray.IsEmpty()
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
@ -850,9 +495,8 @@ func (a *IntArray) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]int, len(a.array))
|
||||
copy(newSlice, a.array)
|
||||
return NewIntArrayFrom(newSlice, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &IntArray{
|
||||
TArray: a.TArray.DeepCopy().(*TArray[int]),
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,25 +8,20 @@ package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
)
|
||||
|
||||
// StrArray is a golang string array with rich features.
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type StrArray struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []string
|
||||
*TArray[string]
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewStrArray creates and returns an empty array.
|
||||
@ -41,8 +36,7 @@ func NewStrArray(safe ...bool) *StrArray {
|
||||
// which is false in default.
|
||||
func NewStrArraySize(size int, cap int, safe ...bool) *StrArray {
|
||||
return &StrArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]string, size, cap),
|
||||
TArray: NewTArraySize[string](size, cap, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -51,8 +45,7 @@ func NewStrArraySize(size int, cap int, safe ...bool) *StrArray {
|
||||
// which is false in default.
|
||||
func NewStrArrayFrom(array []string, safe ...bool) *StrArray {
|
||||
return &StrArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: array,
|
||||
TArray: NewTArrayFrom(array, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,77 +55,64 @@ func NewStrArrayFrom(array []string, safe ...bool) *StrArray {
|
||||
func NewStrArrayFromCopy(array []string, safe ...bool) *StrArray {
|
||||
newArray := make([]string, len(array))
|
||||
copy(newArray, array)
|
||||
return &StrArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: newArray,
|
||||
}
|
||||
return NewStrArrayFrom(newArray, safe...)
|
||||
}
|
||||
|
||||
// lazyInit lazily initializes the array.
|
||||
func (a *StrArray) lazyInit() {
|
||||
a.once.Do(func() {
|
||||
if a.TArray == nil {
|
||||
a.TArray = NewTArray[string](false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns an empty string.
|
||||
func (a *StrArray) At(index int) (value string) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.At(index)
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *StrArray) Get(index int) (value string, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return "", false
|
||||
}
|
||||
return a.array[index], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Get(index)
|
||||
}
|
||||
|
||||
// Set sets value to specified index.
|
||||
func (a *StrArray) Set(index int, value string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
a.array[index] = value
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Set(index, value)
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *StrArray) SetArray(array []string) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
a.lazyInit()
|
||||
a.TArray.SetArray(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Replace replaces the array items by given `array` from the beginning of array.
|
||||
func (a *StrArray) Replace(array []string) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
max := len(array)
|
||||
if max > len(a.array) {
|
||||
max = len(a.array)
|
||||
}
|
||||
for i := 0; i < max; i++ {
|
||||
a.array[i] = array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Replace(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *StrArray) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += gconv.Int(v)
|
||||
}
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.TArray.Sum()
|
||||
}
|
||||
|
||||
// Sort sorts the array in increasing order.
|
||||
// The parameter `reverse` controls whether sort
|
||||
// in increasing order(default) or decreasing order
|
||||
func (a *StrArray) Sort(reverse ...bool) *StrArray {
|
||||
a.lazyInit()
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(reverse) > 0 && reverse[0] {
|
||||
@ -147,200 +127,101 @@ func (a *StrArray) Sort(reverse ...bool) *StrArray {
|
||||
|
||||
// SortFunc sorts the array by custom function `less`.
|
||||
func (a *StrArray) SortFunc(less func(v1, v2 string) bool) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return less(a.array[i], a.array[j])
|
||||
})
|
||||
a.lazyInit()
|
||||
a.TArray.SortFunc(less)
|
||||
return a
|
||||
}
|
||||
|
||||
// InsertBefore inserts the `values` to the front of `index`.
|
||||
func (a *StrArray) InsertBefore(index int, values ...string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]string{}, a.array[index:]...)
|
||||
a.array = append(a.array[0:index], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertBefore(index, values...)
|
||||
}
|
||||
|
||||
// InsertAfter inserts the `values` to the back of `index`.
|
||||
func (a *StrArray) InsertAfter(index int, values ...string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]string{}, a.array[index+1:]...)
|
||||
a.array = append(a.array[0:index+1], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.InsertAfter(index, values...)
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *StrArray) Remove(index int) (value string, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *StrArray) doRemoveWithoutLock(index int) (value string, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return "", false
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.Remove(index)
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *StrArray) RemoveValue(value string) bool {
|
||||
if i := a.Search(value); i != -1 {
|
||||
_, found := a.Remove(i)
|
||||
return found
|
||||
}
|
||||
return false
|
||||
a.lazyInit()
|
||||
return a.TArray.RemoveValue(value)
|
||||
}
|
||||
|
||||
// RemoveValues removes multiple items by `values`.
|
||||
func (a *StrArray) RemoveValues(values ...string) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.RemoveValues(values...)
|
||||
}
|
||||
|
||||
// PushLeft pushes one or multiple items to the beginning of array.
|
||||
func (a *StrArray) PushLeft(value ...string) *StrArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(value, a.array...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushLeft(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PushRight pushes one or multiple items to the end of array.
|
||||
// It equals to Append.
|
||||
func (a *StrArray) PushRight(value ...string) *StrArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.PushRight(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *StrArray) PopLeft() (value string, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return "", false
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLeft()
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *StrArray) PopRight() (value string, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
return "", false
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRight()
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *StrArray) PopRand() (value string, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRand()
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *StrArray) PopRands(size int) []string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]string, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRands(size)
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *StrArray) PopLefts(size int) []string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopLefts(size)
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *StrArray) PopRights(size int) []string {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.TArray.PopRights(size)
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
@ -351,26 +232,8 @@ func (a *StrArray) PopRights(size int) []string {
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *StrArray) Range(start int, end ...int) []string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]string)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]string, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Range(start, end...)
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
@ -387,111 +250,63 @@ func (a *StrArray) Range(start int, end ...int) []string {
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *StrArray) SubSlice(offset int, length ...int) []string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]string, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
}
|
||||
return a.array[offset:end]
|
||||
a.lazyInit()
|
||||
return a.TArray.SubSlice(offset, length...)
|
||||
}
|
||||
|
||||
// Append is alias of PushRight,please See PushRight.
|
||||
func (a *StrArray) Append(value ...string) *StrArray {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.Append(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *StrArray) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
a.lazyInit()
|
||||
return a.TArray.Len()
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *StrArray) Slice() []string {
|
||||
array := ([]string)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array = make([]string, len(a.array))
|
||||
copy(array, a.array)
|
||||
} else {
|
||||
array = a.array
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Slice()
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
func (a *StrArray) Interfaces() []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array := make([]any, len(a.array))
|
||||
for k, v := range a.array {
|
||||
array[k] = v
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Interfaces()
|
||||
}
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *StrArray) Clone() (newArray *StrArray) {
|
||||
a.mu.RLock()
|
||||
array := make([]string, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewStrArrayFrom(array, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &StrArray{
|
||||
TArray: a.TArray.Clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *StrArray) Clear() *StrArray {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]string, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.TArray.Clear()
|
||||
return a
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *StrArray) Contains(value string) bool {
|
||||
return a.Search(value) != -1
|
||||
a.lazyInit()
|
||||
return a.TArray.Contains(value)
|
||||
}
|
||||
|
||||
// ContainsI checks whether a value exists in the array with case-insensitively.
|
||||
// Note that it internally iterates the whole array to do the comparison with case-insensitively.
|
||||
func (a *StrArray) ContainsI(value string) bool {
|
||||
a.lazyInit()
|
||||
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
@ -508,64 +323,29 @@ func (a *StrArray) ContainsI(value string) bool {
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *StrArray) Search(value string) int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return a.doSearchWithoutLock(value)
|
||||
}
|
||||
|
||||
func (a *StrArray) doSearchWithoutLock(value string) int {
|
||||
if len(a.array) == 0 {
|
||||
return -1
|
||||
}
|
||||
result := -1
|
||||
for index, v := range a.array {
|
||||
if strings.Compare(v, value) == 0 {
|
||||
result = index
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
a.lazyInit()
|
||||
return a.TArray.Search(value)
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
// Example: [1,1,2,3,2] -> [1,2,3]
|
||||
func (a *StrArray) Unique() *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
var (
|
||||
ok bool
|
||||
temp string
|
||||
uniqueSet = make(map[string]struct{})
|
||||
uniqueArray = make([]string, 0, len(a.array))
|
||||
)
|
||||
for i := 0; i < len(a.array); i++ {
|
||||
temp = a.array[i]
|
||||
if _, ok = uniqueSet[temp]; ok {
|
||||
continue
|
||||
}
|
||||
uniqueSet[temp] = struct{}{}
|
||||
uniqueArray = append(uniqueArray, temp)
|
||||
}
|
||||
a.array = uniqueArray
|
||||
a.lazyInit()
|
||||
a.TArray.Unique()
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *StrArray) LockFunc(f func(array []string)) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.LockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *StrArray) RLockFunc(f func(array []string)) *StrArray {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.TArray.RLockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -580,42 +360,16 @@ func (a *StrArray) Merge(array any) *StrArray {
|
||||
// Fill fills an array with num entries of the value `value`,
|
||||
// keys starting at the `startIndex` parameter.
|
||||
func (a *StrArray) Fill(startIndex int, num int, value string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if startIndex < 0 || startIndex > len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||
}
|
||||
for i := startIndex; i < startIndex+num; i++ {
|
||||
if i > len(a.array)-1 {
|
||||
a.array = append(a.array, value)
|
||||
} else {
|
||||
a.array[i] = value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.Fill(startIndex, num, value)
|
||||
}
|
||||
|
||||
// Chunk splits an array into multiple arrays,
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *StrArray) Chunk(size int) [][]string {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]string
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
a.lazyInit()
|
||||
return a.TArray.Chunk(size)
|
||||
}
|
||||
|
||||
// Pad pads array to the specified length with `value`.
|
||||
@ -623,98 +377,47 @@ func (a *StrArray) Chunk(size int) [][]string {
|
||||
// If the absolute value of `size` is less than or equal to the length of the array
|
||||
// then no padding takes place.
|
||||
func (a *StrArray) Pad(size int, value string) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
|
||||
return a
|
||||
}
|
||||
n := size
|
||||
if size < 0 {
|
||||
n = -size
|
||||
}
|
||||
n -= len(a.array)
|
||||
tmp := make([]string, n)
|
||||
for i := 0; i < n; i++ {
|
||||
tmp[i] = value
|
||||
}
|
||||
if size > 0 {
|
||||
a.array = append(a.array, tmp...)
|
||||
} else {
|
||||
a.array = append(tmp, a.array...)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Pad(size, value)
|
||||
return a
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *StrArray) Rand() (value string, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return "", false
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
a.lazyInit()
|
||||
return a.TArray.Rand()
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *StrArray) Rands(size int) []string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]string, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.TArray.Rands(size)
|
||||
}
|
||||
|
||||
// Shuffle randomly shuffles the array.
|
||||
func (a *StrArray) Shuffle() *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range grand.Perm(len(a.array)) {
|
||||
a.array[i], a.array[v] = a.array[v], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Shuffle()
|
||||
return a
|
||||
}
|
||||
|
||||
// Reverse makes array with elements in reverse order.
|
||||
func (a *StrArray) Reverse() *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, j := 0, len(a.array)-1; i < j; i, j = i+1, j-1 {
|
||||
a.array[i], a.array[j] = a.array[j], a.array[i]
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Reverse()
|
||||
return a
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *StrArray) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(v)
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.TArray.Join(glue)
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *StrArray) CountValues() map[string]int {
|
||||
m := make(map[string]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
a.lazyInit()
|
||||
return a.TArray.CountValues()
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
@ -725,25 +428,15 @@ func (a *StrArray) Iterator(f func(k int, v string) bool) {
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *StrArray) IteratorAsc(f func(k int, v string) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *StrArray) IteratorDesc(f func(k int, v string) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.IteratorDesc(f)
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
@ -751,6 +444,9 @@ func (a *StrArray) String() string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
a.lazyInit()
|
||||
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
@ -768,80 +464,49 @@ func (a *StrArray) String() string {
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a StrArray) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
a.lazyInit()
|
||||
return a.TArray.MarshalJSON()
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
func (a *StrArray) UnmarshalJSON(b []byte) error {
|
||||
if a.array == nil {
|
||||
a.array = make([]string, 0)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
func (a *StrArray) UnmarshalValue(value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
return json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
a.array = gconv.SliceStr(value)
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.TArray.UnmarshalValue(value)
|
||||
}
|
||||
|
||||
// Filter iterates array and filters elements using custom callback function.
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *StrArray) Filter(filter func(index int, value string) bool) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Filter(filter)
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all empty string value of the array.
|
||||
func (a *StrArray) FilterEmpty() *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if a.array[i] == "" {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.FilterEmpty()
|
||||
return a
|
||||
}
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *StrArray) Walk(f func(value string) string) *StrArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.TArray.Walk(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *StrArray) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
a.lazyInit()
|
||||
return a.TArray.IsEmpty()
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
@ -849,9 +514,8 @@ func (a *StrArray) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]string, len(a.array))
|
||||
copy(newSlice, a.array)
|
||||
return NewStrArrayFrom(newSlice, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &StrArray{
|
||||
TArray: a.TArray.DeepCopy().(*TArray[string]),
|
||||
}
|
||||
}
|
||||
|
||||
859
container/garray/garray_normal_t.go
Normal file
859
container/garray/garray_normal_t.go
Normal file
@ -0,0 +1,859 @@
|
||||
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
||||
//
|
||||
// This Source Code Form is subject to the terms of the MIT License.
|
||||
// If a copy of the MIT was not distributed with this file,
|
||||
// You can obtain one at https://github.com/gogf/gf.
|
||||
|
||||
package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
"sort"
|
||||
|
||||
"github.com/gogf/gf/v2/errors/gcode"
|
||||
"github.com/gogf/gf/v2/errors/gerror"
|
||||
"github.com/gogf/gf/v2/internal/deepcopy"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
)
|
||||
|
||||
// TArray is a golang array with rich features.
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type TArray[T comparable] struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []T
|
||||
}
|
||||
|
||||
// NewTArray creates and returns an empty array.
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewTArray[T comparable](safe ...bool) *TArray[T] {
|
||||
return NewTArraySize[T](0, 0, safe...)
|
||||
}
|
||||
|
||||
// NewTArraySize create and returns an array with given size and cap.
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewTArraySize[T comparable](size int, cap int, safe ...bool) *TArray[T] {
|
||||
return &TArray[T]{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]T, size, cap),
|
||||
}
|
||||
}
|
||||
|
||||
// NewTArrayFrom creates and returns an array with given slice `array`.
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewTArrayFrom[T comparable](array []T, safe ...bool) *TArray[T] {
|
||||
return &TArray[T]{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: array,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTArrayFromCopy creates and returns an array from a copy of given slice `array`.
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewTArrayFromCopy[T comparable](array []T, safe ...bool) *TArray[T] {
|
||||
newArray := make([]T, len(array))
|
||||
copy(newArray, array)
|
||||
return &TArray[T]{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: newArray,
|
||||
}
|
||||
}
|
||||
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns `nil`.
|
||||
func (a *TArray[T]) At(index int) (value T) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *TArray[T]) Get(index int) (value T, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
found = false
|
||||
return
|
||||
}
|
||||
return a.array[index], true
|
||||
}
|
||||
|
||||
// Set sets value to specified index.
|
||||
func (a *TArray[T]) Set(index int, value T) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
a.array[index] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *TArray[T]) SetArray(array []T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
return a
|
||||
}
|
||||
|
||||
// Replace replaces the array items by given `array` from the beginning of array.
|
||||
func (a *TArray[T]) Replace(array []T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
max := len(array)
|
||||
if max > len(a.array) {
|
||||
max = len(a.array)
|
||||
}
|
||||
for i := 0; i < max; i++ {
|
||||
a.array[i] = array[i]
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *TArray[T]) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += gconv.Int(v)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// SortFunc sorts the array by custom function `less`.
|
||||
func (a *TArray[T]) SortFunc(less func(v1, v2 T) bool) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return less(a.array[i], a.array[j])
|
||||
})
|
||||
return a
|
||||
}
|
||||
|
||||
// InsertBefore inserts the `values` to the front of `index`.
|
||||
func (a *TArray[T]) InsertBefore(index int, values ...T) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]T{}, a.array[index:]...)
|
||||
a.array = append(a.array[0:index], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertAfter inserts the `values` to the back of `index`.
|
||||
func (a *TArray[T]) InsertAfter(index int, values ...T) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", index, len(a.array))
|
||||
}
|
||||
rear := append([]T{}, a.array[index+1:]...)
|
||||
a.array = append(a.array[0:index+1], values...)
|
||||
a.array = append(a.array, rear...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *TArray[T]) Remove(index int) (value T, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *TArray[T]) doRemoveWithoutLock(index int) (value T, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
found = false
|
||||
return
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *TArray[T]) RemoveValue(value T) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RemoveValues removes multiple items by `values`.
|
||||
func (a *TArray[T]) RemoveValues(values ...T) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i := a.doSearchWithoutLock(value); i != -1 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PushLeft pushes one or multiple items to the beginning of array.
|
||||
func (a *TArray[T]) PushLeft(value ...T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
a.array = append(value, a.array...)
|
||||
a.mu.Unlock()
|
||||
return a
|
||||
}
|
||||
|
||||
// PushRight pushes one or multiple items to the end of array.
|
||||
// It equals to Append.
|
||||
func (a *TArray[T]) PushRight(value ...T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
a.array = append(a.array, value...)
|
||||
a.mu.Unlock()
|
||||
return a
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *TArray[T]) PopRand() (value T, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
func (a *TArray[T]) PopRands(size int) []T {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]T, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *TArray[T]) PopLeft() (value T, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
found = false
|
||||
return
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *TArray[T]) PopRight() (value T, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
found = false
|
||||
return
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
func (a *TArray[T]) PopLefts(size int) []T {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
func (a *TArray[T]) PopRights(size int) []T {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
// Notice, if in concurrent-safe usage, it returns a copy of slice;
|
||||
// else a pointer to the underlying data.
|
||||
//
|
||||
// If `end` is negative, then the offset will start from the end of array.
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *TArray[T]) Range(start int, end ...int) []T {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]T)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]T, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
// by the `offset` and `size` parameters.
|
||||
// If in concurrent safe usage, it returns a copy of the slice; else a pointer.
|
||||
//
|
||||
// If offset is non-negative, the sequence will start at that offset in the array.
|
||||
// If offset is negative, the sequence will start that far from the end of the array.
|
||||
//
|
||||
// If length is given and is positive, then the sequence will have up to that many elements in it.
|
||||
// If the array is shorter than the length, then only the available array elements will be present.
|
||||
// If length is given and is negative then the sequence will stop that many elements from the end of the array.
|
||||
// If it is omitted, then the sequence will have everything from offset up until the end of the array.
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *TArray[T]) SubSlice(offset int, length ...int) []T {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]T, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
} else {
|
||||
return a.array[offset:end]
|
||||
}
|
||||
}
|
||||
|
||||
// Append is alias of PushRight, please See PushRight.
|
||||
func (a *TArray[T]) Append(value ...T) *TArray[T] {
|
||||
a.PushRight(value...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *TArray[T]) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *TArray[T]) Slice() []T {
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array := make([]T, len(a.array))
|
||||
copy(array, a.array)
|
||||
return array
|
||||
} else {
|
||||
return a.array
|
||||
}
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
func (a *TArray[T]) Interfaces() []any {
|
||||
return tToAnySlice(a.Slice())
|
||||
}
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *TArray[T]) Clone() (newArray *TArray[T]) {
|
||||
a.mu.RLock()
|
||||
array := make([]T, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewTArrayFrom(array, a.mu.IsSafe())
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *TArray[T]) Clear() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]T, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
return a
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *TArray[T]) Contains(value T) bool {
|
||||
return a.Search(value) != -1
|
||||
}
|
||||
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *TArray[T]) Search(value T) int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return a.doSearchWithoutLock(value)
|
||||
}
|
||||
|
||||
func (a *TArray[T]) doSearchWithoutLock(value T) int {
|
||||
if len(a.array) == 0 {
|
||||
return -1
|
||||
}
|
||||
result := -1
|
||||
for index, v := range a.array {
|
||||
if v == value {
|
||||
result = index
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
// Example: [1,1,2,3,2] -> [1,2,3]
|
||||
func (a *TArray[T]) Unique() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
var (
|
||||
ok bool
|
||||
temp T
|
||||
uniqueSet = make(map[T]struct{})
|
||||
uniqueArray = make([]T, 0, len(a.array))
|
||||
)
|
||||
for i := 0; i < len(a.array); i++ {
|
||||
temp = a.array[i]
|
||||
if _, ok = uniqueSet[temp]; ok {
|
||||
continue
|
||||
}
|
||||
uniqueSet[temp] = struct{}{}
|
||||
uniqueArray = append(uniqueArray, temp)
|
||||
}
|
||||
a.array = uniqueArray
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *TArray[T]) LockFunc(f func(array []T)) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
f(a.array)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *TArray[T]) RLockFunc(f func(array []T)) *TArray[T] {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
return a
|
||||
}
|
||||
|
||||
// Merge merges `array` into current array.
|
||||
// The parameter `array` can be any garray or slice type.
|
||||
// The difference between Merge and Append is Append supports only specified slice type,
|
||||
// but Merge supports more parameter types.
|
||||
func (a *TArray[T]) Merge(array any) *TArray[T] {
|
||||
var vals []T
|
||||
switch v := array.(type) {
|
||||
case *SortedTArray[T]:
|
||||
vals = v.Slice()
|
||||
case *TArray[T]:
|
||||
vals = v.Slice()
|
||||
case []T:
|
||||
vals = v
|
||||
default:
|
||||
interfaces := gconv.Interfaces(v)
|
||||
if err := gconv.Scan(interfaces, &vals); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
return a.Append(vals...)
|
||||
}
|
||||
|
||||
// Fill fills an array with num entries of the value `value`,
|
||||
// keys starting at the `startIndex` parameter.
|
||||
func (a *TArray[T]) Fill(startIndex int, num int, value T) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if startIndex < 0 || startIndex > len(a.array) {
|
||||
return gerror.NewCodef(gcode.CodeInvalidParameter, "index %d out of array range %d", startIndex, len(a.array))
|
||||
}
|
||||
for i := startIndex; i < startIndex+num; i++ {
|
||||
if i > len(a.array)-1 {
|
||||
a.array = append(a.array, value)
|
||||
} else {
|
||||
a.array[i] = value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Chunk splits an array into multiple arrays,
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *TArray[T]) Chunk(size int) [][]T {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]T
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Pad pads array to the specified length with `value`.
|
||||
// If size is positive then the array is padded on the right, or negative on the left.
|
||||
// If the absolute value of `size` is less than or equal to the length of the array
|
||||
// then no padding takes place.
|
||||
func (a *TArray[T]) Pad(size int, val T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
|
||||
return a
|
||||
}
|
||||
n := size
|
||||
if size < 0 {
|
||||
n = -size
|
||||
}
|
||||
n -= len(a.array)
|
||||
tmp := make([]T, n)
|
||||
for i := 0; i < n; i++ {
|
||||
tmp[i] = val
|
||||
}
|
||||
if size > 0 {
|
||||
a.array = append(a.array, tmp...)
|
||||
} else {
|
||||
a.array = append(tmp, a.array...)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *TArray[T]) Rand() (value T, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
found = false
|
||||
return
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *TArray[T]) Rands(size int) []T {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]T, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
}
|
||||
|
||||
// Shuffle randomly shuffles the array.
|
||||
func (a *TArray[T]) Shuffle() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range grand.Perm(len(a.array)) {
|
||||
a.array[i], a.array[v] = a.array[v], a.array[i]
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Reverse makes array with elements in reverse order.
|
||||
func (a *TArray[T]) Reverse() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, j := 0, len(a.array)-1; i < j; i, j = i+1, j-1 {
|
||||
a.array[i], a.array[j] = a.array[j], a.array[i]
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *TArray[T]) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(gconv.String(v))
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *TArray[T]) CountValues() map[T]int {
|
||||
m := make(map[T]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
func (a *TArray[T]) Iterator(f func(k int, v T) bool) {
|
||||
a.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *TArray[T]) IteratorAsc(f func(k int, v T) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *TArray[T]) IteratorDesc(f func(k int, v T) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
func (a *TArray[T]) String() string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteByte('[')
|
||||
s := ""
|
||||
for k, v := range a.array {
|
||||
s = gconv.String(v)
|
||||
if gstr.IsNumeric(s) {
|
||||
buffer.WriteString(s)
|
||||
} else {
|
||||
buffer.WriteString(`"` + gstr.QuoteMeta(s, `"\`) + `"`)
|
||||
}
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteByte(',')
|
||||
}
|
||||
}
|
||||
buffer.WriteByte(']')
|
||||
return buffer.String()
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a TArray[T]) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
func (a *TArray[T]) UnmarshalJSON(b []byte) error {
|
||||
if a.array == nil {
|
||||
a.array = make([]T, 0)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
func (a *TArray[T]) UnmarshalValue(value any) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
return json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
if err := gconv.Scan(gconv.SliceAny(value), &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Filter iterates array and filters elements using custom callback function.
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *TArray[T]) Filter(filter func(index int, value T) bool) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterNil removes all nil value of the array.
|
||||
func (a *TArray[T]) FilterNil() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsNil(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all empty value of the array.
|
||||
// Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.
|
||||
func (a *TArray[T]) FilterEmpty() *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsEmpty(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *TArray[T]) Walk(f func(value T) T) *TArray[T] {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *TArray[T]) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
func (a *TArray[T]) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]T, len(a.array))
|
||||
for i, v := range a.array {
|
||||
newSlice[i] = deepcopy.Copy(v).(T)
|
||||
}
|
||||
return NewTArrayFrom(newSlice, a.mu.IsSafe())
|
||||
}
|
||||
@ -7,19 +7,11 @@
|
||||
package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/internal/deepcopy"
|
||||
"github.com/gogf/gf/v2/internal/empty"
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/text/gstr"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
"github.com/gogf/gf/v2/util/gutil"
|
||||
)
|
||||
|
||||
// SortedArray is a golang sorted array with rich features.
|
||||
@ -28,10 +20,17 @@ import (
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type SortedArray struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []any
|
||||
unique bool // Whether enable unique feature(false)
|
||||
comparator func(a, b any) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b)
|
||||
*SortedTArray[any]
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// lazyInit lazily initializes the array.
|
||||
func (a *SortedArray) lazyInit() {
|
||||
a.once.Do(func() {
|
||||
if a.SortedTArray == nil {
|
||||
a.SortedTArray = NewSortedTArraySize[any](0, nil, false)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// NewSortedArray creates and returns an empty sorted array.
|
||||
@ -49,9 +48,7 @@ func NewSortedArray(comparator func(a, b any) int, safe ...bool) *SortedArray {
|
||||
// which is false in default.
|
||||
func NewSortedArraySize(cap int, comparator func(a, b any) int, safe ...bool) *SortedArray {
|
||||
return &SortedArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]any, 0, cap),
|
||||
comparator: comparator,
|
||||
SortedTArray: NewSortedTArraySize(cap, comparator, safe...),
|
||||
}
|
||||
}
|
||||
|
||||
@ -94,224 +91,111 @@ func NewSortedArrayFromCopy(array []any, comparator func(a, b any) int, safe ...
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns `nil`.
|
||||
func (a *SortedArray) At(index int) (value any) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.At(index)
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *SortedArray) SetArray(array []any) *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.getComparator()(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
a.lazyInit()
|
||||
a.SortedTArray.SetArray(array)
|
||||
return a
|
||||
}
|
||||
|
||||
// SetComparator sets/changes the comparator for sorting.
|
||||
// It resorts the array as the comparator is changed.
|
||||
func (a *SortedArray) SetComparator(comparator func(a, b any) int) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.comparator = comparator
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.getComparator()(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
a.lazyInit()
|
||||
a.SortedTArray.SetComparator(comparator)
|
||||
}
|
||||
|
||||
// Sort sorts the array in increasing order.
|
||||
// The parameter `reverse` controls whether sort
|
||||
// in increasing order(default) or decreasing order
|
||||
func (a *SortedArray) Sort() *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.getComparator()(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Sort()
|
||||
return a
|
||||
}
|
||||
|
||||
// Add adds one or multiple values to sorted array, the array always keeps sorted.
|
||||
// It's alias of function Append, see Append.
|
||||
func (a *SortedArray) Add(values ...any) *SortedArray {
|
||||
return a.Append(values...)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Add(values...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Append adds one or multiple values to sorted array, the array always keeps sorted.
|
||||
func (a *SortedArray) Append(values ...any) *SortedArray {
|
||||
if len(values) == 0 {
|
||||
return a
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
index, cmp := a.binSearch(value, false)
|
||||
if a.unique && cmp == 0 {
|
||||
continue
|
||||
}
|
||||
if index < 0 {
|
||||
a.array = append(a.array, value)
|
||||
continue
|
||||
}
|
||||
if cmp > 0 {
|
||||
index++
|
||||
}
|
||||
a.array = append(a.array[:index], append([]any{value}, a.array[index:]...)...)
|
||||
}
|
||||
a.SortedTArray.Append(values...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *SortedArray) Get(index int) (value any, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return nil, false
|
||||
}
|
||||
return a.array[index], true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Get(index)
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *SortedArray) Remove(index int) (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *SortedArray) doRemoveWithoutLock(index int) (value any, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return nil, false
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Remove(index)
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *SortedArray) RemoveValue(value any) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if i, r := a.binSearch(value, false); r == 0 {
|
||||
_, res := a.doRemoveWithoutLock(i)
|
||||
return res
|
||||
}
|
||||
return false
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.RemoveValue(value)
|
||||
}
|
||||
|
||||
// RemoveValues removes an item by `values`.
|
||||
func (a *SortedArray) RemoveValues(values ...any) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i, r := a.binSearch(value, false); r == 0 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.RemoveValues(values...)
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedArray) PopLeft() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopLeft()
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedArray) PopRight() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
return nil, false
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRight()
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedArray) PopRand() (value any, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRand()
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
func (a *SortedArray) PopRands(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]any, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRands(size)
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
func (a *SortedArray) PopLefts(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopLefts(size)
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
func (a *SortedArray) PopRights(size int) []any {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRights(size)
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
@ -322,26 +206,7 @@ func (a *SortedArray) PopRights(size int) []any {
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *SortedArray) Range(start int, end ...int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]any)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]any, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
return a.SortedTArray.Range(start, end...)
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
@ -358,194 +223,91 @@ func (a *SortedArray) Range(start int, end ...int) []any {
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *SortedArray) SubSlice(offset int, length ...int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]any, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
} else {
|
||||
return a.array[offset:end]
|
||||
}
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.SubSlice(offset, length...)
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *SortedArray) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += gconv.Int(v)
|
||||
}
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Sum()
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *SortedArray) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Len()
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *SortedArray) Slice() []any {
|
||||
var array []any
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array = make([]any, len(a.array))
|
||||
copy(array, a.array)
|
||||
} else {
|
||||
array = a.array
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Slice()
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
func (a *SortedArray) Interfaces() []any {
|
||||
return a.Slice()
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Interfaces()
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *SortedArray) Contains(value any) bool {
|
||||
return a.Search(value) != -1
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Contains(value)
|
||||
}
|
||||
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *SortedArray) Search(value any) (index int) {
|
||||
if i, r := a.binSearch(value, true); r == 0 {
|
||||
return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Binary search.
|
||||
// It returns the last compared index and the result.
|
||||
// If `result` equals to 0, it means the value at `index` is equals to `value`.
|
||||
// If `result` lesser than 0, it means the value at `index` is lesser than `value`.
|
||||
// If `result` greater than 0, it means the value at `index` is greater than `value`.
|
||||
func (a *SortedArray) binSearch(value any, lock bool) (index int, result int) {
|
||||
if lock {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
}
|
||||
if len(a.array) == 0 {
|
||||
return -1, -2
|
||||
}
|
||||
min := 0
|
||||
max := len(a.array) - 1
|
||||
mid := 0
|
||||
cmp := -2
|
||||
for min <= max {
|
||||
mid = min + (max-min)/2
|
||||
cmp = a.getComparator()(value, a.array[mid])
|
||||
switch {
|
||||
case cmp < 0:
|
||||
max = mid - 1
|
||||
case cmp > 0:
|
||||
min = mid + 1
|
||||
default:
|
||||
return mid, cmp
|
||||
}
|
||||
}
|
||||
return mid, cmp
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Search(value)
|
||||
}
|
||||
|
||||
// SetUnique sets unique mark to the array,
|
||||
// which means it does not contain any repeated items.
|
||||
// It also does unique check, remove all repeated items.
|
||||
func (a *SortedArray) SetUnique(unique bool) *SortedArray {
|
||||
oldUnique := a.unique
|
||||
a.unique = unique
|
||||
if unique && oldUnique != unique {
|
||||
a.Unique()
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.SetUnique(unique)
|
||||
return a
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
func (a *SortedArray) Unique() *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
for i := 0; i < len(a.array)-1; {
|
||||
if a.getComparator()(a.array[i], a.array[i+1]) == 0 {
|
||||
a.array = append(a.array[:i+1], a.array[i+2:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Unique()
|
||||
return a
|
||||
}
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *SortedArray) Clone() (newArray *SortedArray) {
|
||||
a.mu.RLock()
|
||||
array := make([]any, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewSortedArrayFrom(array, a.comparator, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &SortedArray{
|
||||
SortedTArray: a.SortedTArray.Clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *SortedArray) Clear() *SortedArray {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]any, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Clear()
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *SortedArray) LockFunc(f func(array []any)) *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
// Keep the array always sorted.
|
||||
defer sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.getComparator()(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.LockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *SortedArray) RLockFunc(f func(array []any)) *SortedArray {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.RLockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -561,104 +323,52 @@ func (a *SortedArray) Merge(array any) *SortedArray {
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *SortedArray) Chunk(size int) [][]any {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]any
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Chunk(size)
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *SortedArray) Rand() (value any, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Rand()
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *SortedArray) Rands(size int) []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]any, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Rands(size)
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *SortedArray) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(gconv.String(v))
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Join(glue)
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *SortedArray) CountValues() map[any]int {
|
||||
m := make(map[any]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.CountValues()
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
func (a *SortedArray) Iterator(f func(k int, v any) bool) {
|
||||
a.IteratorAsc(f)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Iterator(f)
|
||||
}
|
||||
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *SortedArray) IteratorAsc(f func(k int, v any) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *SortedArray) IteratorDesc(f func(k int, v any) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.IteratorDesc(f)
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
@ -666,94 +376,35 @@ func (a *SortedArray) String() string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
buffer.WriteByte('[')
|
||||
s := ""
|
||||
for k, v := range a.array {
|
||||
s = gconv.String(v)
|
||||
if gstr.IsNumeric(s) {
|
||||
buffer.WriteString(s)
|
||||
} else {
|
||||
buffer.WriteString(`"` + gstr.QuoteMeta(s, `"\`) + `"`)
|
||||
}
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteByte(',')
|
||||
}
|
||||
}
|
||||
buffer.WriteByte(']')
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.String()
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a SortedArray) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.MarshalJSON()
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
// Note that the comparator is set as string comparator in default.
|
||||
func (a *SortedArray) UnmarshalJSON(b []byte) error {
|
||||
if a.comparator == nil {
|
||||
a.array = make([]any, 0)
|
||||
a.comparator = gutil.ComparatorString
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.comparator != nil && a.array != nil {
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.comparator(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
}
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
// Note that the comparator is set as string comparator in default.
|
||||
func (a *SortedArray) UnmarshalValue(value any) (err error) {
|
||||
if a.comparator == nil {
|
||||
a.comparator = gutil.ComparatorString
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
err = json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
a.array = gconv.SliceAny(value)
|
||||
}
|
||||
if a.comparator != nil && a.array != nil {
|
||||
sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.comparator(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
}
|
||||
return err
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.UnmarshalValue(value)
|
||||
}
|
||||
|
||||
// FilterNil removes all nil value of the array.
|
||||
func (a *SortedArray) FilterNil() *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsNil(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := len(a.array) - 1; i >= 0; {
|
||||
if empty.IsNil(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.FilterNil()
|
||||
return a
|
||||
}
|
||||
|
||||
@ -761,78 +412,36 @@ func (a *SortedArray) FilterNil() *SortedArray {
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *SortedArray) Filter(filter func(index int, value any) bool) *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Filter(filter)
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all empty value of the array.
|
||||
// Values like: 0, nil, false, "", len(slice/map/chan) == 0 are considered empty.
|
||||
func (a *SortedArray) FilterEmpty() *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if empty.IsEmpty(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := len(a.array) - 1; i >= 0; {
|
||||
if empty.IsEmpty(a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.FilterEmpty()
|
||||
return a
|
||||
}
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *SortedArray) Walk(f func(value any) any) *SortedArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
// Keep the array always sorted.
|
||||
defer sort.Slice(a.array, func(i, j int) bool {
|
||||
return a.getComparator()(a.array[i], a.array[j]) < 0
|
||||
})
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Walk(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *SortedArray) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
}
|
||||
|
||||
// getComparator returns the comparator if it's previously set,
|
||||
// or else it panics.
|
||||
func (a *SortedArray) getComparator() func(a, b any) int {
|
||||
if a.comparator == nil {
|
||||
panic("comparator is missing for sorted array")
|
||||
}
|
||||
return a.comparator
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.IsEmpty()
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
func (a *SortedArray) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return &SortedArray{
|
||||
SortedTArray: a.SortedTArray.DeepCopy().(*SortedTArray[any]),
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]any, len(a.array))
|
||||
for i, v := range a.array {
|
||||
newSlice[i] = deepcopy.Copy(v)
|
||||
}
|
||||
return NewSortedArrayFrom(newSlice, a.comparator, a.mu.IsSafe())
|
||||
}
|
||||
|
||||
@ -7,15 +7,10 @@
|
||||
package garray
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/gogf/gf/v2/internal/json"
|
||||
"github.com/gogf/gf/v2/internal/rwmutex"
|
||||
"github.com/gogf/gf/v2/util/gconv"
|
||||
"github.com/gogf/gf/v2/util/grand"
|
||||
)
|
||||
|
||||
// SortedIntArray is a golang sorted int array with rich features.
|
||||
@ -24,10 +19,18 @@ import (
|
||||
// It contains a concurrent-safe/unsafe switch, which should be set
|
||||
// when its initialization and cannot be changed then.
|
||||
type SortedIntArray struct {
|
||||
mu rwmutex.RWMutex
|
||||
array []int
|
||||
unique bool // Whether enable unique feature(false)
|
||||
comparator func(a, b int) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b)
|
||||
*SortedTArray[int]
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// lazyInit lazily initializes the array.
|
||||
func (a *SortedIntArray) lazyInit() {
|
||||
a.once.Do(func() {
|
||||
if a.SortedTArray == nil {
|
||||
a.SortedTArray = NewSortedTArraySize(0, defaultComparatorInt, false)
|
||||
a.SetSorter(quickSortInt)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// NewSortedIntArray creates and returns an empty sorted array.
|
||||
@ -49,10 +52,10 @@ func NewSortedIntArrayComparator(comparator func(a, b int) int, safe ...bool) *S
|
||||
// The parameter `safe` is used to specify whether using array in concurrent-safety,
|
||||
// which is false in default.
|
||||
func NewSortedIntArraySize(cap int, safe ...bool) *SortedIntArray {
|
||||
a := NewSortedTArraySize(cap, defaultComparatorInt, safe...)
|
||||
a.SetSorter(quickSortInt)
|
||||
return &SortedIntArray{
|
||||
mu: rwmutex.Create(safe...),
|
||||
array: make([]int, 0, cap),
|
||||
comparator: defaultComparatorInt,
|
||||
SortedTArray: a,
|
||||
}
|
||||
}
|
||||
|
||||
@ -77,7 +80,7 @@ func NewSortedIntArrayRange(start, end, step int, safe ...bool) *SortedIntArray
|
||||
func NewSortedIntArrayFrom(array []int, safe ...bool) *SortedIntArray {
|
||||
a := NewSortedIntArraySize(0, safe...)
|
||||
a.array = array
|
||||
sort.Ints(a.array)
|
||||
a.sorter(a.array, defaultComparatorInt)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -93,16 +96,14 @@ func NewSortedIntArrayFromCopy(array []int, safe ...bool) *SortedIntArray {
|
||||
// At returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, it returns `0`.
|
||||
func (a *SortedIntArray) At(index int) (value int) {
|
||||
value, _ = a.Get(index)
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.At(index)
|
||||
}
|
||||
|
||||
// SetArray sets the underlying slice array with the given `array`.
|
||||
func (a *SortedIntArray) SetArray(array []int) *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.array = array
|
||||
quickSortInt(a.array, a.getComparator())
|
||||
a.lazyInit()
|
||||
a.SortedTArray.SetArray(array)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -110,200 +111,95 @@ func (a *SortedIntArray) SetArray(array []int) *SortedIntArray {
|
||||
// The parameter `reverse` controls whether sort
|
||||
// in increasing order(default) or decreasing order.
|
||||
func (a *SortedIntArray) Sort() *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
quickSortInt(a.array, a.getComparator())
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Sort()
|
||||
return a
|
||||
}
|
||||
|
||||
// Add adds one or multiple values to sorted array, the array always keeps sorted.
|
||||
// It's alias of function Append, see Append.
|
||||
func (a *SortedIntArray) Add(values ...int) *SortedIntArray {
|
||||
a.lazyInit()
|
||||
return a.Append(values...)
|
||||
}
|
||||
|
||||
// Append adds one or multiple values to sorted array, the array always keeps sorted.
|
||||
func (a *SortedIntArray) Append(values ...int) *SortedIntArray {
|
||||
if len(values) == 0 {
|
||||
return a
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
index, cmp := a.binSearch(value, false)
|
||||
if a.unique && cmp == 0 {
|
||||
continue
|
||||
}
|
||||
if index < 0 {
|
||||
a.array = append(a.array, value)
|
||||
continue
|
||||
}
|
||||
if cmp > 0 {
|
||||
index++
|
||||
}
|
||||
rear := append([]int{}, a.array[index:]...)
|
||||
a.array = append(a.array[0:index], value)
|
||||
a.array = append(a.array, rear...)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Append(values...)
|
||||
return a
|
||||
}
|
||||
|
||||
// Get returns the value by the specified index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *SortedIntArray) Get(index int) (value int, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return 0, false
|
||||
}
|
||||
return a.array[index], true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Get(index)
|
||||
}
|
||||
|
||||
// Remove removes an item by index.
|
||||
// If the given `index` is out of range of the array, the `found` is false.
|
||||
func (a *SortedIntArray) Remove(index int) (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(index)
|
||||
}
|
||||
|
||||
// doRemoveWithoutLock removes an item by index without lock.
|
||||
func (a *SortedIntArray) doRemoveWithoutLock(index int) (value int, found bool) {
|
||||
if index < 0 || index >= len(a.array) {
|
||||
return 0, false
|
||||
}
|
||||
// Determine array boundaries when deleting to improve deletion efficiency.
|
||||
if index == 0 {
|
||||
value := a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
} else if index == len(a.array)-1 {
|
||||
value := a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
}
|
||||
// If it is a non-boundary delete,
|
||||
// it will involve the creation of an array,
|
||||
// then the deletion is less efficient.
|
||||
value = a.array[index]
|
||||
a.array = append(a.array[:index], a.array[index+1:]...)
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Remove(index)
|
||||
}
|
||||
|
||||
// RemoveValue removes an item by value.
|
||||
// It returns true if value is found in the array, or else false if not found.
|
||||
func (a *SortedIntArray) RemoveValue(value int) bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if i, r := a.binSearch(value, false); r == 0 {
|
||||
_, res := a.doRemoveWithoutLock(i)
|
||||
return res
|
||||
}
|
||||
return false
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.RemoveValue(value)
|
||||
}
|
||||
|
||||
// RemoveValues removes an item by `values`.
|
||||
func (a *SortedIntArray) RemoveValues(values ...int) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for _, value := range values {
|
||||
if i, r := a.binSearch(value, false); r == 0 {
|
||||
a.doRemoveWithoutLock(i)
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.RemoveValues(values...)
|
||||
}
|
||||
|
||||
// PopLeft pops and returns an item from the beginning of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedIntArray) PopLeft() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
value = a.array[0]
|
||||
a.array = a.array[1:]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopLeft()
|
||||
}
|
||||
|
||||
// PopRight pops and returns an item from the end of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedIntArray) PopRight() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
index := len(a.array) - 1
|
||||
if index < 0 {
|
||||
return 0, false
|
||||
}
|
||||
value = a.array[index]
|
||||
a.array = a.array[:index]
|
||||
return value, true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRight()
|
||||
}
|
||||
|
||||
// PopRand randomly pops and return an item out of array.
|
||||
// Note that if the array is empty, the `found` is false.
|
||||
func (a *SortedIntArray) PopRand() (value int, found bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRand()
|
||||
}
|
||||
|
||||
// PopRands randomly pops and returns `size` items out of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *SortedIntArray) PopRands(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
size = len(a.array)
|
||||
}
|
||||
array := make([]int, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array)))
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRands(size)
|
||||
}
|
||||
|
||||
// PopLefts pops and returns `size` items from the beginning of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *SortedIntArray) PopLefts(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
if size >= len(a.array) {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[0:size]
|
||||
a.array = a.array[size:]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopLefts(size)
|
||||
}
|
||||
|
||||
// PopRights pops and returns `size` items from the end of array.
|
||||
// If the given `size` is greater than size of the array, it returns all elements of the array.
|
||||
// Note that if given `size` <= 0 or the array is empty, it returns nil.
|
||||
func (a *SortedIntArray) PopRights(size int) []int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
index := len(a.array) - size
|
||||
if index <= 0 {
|
||||
array := a.array
|
||||
a.array = a.array[:0]
|
||||
return array
|
||||
}
|
||||
value := a.array[index:]
|
||||
a.array = a.array[:index]
|
||||
return value
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.PopRights(size)
|
||||
}
|
||||
|
||||
// Range picks and returns items by range, like array[start:end].
|
||||
@ -314,26 +210,8 @@ func (a *SortedIntArray) PopRights(size int) []int {
|
||||
// If `end` is omitted, then the sequence will have everything from start up
|
||||
// until the end of the array.
|
||||
func (a *SortedIntArray) Range(start int, end ...int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
offsetEnd := len(a.array)
|
||||
if len(end) > 0 && end[0] < offsetEnd {
|
||||
offsetEnd = end[0]
|
||||
}
|
||||
if start > offsetEnd {
|
||||
return nil
|
||||
}
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
array := ([]int)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
array = make([]int, offsetEnd-start)
|
||||
copy(array, a.array[start:offsetEnd])
|
||||
} else {
|
||||
array = a.array[start:offsetEnd]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Range(start, end...)
|
||||
}
|
||||
|
||||
// SubSlice returns a slice of elements from the array as specified
|
||||
@ -350,194 +228,91 @@ func (a *SortedIntArray) Range(start int, end ...int) []int {
|
||||
//
|
||||
// Any possibility crossing the left border of array, it will fail.
|
||||
func (a *SortedIntArray) SubSlice(offset int, length ...int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
size := len(a.array)
|
||||
if len(length) > 0 {
|
||||
size = length[0]
|
||||
}
|
||||
if offset > len(a.array) {
|
||||
return nil
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = len(a.array) + offset
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if size < 0 {
|
||||
offset += size
|
||||
size = -size
|
||||
if offset < 0 {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(a.array) {
|
||||
end = len(a.array)
|
||||
size = len(a.array) - offset
|
||||
}
|
||||
if a.mu.IsSafe() {
|
||||
s := make([]int, size)
|
||||
copy(s, a.array[offset:])
|
||||
return s
|
||||
} else {
|
||||
return a.array[offset:end]
|
||||
}
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.SubSlice(offset, length...)
|
||||
}
|
||||
|
||||
// Len returns the length of array.
|
||||
func (a *SortedIntArray) Len() int {
|
||||
a.mu.RLock()
|
||||
length := len(a.array)
|
||||
a.mu.RUnlock()
|
||||
return length
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Len()
|
||||
}
|
||||
|
||||
// Sum returns the sum of values in an array.
|
||||
func (a *SortedIntArray) Sum() (sum int) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
sum += v
|
||||
}
|
||||
return
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Sum()
|
||||
}
|
||||
|
||||
// Slice returns the underlying data of array.
|
||||
// Note that, if it's in concurrent-safe usage, it returns a copy of underlying data,
|
||||
// or else a pointer to the underlying data.
|
||||
func (a *SortedIntArray) Slice() []int {
|
||||
array := ([]int)(nil)
|
||||
if a.mu.IsSafe() {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array = make([]int, len(a.array))
|
||||
copy(array, a.array)
|
||||
} else {
|
||||
array = a.array
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Slice()
|
||||
}
|
||||
|
||||
// Interfaces returns current array as []any.
|
||||
func (a *SortedIntArray) Interfaces() []any {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
array := make([]any, len(a.array))
|
||||
for k, v := range a.array {
|
||||
array[k] = v
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Interfaces()
|
||||
}
|
||||
|
||||
// Contains checks whether a value exists in the array.
|
||||
func (a *SortedIntArray) Contains(value int) bool {
|
||||
return a.Search(value) != -1
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Contains(value)
|
||||
}
|
||||
|
||||
// Search searches array by `value`, returns the index of `value`,
|
||||
// or returns -1 if not exists.
|
||||
func (a *SortedIntArray) Search(value int) (index int) {
|
||||
if i, r := a.binSearch(value, true); r == 0 {
|
||||
return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Binary search.
|
||||
// It returns the last compared index and the result.
|
||||
// If `result` equals to 0, it means the value at `index` is equals to `value`.
|
||||
// If `result` lesser than 0, it means the value at `index` is lesser than `value`.
|
||||
// If `result` greater than 0, it means the value at `index` is greater than `value`.
|
||||
func (a *SortedIntArray) binSearch(value int, lock bool) (index int, result int) {
|
||||
if lock {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
}
|
||||
if len(a.array) == 0 {
|
||||
return -1, -2
|
||||
}
|
||||
min := 0
|
||||
max := len(a.array) - 1
|
||||
mid := 0
|
||||
cmp := -2
|
||||
for min <= max {
|
||||
mid = min + int((max-min)/2)
|
||||
cmp = a.getComparator()(value, a.array[mid])
|
||||
switch {
|
||||
case cmp < 0:
|
||||
max = mid - 1
|
||||
case cmp > 0:
|
||||
min = mid + 1
|
||||
default:
|
||||
return mid, cmp
|
||||
}
|
||||
}
|
||||
return mid, cmp
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Search(value)
|
||||
}
|
||||
|
||||
// SetUnique sets unique mark to the array,
|
||||
// which means it does not contain any repeated items.
|
||||
// It also do unique check, remove all repeated items.
|
||||
func (a *SortedIntArray) SetUnique(unique bool) *SortedIntArray {
|
||||
oldUnique := a.unique
|
||||
a.unique = unique
|
||||
if unique && oldUnique != unique {
|
||||
a.Unique()
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.SetUnique(unique)
|
||||
return a
|
||||
}
|
||||
|
||||
// Unique uniques the array, clear repeated items.
|
||||
func (a *SortedIntArray) Unique() *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
for i := 0; i < len(a.array)-1; {
|
||||
if a.getComparator()(a.array[i], a.array[i+1]) == 0 {
|
||||
a.array = append(a.array[:i+1], a.array[i+2:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Unique()
|
||||
return a
|
||||
}
|
||||
|
||||
// Clone returns a new array, which is a copy of current array.
|
||||
func (a *SortedIntArray) Clone() (newArray *SortedIntArray) {
|
||||
a.mu.RLock()
|
||||
array := make([]int, len(a.array))
|
||||
copy(array, a.array)
|
||||
a.mu.RUnlock()
|
||||
return NewSortedIntArrayFrom(array, a.mu.IsSafe())
|
||||
a.lazyInit()
|
||||
return &SortedIntArray{
|
||||
SortedTArray: a.SortedTArray.Clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Clear deletes all items of current array.
|
||||
func (a *SortedIntArray) Clear() *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
if len(a.array) > 0 {
|
||||
a.array = make([]int, 0)
|
||||
}
|
||||
a.mu.Unlock()
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Clear()
|
||||
return a
|
||||
}
|
||||
|
||||
// LockFunc locks writing by callback function `f`.
|
||||
func (a *SortedIntArray) LockFunc(f func(array []int)) *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.LockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// RLockFunc locks reading by callback function `f`.
|
||||
func (a *SortedIntArray) RLockFunc(f func(array []int)) *SortedIntArray {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
f(a.array)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.RLockFunc(f)
|
||||
return a
|
||||
}
|
||||
|
||||
@ -546,6 +321,7 @@ func (a *SortedIntArray) RLockFunc(f func(array []int)) *SortedIntArray {
|
||||
// The difference between Merge and Append is Append supports only specified slice type,
|
||||
// but Merge supports more parameter types.
|
||||
func (a *SortedIntArray) Merge(array any) *SortedIntArray {
|
||||
a.lazyInit()
|
||||
return a.Add(gconv.Ints(array)...)
|
||||
}
|
||||
|
||||
@ -553,104 +329,52 @@ func (a *SortedIntArray) Merge(array any) *SortedIntArray {
|
||||
// the size of each array is determined by `size`.
|
||||
// The last chunk may contain less than size elements.
|
||||
func (a *SortedIntArray) Chunk(size int) [][]int {
|
||||
if size < 1 {
|
||||
return nil
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
length := len(a.array)
|
||||
chunks := int(math.Ceil(float64(length) / float64(size)))
|
||||
var n [][]int
|
||||
for i, end := 0, 0; chunks > 0; chunks-- {
|
||||
end = (i + 1) * size
|
||||
if end > length {
|
||||
end = length
|
||||
}
|
||||
n = append(n, a.array[i*size:end])
|
||||
i++
|
||||
}
|
||||
return n
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Chunk(size)
|
||||
}
|
||||
|
||||
// Rand randomly returns one item from array(no deleting).
|
||||
func (a *SortedIntArray) Rand() (value int, found bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return a.array[grand.Intn(len(a.array))], true
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Rand()
|
||||
}
|
||||
|
||||
// Rands randomly returns `size` items from array(no deleting).
|
||||
func (a *SortedIntArray) Rands(size int) []int {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if size <= 0 || len(a.array) == 0 {
|
||||
return nil
|
||||
}
|
||||
array := make([]int, size)
|
||||
for i := 0; i < size; i++ {
|
||||
array[i] = a.array[grand.Intn(len(a.array))]
|
||||
}
|
||||
return array
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Rands(size)
|
||||
}
|
||||
|
||||
// Join joins array elements with a string `glue`.
|
||||
func (a *SortedIntArray) Join(glue string) string {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
if len(a.array) == 0 {
|
||||
return ""
|
||||
}
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for k, v := range a.array {
|
||||
buffer.WriteString(gconv.String(v))
|
||||
if k != len(a.array)-1 {
|
||||
buffer.WriteString(glue)
|
||||
}
|
||||
}
|
||||
return buffer.String()
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.Join(glue)
|
||||
}
|
||||
|
||||
// CountValues counts the number of occurrences of all values in the array.
|
||||
func (a *SortedIntArray) CountValues() map[int]int {
|
||||
m := make(map[int]int)
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for _, v := range a.array {
|
||||
m[v]++
|
||||
}
|
||||
return m
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.CountValues()
|
||||
}
|
||||
|
||||
// Iterator is alias of IteratorAsc.
|
||||
func (a *SortedIntArray) Iterator(f func(k int, v int) bool) {
|
||||
a.IteratorAsc(f)
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Iterator(f)
|
||||
}
|
||||
|
||||
// IteratorAsc iterates the array readonly in ascending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *SortedIntArray) IteratorAsc(f func(k int, v int) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for k, v := range a.array {
|
||||
if !f(k, v) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.IteratorAsc(f)
|
||||
}
|
||||
|
||||
// IteratorDesc iterates the array readonly in descending order with given callback function `f`.
|
||||
// If `f` returns true, then it continues iterating; or false to stop.
|
||||
func (a *SortedIntArray) IteratorDesc(f func(k int, v int) bool) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
for i := len(a.array) - 1; i >= 0; i-- {
|
||||
if !f(i, a.array[i]) {
|
||||
break
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.IteratorDesc(f)
|
||||
}
|
||||
|
||||
// String returns current array as a string, which implements like json.Marshal does.
|
||||
@ -658,73 +382,64 @@ func (a *SortedIntArray) String() string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
a.lazyInit()
|
||||
return "[" + a.Join(",") + "]"
|
||||
}
|
||||
|
||||
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
|
||||
// Note that do not use pointer as its receiver here.
|
||||
func (a SortedIntArray) MarshalJSON() ([]byte, error) {
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
return json.Marshal(a.array)
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.MarshalJSON()
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
|
||||
func (a *SortedIntArray) UnmarshalJSON(b []byte) error {
|
||||
if a.comparator == nil {
|
||||
a.array = make([]int, 0)
|
||||
a.lazyInit()
|
||||
if a.comparator == nil || a.sorter == nil {
|
||||
a.comparator = defaultComparatorInt
|
||||
a.sorter = quickSortInt
|
||||
a.array = make([]int, 0)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if err := json.UnmarshalUseNumber(b, &a.array); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.array != nil {
|
||||
sort.Ints(a.array)
|
||||
}
|
||||
return nil
|
||||
|
||||
return a.SortedTArray.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// UnmarshalValue is an interface implement which sets any type of value for array.
|
||||
func (a *SortedIntArray) UnmarshalValue(value any) (err error) {
|
||||
if a.comparator == nil {
|
||||
a.lazyInit()
|
||||
if a.comparator == nil || a.sorter == nil {
|
||||
a.comparator = defaultComparatorInt
|
||||
a.sorter = quickSortInt
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
switch value.(type) {
|
||||
case string, []byte:
|
||||
err = json.UnmarshalUseNumber(gconv.Bytes(value), &a.array)
|
||||
default:
|
||||
a.array = gconv.SliceInt(value)
|
||||
}
|
||||
if a.array != nil {
|
||||
sort.Ints(a.array)
|
||||
}
|
||||
return err
|
||||
|
||||
return a.SortedTArray.UnmarshalValue(value)
|
||||
}
|
||||
|
||||
// Filter iterates array and filters elements using custom callback function.
|
||||
// It removes the element from array if callback function `filter` returns true,
|
||||
// it or else does nothing and continues iterating.
|
||||
func (a *SortedIntArray) Filter(filter func(index int, value int) bool) *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
for i := 0; i < len(a.array); {
|
||||
if filter(i, a.array[i]) {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Filter(filter)
|
||||
return a
|
||||
}
|
||||
|
||||
// FilterEmpty removes all zero value of the array.
|
||||
func (a *SortedIntArray) FilterEmpty() *SortedIntArray {
|
||||
a.lazyInit()
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
if len(a.array) == 0 {
|
||||
return a
|
||||
}
|
||||
|
||||
if a.array[0] != 0 && a.array[len(a.array)-1] != 0 {
|
||||
a.SortedTArray.FilterEmpty()
|
||||
return a
|
||||
}
|
||||
|
||||
for i := 0; i < len(a.array); {
|
||||
if a.array[i] == 0 {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
@ -735,6 +450,7 @@ func (a *SortedIntArray) FilterEmpty() *SortedIntArray {
|
||||
for i := len(a.array) - 1; i >= 0; {
|
||||
if a.array[i] == 0 {
|
||||
a.array = append(a.array[:i], a.array[i+1:]...)
|
||||
i--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
@ -744,40 +460,21 @@ func (a *SortedIntArray) FilterEmpty() *SortedIntArray {
|
||||
|
||||
// Walk applies a user supplied function `f` to every item of array.
|
||||
func (a *SortedIntArray) Walk(f func(value int) int) *SortedIntArray {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
// Keep the array always sorted.
|
||||
defer quickSortInt(a.array, a.getComparator())
|
||||
|
||||
for i, v := range a.array {
|
||||
a.array[i] = f(v)
|
||||
}
|
||||
a.lazyInit()
|
||||
a.SortedTArray.Walk(f)
|
||||
return a
|
||||
}
|
||||
|
||||
// IsEmpty checks whether the array is empty.
|
||||
func (a *SortedIntArray) IsEmpty() bool {
|
||||
return a.Len() == 0
|
||||
}
|
||||
|
||||
// getComparator returns the comparator if it's previously set,
|
||||
// or else it returns a default comparator.
|
||||
func (a *SortedIntArray) getComparator() func(a, b int) int {
|
||||
if a.comparator == nil {
|
||||
return defaultComparatorInt
|
||||
}
|
||||
return a.comparator
|
||||
a.lazyInit()
|
||||
return a.SortedTArray.IsEmpty()
|
||||
}
|
||||
|
||||
// DeepCopy implements interface for deep copy of current type.
|
||||
func (a *SortedIntArray) DeepCopy() any {
|
||||
if a == nil {
|
||||
return nil
|
||||
a.lazyInit()
|
||||
return &SortedIntArray{
|
||||
SortedTArray: a.SortedTArray.DeepCopy().(*SortedTArray[int]),
|
||||
}
|
||||
a.mu.RLock()
|
||||
defer a.mu.RUnlock()
|
||||
newSlice := make([]int, len(a.array))
|
||||
copy(newSlice, a.array)
|
||||
return NewSortedIntArrayFrom(newSlice, a.mu.IsSafe())
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user