Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
951b2c7f0d | ||
|
|
544c77a513 | ||
|
|
a3864a33fa | ||
|
|
d52c96ab79 |
No files matched your search
@@ -6,3 +6,4 @@ https://github.com/owncloud/ocis/pull/12051
|
||||
https://github.com/owncloud/ocis/pull/12087
|
||||
https://github.com/owncloud/ocis/pull/12137
|
||||
https://github.com/owncloud/ocis/pull/12302
|
||||
https://github.com/owncloud/ocis/pull/12432
|
||||
@@ -33,7 +33,7 @@ require (
|
||||
github.com/go-micro/plugins/v4/store/nats-js-kv v0.0.0-20240726082623-6831adfdcdc4
|
||||
github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0
|
||||
github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0
|
||||
github.com/go-playground/validator/v10 v10.30.2
|
||||
github.com/go-playground/validator/v10 v10.30.3
|
||||
github.com/gofrs/uuid v4.4.0+incompatible
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/golang/protobuf v1.5.4
|
||||
@@ -64,12 +64,12 @@ require (
|
||||
github.com/open-policy-agent/opa v1.16.2
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260521135517-5cf6fa2c7dbf
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260616081804-228bd580fa22
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/r3labs/sse/v2 v2.10.0
|
||||
github.com/rogpeppe/go-internal v1.14.1
|
||||
github.com/rogpeppe/go-internal v1.15.0
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/rs/zerolog v1.35.1
|
||||
github.com/shamaton/msgpack/v2 v2.4.1
|
||||
@@ -86,14 +86,14 @@ require (
|
||||
github.com/xhit/go-simple-mail/v2 v2.16.0
|
||||
go-micro.dev/v4 v4.11.0
|
||||
go.etcd.io/bbolt v1.4.3
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0
|
||||
go.opentelemetry.io/contrib/zpages v0.68.0
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel v1.44.0
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0
|
||||
go.opentelemetry.io/otel/sdk v1.44.0
|
||||
go.opentelemetry.io/otel/trace v1.44.0
|
||||
golang.org/x/crypto v0.52.0
|
||||
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
|
||||
golang.org/x/image v0.41.0
|
||||
@@ -102,7 +102,7 @@ require (
|
||||
golang.org/x/sync v0.20.0
|
||||
golang.org/x/term v0.43.0
|
||||
golang.org/x/text v0.37.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa
|
||||
google.golang.org/grpc v1.81.1
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
@@ -116,7 +116,7 @@ require (
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.4.0 // indirect
|
||||
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProtonMail/go-crypto v1.1.6 // indirect
|
||||
@@ -156,8 +156,8 @@ require (
|
||||
github.com/ceph/go-ceph v0.39.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cevaris/ordered_map v0.0.0-20190319150403-3adeae072e73 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.10.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.6.0 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/cloudflare/circl v1.6.3 // indirect
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 // indirect
|
||||
@@ -173,13 +173,13 @@ require (
|
||||
github.com/dgraph-io/ristretto v0.2.0 // indirect
|
||||
github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dlclark/regexp2 v1.4.0 // indirect
|
||||
github.com/dlclark/regexp2 v1.12.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/egirna/icap v0.0.0-20181108071049-d5ee18bd70bc // indirect
|
||||
github.com/emirpasic/gods v1.18.1 // indirect
|
||||
github.com/emvi/iso-639-1 v1.1.1 // indirect
|
||||
github.com/evanphx/json-patch/v5 v5.5.0 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/gdexlab/go-render v1.0.1 // indirect
|
||||
@@ -259,7 +259,7 @@ require (
|
||||
github.com/mattermost/xml-roundtrip-validator v0.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.19 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.44 // indirect
|
||||
github.com/maxymania/go-system v0.0.0-20170110133659-647cc364bf0b // indirect
|
||||
github.com/mendsley/gojwk v0.0.0-20141217222730-4d5ec6e58103 // indirect
|
||||
@@ -268,7 +268,7 @@ require (
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/highwayhash v1.0.4 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/minio/minio-go/v7 v7.1.0 // indirect
|
||||
github.com/minio/minio-go/v7 v7.2.0 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
@@ -334,8 +334,8 @@ require (
|
||||
go.etcd.io/etcd/client/v3 v3.6.11 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
@@ -346,8 +346,9 @@ require (
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.2 // indirect
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
|
||||
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -59,6 +59,8 @@ github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3Q
|
||||
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
|
||||
github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
|
||||
github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
|
||||
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible h1:z4yfnGrZ7netVz+0EDJ0Wi+5VZCSYp4Z0m2dk6cEM60=
|
||||
github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0 h1:6ZXKb9Rp6qp1bDbJefnG7cTH8yMN1IC/4nf+GVjO99k=
|
||||
@@ -185,8 +187,12 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/clipperhouse/displaywidth v0.10.0 h1:GhBG8WuerxjFQQYeuZAeVTuyxuX+UraiZGD4HJQ3Y8g=
|
||||
github.com/clipperhouse/displaywidth v0.10.0/go.mod h1:XqJajYsaiEwkxOj4bowCTMcT1SgvHo9flfF3jQasdbs=
|
||||
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
|
||||
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
|
||||
github.com/clipperhouse/uax29/v2 v2.6.0 h1:z0cDbUV+aPASdFb2/ndFnS9ts/WNXgTNNGFoKXuhpos=
|
||||
github.com/clipperhouse/uax29/v2 v2.6.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
|
||||
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
|
||||
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
@@ -238,6 +244,8 @@ github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4m
|
||||
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E=
|
||||
github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E=
|
||||
github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
|
||||
github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8=
|
||||
github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
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/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e h1:rcHHSQqzCgvlwP0I/fQ8rQMn/MpHE5gWSLdtpxtP6KQ=
|
||||
@@ -259,6 +267,8 @@ github.com/evanphx/json-patch/v5 v5.5.0/go.mod h1:G79N1coSVB93tBe7j6PhzjmR3/2Vvl
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
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/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
@@ -365,6 +375,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.2 h1:JiFIMtSSHb2/XBUbWM4i/MpeQm9ZK2xqPNk8vgvu5JQ=
|
||||
github.com/go-playground/validator/v10 v10.30.2/go.mod h1:mAf2pIOVXjTEBrwUMGKkCWKKPs9NheYGabeB04txQSc=
|
||||
github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8=
|
||||
github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
|
||||
@@ -653,6 +665,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
|
||||
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-sqlite3 v1.14.44 h1:3VSe+xafpbzsLbdr2AWlAZk9yRHiBhTBakioXaCKTF8=
|
||||
github.com/mattn/go-sqlite3 v1.14.44/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
@@ -674,6 +688,8 @@ github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.1.0 h1:QEt5IStDpxgGjEdtOgpiZ5QhmSl3ax7qy61vi2SwHO8=
|
||||
github.com/minio/minio-go/v7 v7.1.0/go.mod h1:Dm7WS1AgLmBa0NcQD6SeJnJf+K/EUW3GR7Ks6olB3OA=
|
||||
github.com/minio/minio-go/v7 v7.2.0 h1:RCJM0R1XOsRs+A3x3UCaf3ZYbByDaLjFeAi+YCQEPhs=
|
||||
github.com/minio/minio-go/v7 v7.2.0/go.mod h1:EU9hENAStx/xXduNdrGO5e4X5vk19NtgB+RIPjZO8o0=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
@@ -742,6 +758,16 @@ github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:J
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260521135517-5cf6fa2c7dbf h1:VSRW0jZVcDrmwCwEoXZAIPQi3Agnes9uiNTdWGKjzKg=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260521135517-5cf6fa2c7dbf/go.mod h1:oHjvB9PhfF8QqiNGz7Hd4AVvR7CSPx3CLVRxUzmjK0w=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260612153304-63930c859f43 h1:5nkkNr1hnrU+a8thc84zollqkP6CazilEuz+EIp8YWk=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260612153304-63930c859f43/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615121532-bd663f8d0aed h1:QKiUkC6uBq7wjRhUHWaho/MkXPP9bleVinJ+wwyxbUQ=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615121532-bd663f8d0aed/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615124328-892e11ba709b h1:18qsAy2Z6K/+FgVh2FbM1C2So4WRLCzS9fsM3uotO5o=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615124328-892e11ba709b/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615133621-ad8d76aff9d6 h1:5FupdFnTwLdUbwoGyvw89qPob0dnYSxEBdebtt0VbPw=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260615133621-ad8d76aff9d6/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260616081804-228bd580fa22 h1:AHc4Ck0AeKJcbGAUblYGvKtXx8/0NetMB6OjtgCDU1E=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20260616081804-228bd580fa22/go.mod h1:gNSgpblFyfCDi1OQfU4VqPIHWtAPR3YPTE1ZaTNnG/U=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.9 h1:njquRbBU7fuwIe5rEvtaniVBjwWzcpdUVptSgzFqZsw=
|
||||
@@ -816,6 +842,8 @@ github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqn
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
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.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
|
||||
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
@@ -877,6 +905,7 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
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/stvp/go-udp-testing v0.0.0-20201019212854-469649b16807/go.mod h1:7jxmlfBCDBXRzr0eAQJ48XC1hBu1np4CS5+cHEYfwpc=
|
||||
@@ -965,26 +994,41 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0 h1:2yEATaop1/a1I4psnSLgWVPLWwCzkqWakgJy7xTDVy0=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0/go.mod h1:D7J12YRapIekYyPWgGPlA/23pRmpSEZC5xJC/TTLI9U=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo=
|
||||
go.opentelemetry.io/contrib/zpages v0.68.0 h1:H5yrUwxPrbvhzdBxjQD+VXMtPjIBfp8NWNVvQT8E30M=
|
||||
go.opentelemetry.io/contrib/zpages v0.68.0/go.mod h1:sZGctYYO4UOHItj9bx3F+t/s+u1Fv8CHCJ5s2eR2cjU=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0 h1:D7UpUy2Xc2wsi1Ras6V40q806WM07rqoCWzXu7Sqy+4=
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0/go.mod h1:nPCqOnEH9rNLKqH/+rrUjiMzHJdV1BlpKcTwRTyKkKI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 h1:RAE+JPfvEmvy+0LzyUA25/SGawPwIUbZ6u0Wug54sLc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod h1:AGmbycVGEsRx9mXMZ75CsOyhSP6MFIcj/6dnG+vhVjk=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0 h1:qazEJlUOQzhCpzQpFETGby7EdqjI1wsd0W+6Gg1SCTU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0/go.mod h1:fOD2Yefuxixkx3ahVNf0O/PERb6r4OlbxfATVnYvzCo=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
@@ -1325,8 +1369,12 @@ google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH8
|
||||
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409/go.mod h1:rxKD3IEILWEu3P44seeNOAwZN4SaoKaQ/2eTg4mM6EM=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
|
||||
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
@@ -1370,6 +1418,8 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/ini.v1 v1.67.2 h1:JtOSMb9OuaCZKr7h5D/h6iii14sK0hLbplTc6frx4Ss=
|
||||
gopkg.in/ini.v1 v1.67.2/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
_fuzz/
|
||||
_fuzz/
|
||||
.devcontainer/
|
||||
+37
-22
@@ -1,27 +1,42 @@
|
||||
run:
|
||||
deadline: 2m
|
||||
|
||||
version: "2"
|
||||
linters:
|
||||
disable-all: true
|
||||
default: none
|
||||
enable:
|
||||
- misspell
|
||||
- govet
|
||||
- staticcheck
|
||||
- errcheck
|
||||
- unparam
|
||||
- ineffassign
|
||||
- nakedret
|
||||
- gocyclo
|
||||
- dupl
|
||||
- goimports
|
||||
- revive
|
||||
- errcheck
|
||||
- gocyclo
|
||||
- gosec
|
||||
- gosimple
|
||||
- typecheck
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
- nakedret
|
||||
- revive
|
||||
- staticcheck
|
||||
- unparam
|
||||
- unused
|
||||
|
||||
linters-settings:
|
||||
gofmt:
|
||||
simplify: true
|
||||
dupl:
|
||||
threshold: 600
|
||||
settings:
|
||||
dupl:
|
||||
threshold: 600
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- goimports
|
||||
settings:
|
||||
gofmt:
|
||||
simplify: true
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
+58
-36
@@ -21,21 +21,43 @@ type Constraints struct {
|
||||
IncludePrerelease bool
|
||||
}
|
||||
|
||||
// MaxConstraintLen is the maximum allowed length of a constraint string.
|
||||
const MaxConstraintLen = 512
|
||||
|
||||
// MaxConstraintGroups is the maximum number of OR groups allowed in a
|
||||
// constraint string.
|
||||
const MaxConstraintGroups = 32
|
||||
|
||||
// ErrConstraintTooLong is returned when a constraint string exceeds the
|
||||
// maximum allowed length.
|
||||
var ErrConstraintTooLong = fmt.Errorf("constraint string is too long (max %d bytes)", MaxConstraintLen)
|
||||
|
||||
// ErrTooManyConstraintGroups is returned when a constraint string contains
|
||||
// too many OR groups.
|
||||
var ErrTooManyConstraintGroups = fmt.Errorf("too many constraint groups (max %d)", MaxConstraintGroups)
|
||||
|
||||
// NewConstraint returns a Constraints instance that a Version instance can
|
||||
// be checked against. If there is a parse error it will be returned.
|
||||
func NewConstraint(c string) (*Constraints, error) {
|
||||
|
||||
if len(c) > MaxConstraintLen {
|
||||
return nil, ErrConstraintTooLong
|
||||
}
|
||||
|
||||
// Rewrite - ranges into a comparison operation.
|
||||
c = rewriteRange(c)
|
||||
|
||||
ors := strings.Split(c, "||")
|
||||
if len(ors) > MaxConstraintGroups {
|
||||
return nil, ErrTooManyConstraintGroups
|
||||
}
|
||||
lenors := len(ors)
|
||||
or := make([][]*constraint, lenors)
|
||||
hasPre := make([]bool, lenors)
|
||||
for k, v := range ors {
|
||||
// Validate the segment
|
||||
if !validConstraintRegex.MatchString(v) {
|
||||
return nil, fmt.Errorf("improper constraint: %s", v)
|
||||
return nil, fmt.Errorf("improper constraint: %q", v)
|
||||
}
|
||||
|
||||
cs := findConstraintRegex.FindAllString(v, -1)
|
||||
@@ -104,9 +126,9 @@ func (cs Constraints) Validate(v *Version) (bool, []error) {
|
||||
for _, c := range o {
|
||||
// Before running the check handle the case there the version is
|
||||
// a prerelease and the check is not searching for prereleases.
|
||||
if !(cs.IncludePrerelease || cs.containsPre[i]) && v.pre != "" {
|
||||
if !cs.IncludePrerelease && !cs.containsPre[i] && v.pre != "" {
|
||||
if !prerelesase {
|
||||
em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
em := fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
e = append(e, em)
|
||||
prerelesase = true
|
||||
}
|
||||
@@ -258,7 +280,7 @@ func parseConstraint(c string) (*constraint, error) {
|
||||
if len(c) > 0 {
|
||||
m := constraintRegex.FindStringSubmatch(c)
|
||||
if m == nil {
|
||||
return nil, fmt.Errorf("improper constraint: %s", c)
|
||||
return nil, fmt.Errorf("improper constraint: %q", c)
|
||||
}
|
||||
|
||||
cs := &constraint{
|
||||
@@ -325,7 +347,7 @@ func constraintNotEqual(v *Version, c *constraint, includePre bool) (bool, error
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
if c.dirty {
|
||||
@@ -335,7 +357,7 @@ func constraintNotEqual(v *Version, c *constraint, includePre bool) (bool, error
|
||||
if c.con.Minor() != v.Minor() && !c.minorDirty {
|
||||
return true, nil
|
||||
} else if c.minorDirty {
|
||||
return false, fmt.Errorf("%s is equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is equal to %q", v, c.orig)
|
||||
} else if c.con.Patch() != v.Patch() && !c.patchDirty {
|
||||
return true, nil
|
||||
} else if c.patchDirty {
|
||||
@@ -345,15 +367,15 @@ func constraintNotEqual(v *Version, c *constraint, includePre bool) (bool, error
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is equal to %q", v, c.orig)
|
||||
}
|
||||
return false, fmt.Errorf("%s is equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is equal to %q", v, c.orig)
|
||||
}
|
||||
}
|
||||
|
||||
eq := v.Equal(c.con)
|
||||
if eq {
|
||||
return false, fmt.Errorf("%s is equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
@@ -364,7 +386,7 @@ func constraintGreaterThan(v *Version, c *constraint, includePre bool) (bool, er
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
var eq bool
|
||||
@@ -374,17 +396,17 @@ func constraintGreaterThan(v *Version, c *constraint, includePre bool) (bool, er
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than or equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
if v.Major() > c.con.Major() {
|
||||
return true, nil
|
||||
} else if v.Major() < c.con.Major() {
|
||||
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than or equal to %q", v, c.orig)
|
||||
} else if c.minorDirty {
|
||||
// This is a range case such as >11. When the version is something like
|
||||
// 11.1.0 is it not > 11. For that we would need 12 or higher
|
||||
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than or equal to %q", v, c.orig)
|
||||
} else if c.patchDirty {
|
||||
// This is for ranges such as >11.1. A version of 11.1.1 is not greater
|
||||
// which one of 11.2.1 is greater
|
||||
@@ -392,7 +414,7 @@ func constraintGreaterThan(v *Version, c *constraint, includePre bool) (bool, er
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than or equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
// If we have gotten here we are not comparing pre-preleases and can use the
|
||||
@@ -401,21 +423,21 @@ func constraintGreaterThan(v *Version, c *constraint, includePre bool) (bool, er
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than or equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
func constraintLessThan(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
eq := v.Compare(c.con) < 0
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is greater than or equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
func constraintGreaterThanEqual(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
@@ -423,21 +445,21 @@ func constraintGreaterThanEqual(v *Version, c *constraint, includePre bool) (boo
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
eq := v.Compare(c.con) >= 0
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is less than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than %q", v, c.orig)
|
||||
}
|
||||
|
||||
func constraintLessThanEqual(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
var eq bool
|
||||
@@ -447,13 +469,13 @@ func constraintLessThanEqual(v *Version, c *constraint, includePre bool) (bool,
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s is greater than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is greater than %q", v, c.orig)
|
||||
}
|
||||
|
||||
if v.Major() > c.con.Major() {
|
||||
return false, fmt.Errorf("%s is greater than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is greater than %q", v, c.orig)
|
||||
} else if v.Major() == c.con.Major() && v.Minor() > c.con.Minor() && !c.minorDirty {
|
||||
return false, fmt.Errorf("%s is greater than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is greater than %q", v, c.orig)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
@@ -469,11 +491,11 @@ func constraintTilde(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
if v.LessThan(c.con) {
|
||||
return false, fmt.Errorf("%s is less than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than %q", v, c.orig)
|
||||
}
|
||||
|
||||
// ~0.0.0 is a special case where all constraints are accepted. It's
|
||||
@@ -484,11 +506,11 @@ func constraintTilde(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
}
|
||||
|
||||
if v.Major() != c.con.Major() {
|
||||
return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same major version as %q", v, c.orig)
|
||||
}
|
||||
|
||||
if v.Minor() != c.con.Minor() && !c.minorDirty {
|
||||
return false, fmt.Errorf("%s does not have same major and minor version as %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same major and minor version as %q", v, c.orig)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
@@ -500,7 +522,7 @@ func constraintTildeOrEqual(v *Version, c *constraint, includePre bool) (bool, e
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
if c.dirty {
|
||||
@@ -512,7 +534,7 @@ func constraintTildeOrEqual(v *Version, c *constraint, includePre bool) (bool, e
|
||||
return true, nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("%s is not equal to %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is not equal to %q", v, c.orig)
|
||||
}
|
||||
|
||||
// ^* --> (any)
|
||||
@@ -528,12 +550,12 @@ func constraintCaret(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
// The existence of prereleases is checked at the group level and passed in.
|
||||
// Exit early if the version has a prerelease but those are to be ignored.
|
||||
if v.Prerelease() != "" && !includePre {
|
||||
return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
return false, fmt.Errorf("%q is a prerelease version and the constraint is only looking for release versions", v)
|
||||
}
|
||||
|
||||
// This less than handles prereleases
|
||||
if v.LessThan(c.con) {
|
||||
return false, fmt.Errorf("%s is less than %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q is less than %q", v, c.orig)
|
||||
}
|
||||
|
||||
var eq bool
|
||||
@@ -548,12 +570,12 @@ func constraintCaret(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same major version as %q", v, c.orig)
|
||||
}
|
||||
|
||||
// ^ when the major is 0 and minor > 0 is >=0.y.z < 0.y+1
|
||||
if c.con.Major() == 0 && v.Major() > 0 {
|
||||
return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same major version as %q", v, c.orig)
|
||||
}
|
||||
// If the con Minor is > 0 it is not dirty
|
||||
if c.con.Minor() > 0 || c.patchDirty {
|
||||
@@ -561,11 +583,11 @@ func constraintCaret(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s does not have same minor version as %s. Expected minor versions to match when constraint major version is 0", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same minor version as %q. Expected minor versions to match when constraint major version is 0", v, c.orig)
|
||||
}
|
||||
// ^ when the minor is 0 and minor > 0 is =0.0.z
|
||||
if c.con.Minor() == 0 && v.Minor() > 0 {
|
||||
return false, fmt.Errorf("%s does not have same minor version as %s", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not have same minor version as %q", v, c.orig)
|
||||
}
|
||||
|
||||
// At this point the major is 0 and the minor is 0 and not dirty. The patch
|
||||
@@ -574,7 +596,7 @@ func constraintCaret(v *Version, c *constraint, includePre bool) (bool, error) {
|
||||
if eq {
|
||||
return true, nil
|
||||
}
|
||||
return false, fmt.Errorf("%s does not equal %s. Expect version and constraint to equal when major and minor versions are 0", v, c.orig)
|
||||
return false, fmt.Errorf("%q does not equal %q. Expect version and constraint to equal when major and minor versions are 0", v, c.orig)
|
||||
}
|
||||
|
||||
func isX(x string) bool {
|
||||
|
||||
+38
-1
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -48,8 +49,16 @@ var (
|
||||
|
||||
// ErrInvalidPrerelease is returned when the pre-release is an invalid format
|
||||
ErrInvalidPrerelease = errors.New("invalid prerelease string")
|
||||
|
||||
// ErrVersionTooLong is returned when a version string exceeds the
|
||||
// maximum allowed length.
|
||||
ErrVersionTooLong = fmt.Errorf("version string is too long (max %d bytes)", MaxVersionLen)
|
||||
)
|
||||
|
||||
// MaxVersionLen is the maximum allowed length of a version string. This guards
|
||||
// against unbounded input causing excessive memory allocations during parsing.
|
||||
const MaxVersionLen = 256
|
||||
|
||||
// semVerRegex is the regular expression used to parse a semantic version.
|
||||
// This is not the official regex from the semver spec. It has been modified to allow for loose handling
|
||||
// where versions like 2.1 are detected.
|
||||
@@ -94,6 +103,10 @@ func StrictNewVersion(v string) (*Version, error) {
|
||||
return nil, ErrEmptyString
|
||||
}
|
||||
|
||||
if len(v) > MaxVersionLen {
|
||||
return nil, ErrVersionTooLong
|
||||
}
|
||||
|
||||
// Split the parts into [0]major, [1]minor, and [2]patch,prerelease,build
|
||||
parts := strings.SplitN(v, ".", 3)
|
||||
if len(parts) != 3 {
|
||||
@@ -161,6 +174,9 @@ func StrictNewVersion(v string) (*Version, error) {
|
||||
// attempts to convert it to SemVer. If you want to validate it was a strict
|
||||
// semantic version at parse time see StrictNewVersion().
|
||||
func NewVersion(v string) (*Version, error) {
|
||||
if len(v) > MaxVersionLen {
|
||||
return nil, ErrVersionTooLong
|
||||
}
|
||||
if CoerceNewVersion {
|
||||
return coerceNewVersion(v)
|
||||
}
|
||||
@@ -289,6 +305,8 @@ func coerceNewVersion(v string) (*Version, error) {
|
||||
|
||||
// New creates a new instance of Version with each of the parts passed in as
|
||||
// arguments instead of parsing a version string.
|
||||
// Note, New does not validate prerelease or metadata. Incorrect information can
|
||||
// be passed in.
|
||||
func New(major, minor, patch uint64, pre, metadata string) *Version {
|
||||
v := Version{
|
||||
major: major,
|
||||
@@ -301,6 +319,7 @@ func New(major, minor, patch uint64, pre, metadata string) *Version {
|
||||
|
||||
v.original = v.String()
|
||||
|
||||
// TODO: In the next semver major version validate the pre and metadata. Return error if there is one.
|
||||
return &v
|
||||
}
|
||||
|
||||
@@ -388,6 +407,9 @@ func (v Version) IncPatch() Version {
|
||||
} else {
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
if v.patch == math.MaxUint64 {
|
||||
panic("patch version increment would overflow uint64")
|
||||
}
|
||||
vNext.patch = v.patch + 1
|
||||
}
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
@@ -404,6 +426,9 @@ func (v Version) IncMinor() Version {
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
vNext.patch = 0
|
||||
if v.minor == math.MaxUint64 {
|
||||
panic("minor version increment would overflow uint64")
|
||||
}
|
||||
vNext.minor = v.minor + 1
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext
|
||||
@@ -421,6 +446,9 @@ func (v Version) IncMajor() Version {
|
||||
vNext.pre = ""
|
||||
vNext.patch = 0
|
||||
vNext.minor = 0
|
||||
if v.major == math.MaxUint64 {
|
||||
panic("major version increment would overflow uint64")
|
||||
}
|
||||
vNext.major = v.major + 1
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext
|
||||
@@ -568,7 +596,16 @@ func (v Version) MarshalText() ([]byte, error) {
|
||||
// Scan implements the SQL.Scanner interface.
|
||||
func (v *Version) Scan(value interface{}) error {
|
||||
var s string
|
||||
s, _ = value.(string)
|
||||
switch t := value.(type) {
|
||||
case string:
|
||||
s = t
|
||||
case []byte:
|
||||
s = string(t)
|
||||
case nil:
|
||||
return fmt.Errorf("cannot scan nil into Version")
|
||||
default:
|
||||
return fmt.Errorf("unsupported Scan type %T", value)
|
||||
}
|
||||
temp, err := NewVersion(s)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+12
@@ -28,6 +28,18 @@ Retrieve and consider the comments on the PR, which may have come from GitHub Co
|
||||
|
||||
Offer to optionally post a brief summary of the review to the PR, via the gh CLI tool.
|
||||
|
||||
## Tagged Go releases
|
||||
|
||||
If I ask you whether we are ready to release, this means a tagged Go release on the main branch. Go releases are git tagged with a version number.
|
||||
|
||||
Review the changes since the last release, i.e. the previous git tag. Ensure that the changes are complete and correct. Identify new features, bug fixes, and performance improvements.
|
||||
|
||||
Identify breaking changes, especially API changes.
|
||||
|
||||
Ensure good test coverage. Look for performance changes, especially performance regressions, by running benchmarks against the previous release.
|
||||
|
||||
Ensure that the documentation in READMEs and GoDocs are complete, correct and consistent.
|
||||
|
||||
## Comparisons to go-runewidth
|
||||
|
||||
We originally attempted to make this package compatible with go-runewidth.
|
||||
|
||||
+14
@@ -1,5 +1,19 @@
|
||||
# Changelog
|
||||
|
||||
## [0.11.0]
|
||||
|
||||
[Compare](https://github.com/clipperhouse/displaywidth/compare/v0.10.0...v0.11.0)
|
||||
|
||||
### Added
|
||||
- New `ControlSequences8Bit` option to treat 8-bit ECMA-48 (C1) escape sequences as zero-width. (#22)
|
||||
|
||||
### Changed
|
||||
- Upgraded uax29 dependency to v2.7.0 for 8-bit escape sequence support in the grapheme iterator.
|
||||
- Truncation now validates that preserved trailing escape sequences are zero-width, preventing edge cases where non-zero-width sequences could leak into output.
|
||||
|
||||
### Note
|
||||
- `ControlSequences8Bit` is deliberately ignored by `TruncateString` and `TruncateBytes`, because C1 byte values (0x80–0x9F) overlap with UTF-8 multi-byte encoding.
|
||||
|
||||
## [0.10.0]
|
||||
|
||||
[Compare](https://github.com/clipperhouse/displaywidth/compare/v0.9.0...v0.10.0)
|
||||
|
||||
+21
-1
@@ -79,6 +79,16 @@ when calculating the display width. When `false` (default), ANSI escape
|
||||
sequences are treated as just a series of characters. When `true`, they are
|
||||
treated as a single zero-width unit.
|
||||
|
||||
#### ControlSequences8Bit
|
||||
|
||||
`ControlSequences8Bit` specifies whether to ignore 8-bit ECMA-48 escape sequences
|
||||
when calculating the display width. When `false` (default), these are treated
|
||||
as just a series of characters. When `true`, they are treated as a single
|
||||
zero-width unit.
|
||||
|
||||
Note: this option is ignored by the `Truncate` methods, as the concatenation
|
||||
can lead to unintended UTF-8 semantics.
|
||||
|
||||
#### EastAsianWidth
|
||||
|
||||
`EastAsianWidth` defines how
|
||||
@@ -103,12 +113,22 @@ and [regional indicator pairs](https://en.wikipedia.org/wiki/Regional_indicator_
|
||||
for emojis. We are keeping an eye on
|
||||
[emerging standards](https://www.jeffquast.com/post/state-of-terminal-emulation-2025/).
|
||||
|
||||
For control sequences, we implement the [ECMA-48](https://ecma-international.org/publications-and-standards/standards/ecma-48/) standard for 7-bit ASCII control sequences.
|
||||
For control sequences, we implement the [ECMA-48](https://ecma-international.org/publications-and-standards/standards/ecma-48/) standard for 7-bit and 8-bit control sequences.
|
||||
|
||||
`clipperhouse/displaywidth`, `mattn/go-runewidth`, and `rivo/uniseg` will
|
||||
give the same outputs for most real-world text. Extensive details are in the
|
||||
[compatibility analysis](comparison/COMPATIBILITY_ANALYSIS.md).
|
||||
|
||||
## Invalid UTF-8
|
||||
|
||||
This package does not validate UTF-8. If you pass invalid UTF-8, the results
|
||||
are undefined. We fuzz against invalid UTF-8 to ensure we don't panic or
|
||||
loop indefinitely.
|
||||
|
||||
The `ControlSequences8Bit` option means that we will segment valid 8-bit
|
||||
control sequences, which are typically _not_ valid UTF-8. 8-bit control bytes
|
||||
happen to also be UTF-8 continuation bytes. Use with caution.
|
||||
|
||||
## Prior Art
|
||||
|
||||
[mattn/go-runewidth](https://github.com/mattn/go-runewidth)
|
||||
|
||||
+2
@@ -45,6 +45,7 @@ func StringGraphemes(s string) Graphemes[string] {
|
||||
func (options Options) StringGraphemes(s string) Graphemes[string] {
|
||||
g := graphemes.FromString(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
|
||||
|
||||
return Graphemes[string]{iter: g, options: options}
|
||||
}
|
||||
@@ -66,6 +67,7 @@ func BytesGraphemes(s []byte) Graphemes[[]byte] {
|
||||
func (options Options) BytesGraphemes(s []byte) Graphemes[[]byte] {
|
||||
g := graphemes.FromBytes(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
|
||||
|
||||
return Graphemes[[]byte]{iter: g, options: options}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package displaywidth
|
||||
|
||||
// Options allows you to specify the treatment of ambiguous East Asian
|
||||
// characters and ANSI escape sequences.
|
||||
type Options struct {
|
||||
// EastAsianWidth specifies whether to treat ambiguous East Asian characters
|
||||
// as width 1 or 2. When false (default), ambiguous East Asian characters
|
||||
// are treated as width 1. When true, they are width 2.
|
||||
EastAsianWidth bool
|
||||
|
||||
// ControlSequences specifies whether to ignore 7-bit ECMA-48 escape sequences
|
||||
// when calculating the display width. When false (default), ANSI escape
|
||||
// sequences are treated as just a series of characters. When true, they are
|
||||
// treated as a single zero-width unit.
|
||||
ControlSequences bool
|
||||
// ControlSequences8Bit specifies whether to ignore 8-bit ECMA-48 escape sequences
|
||||
// when calculating the display width. When false (default), these are treated
|
||||
// as just a series of characters. When true, they are treated as a single
|
||||
// zero-width unit.
|
||||
ControlSequences8Bit bool
|
||||
}
|
||||
|
||||
// DefaultOptions is the default options for the display width
|
||||
// calculation, which is EastAsianWidth false, ControlSequences false, and
|
||||
// ControlSequences8Bit false.
|
||||
var DefaultOptions = Options{
|
||||
EastAsianWidth: false,
|
||||
ControlSequences: false,
|
||||
ControlSequences8Bit: false,
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package displaywidth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/clipperhouse/uax29/v2/graphemes"
|
||||
)
|
||||
|
||||
// TruncateString truncates a string to the given maxWidth, and appends the
|
||||
// given tail if the string is truncated.
|
||||
//
|
||||
// It ensures the visible width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
//
|
||||
// When [Options.ControlSequences] is true, 7-bit ANSI escape sequences that
|
||||
// appear after the truncation point are preserved in the output. This ensures
|
||||
// that escape sequences such as SGR resets are not lost, preventing color
|
||||
// bleed in terminal output.
|
||||
//
|
||||
// [Options.ControlSequences8Bit] is ignored by truncation. 8-bit C1 byte values
|
||||
// (0x80-0x9F) overlap with UTF-8 multi-byte encoding, so manipulating them
|
||||
// during truncation can shift byte boundaries and form unintended visible
|
||||
// characters. Use [Options.String] or [Options.Bytes] for 8-bit-aware width
|
||||
// measurement.
|
||||
func (options Options) TruncateString(s string, maxWidth int, tail string) string {
|
||||
// We deliberately ignore ControlSequences8Bit for truncation, see above.
|
||||
options.ControlSequences8Bit = false
|
||||
|
||||
maxWidthWithoutTail := maxWidth - options.String(tail)
|
||||
|
||||
var pos, total int
|
||||
g := graphemes.FromString(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for g.Next() {
|
||||
gw := graphemeWidth(g.Value(), options)
|
||||
if total+gw <= maxWidthWithoutTail {
|
||||
pos = g.End()
|
||||
}
|
||||
total += gw
|
||||
if total > maxWidth {
|
||||
if options.ControlSequences {
|
||||
// Build result with trailing 7-bit ANSI escape sequences preserved
|
||||
var b strings.Builder
|
||||
b.Grow(len(s) + len(tail)) // at most original + tail
|
||||
b.WriteString(s[:pos])
|
||||
b.WriteString(tail)
|
||||
|
||||
rem := graphemes.FromString(s[pos:])
|
||||
rem.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for rem.Next() {
|
||||
v := rem.Value()
|
||||
// Only preserve 7-bit escapes (ESC = 0x1B) that measure
|
||||
// as zero-width on their own; some sequences (e.g. SOS)
|
||||
// are only valid in their original context.
|
||||
if len(v) > 0 && v[0] == 0x1B && options.String(v) == 0 {
|
||||
b.WriteString(v)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
return s[:pos] + tail
|
||||
}
|
||||
}
|
||||
// No truncation
|
||||
return s
|
||||
}
|
||||
|
||||
// TruncateString truncates a string to the given maxWidth, and appends the
|
||||
// given tail if the string is truncated.
|
||||
//
|
||||
// It ensures the total width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
func TruncateString(s string, maxWidth int, tail string) string {
|
||||
return DefaultOptions.TruncateString(s, maxWidth, tail)
|
||||
}
|
||||
|
||||
// TruncateBytes truncates a []byte to the given maxWidth, and appends the
|
||||
// given tail if the []byte is truncated.
|
||||
//
|
||||
// It ensures the visible width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
//
|
||||
// When [Options.ControlSequences] is true, 7-bit ANSI escape sequences that
|
||||
// appear after the truncation point are preserved in the output. This ensures
|
||||
// that escape sequences such as SGR resets are not lost, preventing color
|
||||
// bleed in terminal output.
|
||||
//
|
||||
// [Options.ControlSequences8Bit] is ignored by truncation. 8-bit C1 byte values
|
||||
// (0x80-0x9F) overlap with UTF-8 multi-byte encoding, so manipulating them
|
||||
// during truncation can shift byte boundaries and form unintended visible
|
||||
// characters. Use [Options.String] or [Options.Bytes] for 8-bit-aware width
|
||||
// measurement.
|
||||
func (options Options) TruncateBytes(s []byte, maxWidth int, tail []byte) []byte {
|
||||
// We deliberately ignore ControlSequences8Bit for truncation, see above.
|
||||
options.ControlSequences8Bit = false
|
||||
|
||||
maxWidthWithoutTail := maxWidth - options.Bytes(tail)
|
||||
|
||||
var pos, total int
|
||||
g := graphemes.FromBytes(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for g.Next() {
|
||||
gw := graphemeWidth(g.Value(), options)
|
||||
if total+gw <= maxWidthWithoutTail {
|
||||
pos = g.End()
|
||||
}
|
||||
total += gw
|
||||
if total > maxWidth {
|
||||
if options.ControlSequences {
|
||||
// Build result with trailing 7-bit ANSI escape sequences preserved
|
||||
result := make([]byte, 0, len(s)+len(tail)) // at most original + tail
|
||||
result = append(result, s[:pos]...)
|
||||
result = append(result, tail...)
|
||||
|
||||
rem := graphemes.FromBytes(s[pos:])
|
||||
rem.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for rem.Next() {
|
||||
v := rem.Value()
|
||||
// Only preserve 7-bit escapes (ESC = 0x1B) that measure
|
||||
// as zero-width on their own; some sequences (e.g. SOS)
|
||||
// are only valid in their original context.
|
||||
if len(v) > 0 && v[0] == 0x1B && options.Bytes(v) == 0 {
|
||||
result = append(result, v...)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
result := make([]byte, 0, pos+len(tail))
|
||||
result = append(result, s[:pos]...)
|
||||
result = append(result, tail...)
|
||||
return result
|
||||
}
|
||||
}
|
||||
// No truncation
|
||||
return s
|
||||
}
|
||||
|
||||
// TruncateBytes truncates a []byte to the given maxWidth, and appends the
|
||||
// given tail if the []byte is truncated.
|
||||
//
|
||||
// It ensures the total width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
func TruncateBytes(s []byte, maxWidth int, tail []byte) []byte {
|
||||
return DefaultOptions.TruncateBytes(s, maxWidth, tail)
|
||||
}
|
||||
+14
-142
@@ -1,35 +1,11 @@
|
||||
package displaywidth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/clipperhouse/uax29/v2/graphemes"
|
||||
)
|
||||
|
||||
// Options allows you to specify the treatment of ambiguous East Asian
|
||||
// characters and ANSI escape sequences.
|
||||
type Options struct {
|
||||
// EastAsianWidth specifies whether to treat ambiguous East Asian characters
|
||||
// as width 1 or 2. When false (default), ambiguous East Asian characters
|
||||
// are treated as width 1. When true, they are width 2.
|
||||
EastAsianWidth bool
|
||||
|
||||
// ControlSequences specifies whether to ignore ECMA-48 escape sequences
|
||||
// when calculating the display width. When false (default), ANSI escape
|
||||
// sequences are treated as just a series of characters. When true, they are
|
||||
// treated as a single zero-width unit.
|
||||
//
|
||||
// Note that this option is about *sequences*. Individual control characters
|
||||
// are already treated as zero-width. With this option, ANSI sequences such as
|
||||
// "\x1b[31m" and "\x1b[0m" do not count towards the width of a string.
|
||||
ControlSequences bool
|
||||
}
|
||||
|
||||
// DefaultOptions is the default options for the display width
|
||||
// calculation, which is EastAsianWidth false and ControlSequences false.
|
||||
var DefaultOptions = Options{EastAsianWidth: false, ControlSequences: false}
|
||||
|
||||
// String calculates the display width of a string,
|
||||
// by iterating over grapheme clusters in the string
|
||||
// and summing their widths.
|
||||
@@ -55,6 +31,7 @@ func (options Options) String(s string) int {
|
||||
// Not ASCII, use grapheme parsing
|
||||
g := graphemes.FromString(s[pos:])
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
|
||||
|
||||
start := pos
|
||||
|
||||
@@ -105,6 +82,7 @@ func (options Options) Bytes(s []byte) int {
|
||||
// Not ASCII, use grapheme parsing
|
||||
g := graphemes.FromBytes(s[pos:])
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
g.AnsiEscapeSequences8Bit = options.ControlSequences8Bit
|
||||
|
||||
start := pos
|
||||
|
||||
@@ -166,128 +144,22 @@ func (options Options) Rune(r rune) int {
|
||||
|
||||
const _Default property = 0
|
||||
|
||||
// TruncateString truncates a string to the given maxWidth, and appends the
|
||||
// given tail if the string is truncated.
|
||||
//
|
||||
// It ensures the visible width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
//
|
||||
// When [Options.ControlSequences] is true, ANSI escape sequences that appear
|
||||
// after the truncation point are preserved in the output. This ensures that
|
||||
// escape sequences such as SGR resets are not lost, preventing color bleed
|
||||
// in terminal output.
|
||||
func (options Options) TruncateString(s string, maxWidth int, tail string) string {
|
||||
maxWidthWithoutTail := maxWidth - options.String(tail)
|
||||
|
||||
var pos, total int
|
||||
g := graphemes.FromString(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for g.Next() {
|
||||
gw := graphemeWidth(g.Value(), options)
|
||||
if total+gw <= maxWidthWithoutTail {
|
||||
pos = g.End()
|
||||
}
|
||||
total += gw
|
||||
if total > maxWidth {
|
||||
if options.ControlSequences {
|
||||
// Build result with trailing ANSI escape sequences preserved
|
||||
var b strings.Builder
|
||||
b.Grow(len(s) + len(tail)) // at most original + tail
|
||||
b.WriteString(s[:pos])
|
||||
b.WriteString(tail)
|
||||
rem := graphemes.FromString(s[pos:])
|
||||
rem.AnsiEscapeSequences = true
|
||||
for rem.Next() {
|
||||
v := rem.Value()
|
||||
if len(v) > 0 && v[0] == 0x1B {
|
||||
b.WriteString(v)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
return s[:pos] + tail
|
||||
}
|
||||
}
|
||||
// No truncation
|
||||
return s
|
||||
}
|
||||
|
||||
// TruncateString truncates a string to the given maxWidth, and appends the
|
||||
// given tail if the string is truncated.
|
||||
//
|
||||
// It ensures the total width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
func TruncateString(s string, maxWidth int, tail string) string {
|
||||
return DefaultOptions.TruncateString(s, maxWidth, tail)
|
||||
}
|
||||
|
||||
// TruncateBytes truncates a []byte to the given maxWidth, and appends the
|
||||
// given tail if the []byte is truncated.
|
||||
//
|
||||
// It ensures the visible width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
//
|
||||
// When [Options.ControlSequences] is true, ANSI escape sequences that appear
|
||||
// after the truncation point are preserved in the output. This ensures that
|
||||
// escape sequences such as SGR resets are not lost, preventing color bleed
|
||||
// in terminal output.
|
||||
func (options Options) TruncateBytes(s []byte, maxWidth int, tail []byte) []byte {
|
||||
maxWidthWithoutTail := maxWidth - options.Bytes(tail)
|
||||
|
||||
var pos, total int
|
||||
g := graphemes.FromBytes(s)
|
||||
g.AnsiEscapeSequences = options.ControlSequences
|
||||
|
||||
for g.Next() {
|
||||
gw := graphemeWidth(g.Value(), options)
|
||||
if total+gw <= maxWidthWithoutTail {
|
||||
pos = g.End()
|
||||
}
|
||||
total += gw
|
||||
if total > maxWidth {
|
||||
if options.ControlSequences {
|
||||
// Build result with trailing ANSI escape sequences preserved
|
||||
result := make([]byte, 0, len(s)+len(tail)) // at most original + tail
|
||||
result = append(result, s[:pos]...)
|
||||
result = append(result, tail...)
|
||||
rem := graphemes.FromBytes(s[pos:])
|
||||
rem.AnsiEscapeSequences = true
|
||||
for rem.Next() {
|
||||
v := rem.Value()
|
||||
if len(v) > 0 && v[0] == 0x1B {
|
||||
result = append(result, v...)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
result := make([]byte, 0, pos+len(tail))
|
||||
result = append(result, s[:pos]...)
|
||||
result = append(result, tail...)
|
||||
return result
|
||||
}
|
||||
}
|
||||
// No truncation
|
||||
return s
|
||||
}
|
||||
|
||||
// TruncateBytes truncates a []byte to the given maxWidth, and appends the
|
||||
// given tail if the []byte is truncated.
|
||||
//
|
||||
// It ensures the total width, including the width of the tail, is less than or
|
||||
// equal to maxWidth.
|
||||
func TruncateBytes(s []byte, maxWidth int, tail []byte) []byte {
|
||||
return DefaultOptions.TruncateBytes(s, maxWidth, tail)
|
||||
}
|
||||
|
||||
// graphemeWidth returns the display width of a grapheme cluster.
|
||||
// The passed string must be a single grapheme cluster.
|
||||
func graphemeWidth[T ~string | []byte](s T, options Options) int {
|
||||
// Optimization: no need to look up properties
|
||||
switch len(s) {
|
||||
case 0:
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
case 1:
|
||||
}
|
||||
|
||||
// C1 controls (0x80-0x9F) are zero-width when 8-bit control sequences
|
||||
// are enabled. This must be checked before the single-byte optimization
|
||||
// below, which would otherwise return width 1 for these bytes.
|
||||
if options.ControlSequences8Bit && s[0] >= 0x80 && s[0] <= 0x9F {
|
||||
return 0
|
||||
}
|
||||
|
||||
// Optimization: single-byte graphemes need no property lookup
|
||||
if len(s) == 1 {
|
||||
return asciiWidth(s[0])
|
||||
}
|
||||
|
||||
|
||||
+42
-18
@@ -7,18 +7,17 @@ An implementation of grapheme cluster boundaries from [Unicode text segmentation
|
||||
## Quick start
|
||||
|
||||
```
|
||||
go get "github.com/clipperhouse/uax29/v2/graphemes"
|
||||
go get github.com/clipperhouse/uax29/v2/graphemes
|
||||
```
|
||||
|
||||
```go
|
||||
import "github.com/clipperhouse/uax29/v2/graphemes"
|
||||
|
||||
text := "Hello, 世界. Nice dog! 👍🐶"
|
||||
g := graphemes.FromString(text)
|
||||
|
||||
tokens := graphemes.FromString(text)
|
||||
|
||||
for tokens.Next() { // Next() returns true until end of data
|
||||
fmt.Println(tokens.Value()) // Do something with the current grapheme
|
||||
for g.Next() { // Next() returns true until end of data
|
||||
fmt.Println(g.Value()) // Do something with the current grapheme
|
||||
}
|
||||
```
|
||||
|
||||
@@ -37,11 +36,10 @@ We use the Unicode [test suite](https://unicode.org/reports/tr41/tr41-36.html#Te
|
||||
|
||||
```go
|
||||
text := "Hello, 世界. Nice dog! 👍🐶"
|
||||
g := graphemes.FromString(text)
|
||||
|
||||
tokens := graphemes.FromString(text)
|
||||
|
||||
for tokens.Next() { // Next() returns true until end of data
|
||||
fmt.Println(tokens.Value()) // Do something with the current grapheme
|
||||
for g.Next() { // Next() returns true until end of data
|
||||
fmt.Println(g.Value()) // Do something with the current grapheme
|
||||
}
|
||||
```
|
||||
|
||||
@@ -50,15 +48,15 @@ for tokens.Next() { // Next() returns true until end of data
|
||||
`FromReader` embeds a [`bufio.Scanner`](https://pkg.go.dev/bufio#Scanner), so just use those methods.
|
||||
|
||||
```go
|
||||
r := getYourReader() // from a file or network maybe
|
||||
tokens := graphemes.FromReader(r)
|
||||
r := getYourReader() // from a file or network maybe
|
||||
g := graphemes.FromReader(r)
|
||||
|
||||
for tokens.Scan() { // Scan() returns true until error or EOF
|
||||
fmt.Println(tokens.Text()) // Do something with the current grapheme
|
||||
for g.Scan() { // Scan() returns true until error or EOF
|
||||
fmt.Println(g.Text()) // Do something with the current grapheme
|
||||
}
|
||||
|
||||
if tokens.Err() != nil { // Check the error
|
||||
log.Fatal(tokens.Err())
|
||||
if g.Err() != nil { // Check the error
|
||||
log.Fatal(g.Err())
|
||||
}
|
||||
```
|
||||
|
||||
@@ -67,13 +65,39 @@ if tokens.Err() != nil { // Check the error
|
||||
```go
|
||||
b := []byte("Hello, 世界. Nice dog! 👍🐶")
|
||||
|
||||
tokens := graphemes.FromBytes(b)
|
||||
g := graphemes.FromBytes(b)
|
||||
|
||||
for tokens.Next() { // Next() returns true until end of data
|
||||
fmt.Println(tokens.Value()) // Do something with the current grapheme
|
||||
for g.Next() { // Next() returns true until end of data
|
||||
fmt.Println(g.Value()) // Do something with the current grapheme
|
||||
}
|
||||
```
|
||||
|
||||
### ANSI escape sequences
|
||||
|
||||
By the UAX 29 specification, ANSI escape sequences are not grapheme clusters. To treat 7-bit ANSI escape sequences as a single cluster, set `AnsiEscapeSequences` to true.
|
||||
|
||||
```go
|
||||
text := "Hello, \x1b[31mworld\x1b[0m!"
|
||||
g := graphemes.FromString(text)
|
||||
g.AnsiEscapeSequences = true
|
||||
|
||||
for g.Next() {
|
||||
fmt.Println(g.Value())
|
||||
}
|
||||
```
|
||||
|
||||
To also parse 8-bit C1 controls (non-UTF-8 bytes), set `AnsiEscapeSequences8Bit` to true.
|
||||
|
||||
```go
|
||||
g.AnsiEscapeSequences = true // 7-bit forms (ESC ...)
|
||||
g.AnsiEscapeSequences8Bit = true // 8-bit C1 forms (0x80-0x9F), not valid UTF-8
|
||||
```
|
||||
|
||||
For ESC-initiated (7-bit) control strings, only 7-bit terminators are recognized.
|
||||
For C1-initiated (8-bit) control strings, only C1 ST (`0x9C`) is recognized as ST.
|
||||
|
||||
We implement [ECMA-48](https://ecma-international.org/publications-and-standards/standards/ecma-48/) control codes in both 7-bit and 8-bit representations. 8-bit control codes are not UTF-8 encoded and are not valid UTF-8, caveat emptor.
|
||||
|
||||
### Benchmarks
|
||||
|
||||
```
|
||||
|
||||
+48
-29
@@ -1,46 +1,43 @@
|
||||
package graphemes
|
||||
|
||||
// ansiEscapeLength returns the byte length of a valid ANSI escape sequence at the
|
||||
// start of data, or 0 if none. Input is UTF-8; only 7-bit ESC sequences are
|
||||
// recognized (C1 0x80–0x9F can be UTF-8 continuation bytes).
|
||||
// ansiEscapeLength returns the byte length of a valid 7-bit ANSI escape
|
||||
// sequence at the start of data, or 0 if none.
|
||||
//
|
||||
// Recognized forms (ECMA-48 / ISO 6429):
|
||||
// - CSI: ESC [ then parameter bytes (0x30–0x3F), intermediate (0x20–0x2F), final (0x40–0x7E)
|
||||
// - OSC: ESC ] then payload until ST (ESC \) or BEL (0x07)
|
||||
// - DCS, SOS, PM, APC: ESC P / X / ^ / _ then payload until ST (ESC \)
|
||||
// - Two-byte: ESC + Fe (0x40–0x5F excluding above), or Fp (0x30–0x3F), or nF (0x20–0x2F then final)
|
||||
// - CSI: ESC [ then parameter bytes (0x30-0x3F), intermediate (0x20-0x2F), final (0x40-0x7E)
|
||||
// - OSC: ESC ] then payload until BEL (0x07), 7-bit ST (ESC \), CAN (0x18), or SUB (0x1A)
|
||||
// - DCS, SOS, PM, APC: ESC P/X/^/_ then payload until 7-bit ST (ESC \), CAN, or SUB
|
||||
// - Two-byte: ESC + Fe/Fs (0x40-0x7E excluding above), or Fp (0x30-0x3F), or nF (0x20-0x2F then final)
|
||||
func ansiEscapeLength[T ~string | ~[]byte](data T) int {
|
||||
n := len(data)
|
||||
if n < 2 {
|
||||
return 0
|
||||
}
|
||||
if data[0] != esc {
|
||||
if n < 2 || data[0] != esc {
|
||||
return 0
|
||||
}
|
||||
|
||||
b1 := data[1]
|
||||
switch b1 {
|
||||
case '[': // CSI
|
||||
body := csiLength(data[2:])
|
||||
body := csiBodyLength(data[2:])
|
||||
if body == 0 {
|
||||
return 0
|
||||
}
|
||||
return 2 + body
|
||||
case ']': // OSC – allows BEL or ST as terminator
|
||||
case ']': // OSC - allows BEL or 7-bit ST terminator
|
||||
body := oscLength(data[2:])
|
||||
if body == 0 {
|
||||
if body < 0 {
|
||||
return 0
|
||||
}
|
||||
return 2 + body
|
||||
case 'P', 'X', '^', '_': // DCS, SOS, PM, APC – require ST (ESC \) only
|
||||
case 'P', 'X', '^', '_': // DCS, SOS, PM, APC
|
||||
body := stSequenceLength(data[2:])
|
||||
if body == 0 {
|
||||
if body < 0 {
|
||||
return 0
|
||||
}
|
||||
return 2 + body
|
||||
}
|
||||
if b1 >= 0x40 && b1 <= 0x5F {
|
||||
// Fe (C1) two-byte; [ ] P X ^ _ handled above
|
||||
|
||||
if b1 >= 0x40 && b1 <= 0x7E {
|
||||
// Fe/Fs two-byte; [ ] P X ^ _ handled above
|
||||
return 2
|
||||
}
|
||||
if b1 >= 0x30 && b1 <= 0x3F {
|
||||
@@ -48,7 +45,7 @@ func ansiEscapeLength[T ~string | ~[]byte](data T) int {
|
||||
return 2
|
||||
}
|
||||
if b1 >= 0x20 && b1 <= 0x2F {
|
||||
// nF: intermediates then one final (0x30–0x7E)
|
||||
// nF: intermediates then one final (0x30-0x7E)
|
||||
i := 2
|
||||
for i < n && data[i] >= 0x20 && data[i] <= 0x2F {
|
||||
i++
|
||||
@@ -58,17 +55,18 @@ func ansiEscapeLength[T ~string | ~[]byte](data T) int {
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
// csiLength returns the length of the CSI body (param/intermediate/final bytes).
|
||||
// csiBodyLength returns the length of the CSI body (param/intermediate/final bytes).
|
||||
// data is the slice after "ESC [".
|
||||
// Per ECMA-48, the CSI body has the form:
|
||||
//
|
||||
// parameters (0x30–0x3F)*, intermediates (0x20–0x2F)*, final (0x40–0x7E)
|
||||
//
|
||||
// Once an intermediate byte is seen, subsequent parameter bytes are invalid.
|
||||
func csiLength[T ~string | ~[]byte](data T) int {
|
||||
func csiBodyLength[T ~string | ~[]byte](data T) int {
|
||||
seenIntermediate := false
|
||||
for i := 0; i < len(data); i++ {
|
||||
b := data[i]
|
||||
@@ -90,30 +88,51 @@ func csiLength[T ~string | ~[]byte](data T) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
// oscLength returns the length of the OSC body up to and including
|
||||
// the terminator. OSC accepts either BEL (0x07) or ST (ESC \) per
|
||||
// widespread terminal convention. data is the slice after "ESC ]".
|
||||
// oscLength returns the length of the OSC body.
|
||||
// data is the slice after "ESC ]".
|
||||
//
|
||||
// Returns:
|
||||
// - n >= 0: consumed body length (includes BEL/ST terminator when present)
|
||||
// - -1: not terminated in the provided data
|
||||
//
|
||||
// OSC accepts BEL (0x07) or 7-bit ST (ESC \) as terminators by widespread convention.
|
||||
// Per ECMA-48, CAN (0x18) and SUB (0x1A) cancel the control string; in that
|
||||
// case they are not part of the OSC sequence length.
|
||||
func oscLength[T ~string | ~[]byte](data T) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
b := data[i]
|
||||
if b == bel {
|
||||
return i + 1
|
||||
}
|
||||
if b == can || b == sub {
|
||||
return i
|
||||
}
|
||||
if b == esc && i+1 < len(data) && data[i+1] == '\\' {
|
||||
return i + 2
|
||||
}
|
||||
}
|
||||
return 0
|
||||
return -1
|
||||
}
|
||||
|
||||
// stSequenceLength returns the length of a control-string body up to and
|
||||
// including the ST (ESC \) terminator. Used for DCS, SOS, PM, and APC, which
|
||||
// per ECMA-48 require ST and do not accept BEL. data is the slice after "ESC x".
|
||||
// stSequenceLength returns the length of a control-string body.
|
||||
// data is the slice after "ESC x".
|
||||
//
|
||||
// Returns:
|
||||
// - n >= 0: consumed body length (includes ST terminator when present)
|
||||
// - -1: not terminated in the provided data
|
||||
//
|
||||
// Used for DCS, SOS, PM, and APC, which per ECMA-48 terminate with ST.
|
||||
// ST here is the 7-bit form (ESC \).
|
||||
// CAN (0x18) and SUB (0x1A) cancel the control string; in that case they are
|
||||
// not part of the sequence length.
|
||||
func stSequenceLength[T ~string | ~[]byte](data T) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
if data[i] == can || data[i] == sub {
|
||||
return i
|
||||
}
|
||||
if data[i] == esc && i+1 < len(data) && data[i+1] == '\\' {
|
||||
return i + 2
|
||||
}
|
||||
}
|
||||
return 0
|
||||
return -1
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package graphemes
|
||||
|
||||
// ansiEscapeLength8Bit returns the byte length of a valid 8-bit C1 ANSI
|
||||
// sequence at the start of data, or 0 if none.
|
||||
//
|
||||
// Recognized forms (ECMA-48 / ISO 6429):
|
||||
// - C1 CSI (0x9B) body as parameter/intermediate/final bytes
|
||||
// - C1 OSC (0x9D) body terminated by BEL, C1 ST, CAN, or SUB
|
||||
// - C1 DCS/SOS/PM/APC (0x90/0x98/0x9E/0x9F) body terminated by C1 ST, CAN, or SUB
|
||||
// - Standalone C1 controls (0x80..0x9F not listed above): single byte
|
||||
func ansiEscapeLength8Bit[T ~string | ~[]byte](data T) int {
|
||||
if len(data) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
switch data[0] {
|
||||
case 0x9B: // C1 CSI
|
||||
body := csiBodyLength(data[1:])
|
||||
if body == 0 {
|
||||
return 0
|
||||
}
|
||||
return 1 + body
|
||||
case 0x9D: // C1 OSC
|
||||
body := oscLengthC1(data[1:])
|
||||
if body < 0 {
|
||||
return 0
|
||||
}
|
||||
return 1 + body
|
||||
case 0x90, 0x98, 0x9E, 0x9F: // C1 DCS, SOS, PM, APC
|
||||
body := stSequenceLengthC1(data[1:])
|
||||
if body < 0 {
|
||||
return 0
|
||||
}
|
||||
return 1 + body
|
||||
default:
|
||||
if data[0] >= 0x80 && data[0] <= 0x9F {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
// oscLengthC1 returns the length of a C1 OSC body.
|
||||
// data is the slice after the C1 OSC initiator (0x9D).
|
||||
//
|
||||
// Returns:
|
||||
// - n >= 0: consumed body length (includes BEL/ST terminator when present)
|
||||
// - -1: not terminated in the provided data
|
||||
//
|
||||
// Terminators: BEL (0x07) or C1 ST (0x9C).
|
||||
// CAN (0x18) and SUB (0x1A) cancel the control string.
|
||||
func oscLengthC1[T ~string | ~[]byte](data T) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
b := data[i]
|
||||
if b == bel || b == st {
|
||||
return i + 1
|
||||
}
|
||||
if b == can || b == sub {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// stSequenceLengthC1 parses DCS/SOS/PM/APC bodies that terminate with C1 ST
|
||||
// (0x9C), or are canceled by CAN/SUB.
|
||||
func stSequenceLengthC1[T ~string | ~[]byte](data T) int {
|
||||
for i := 0; i < len(data); i++ {
|
||||
b := data[i]
|
||||
if b == can || b == sub {
|
||||
return i
|
||||
}
|
||||
if b == st {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
+23
-6
@@ -27,9 +27,18 @@ type Iterator[T ~string | ~[]byte] struct {
|
||||
data T
|
||||
pos int
|
||||
start int
|
||||
// AnsiEscapeSequences treats ANSI escape sequences (ECMA-48) as single grapheme
|
||||
// clusters when true. Default is false.
|
||||
// AnsiEscapeSequences treats 7-bit ANSI escape sequences (ECMA-48) as
|
||||
// single grapheme clusters when true. The default is false.
|
||||
//
|
||||
// 8-bit controls are not enabled by this option. See [AnsiEscapeSequences8Bit].
|
||||
AnsiEscapeSequences bool
|
||||
// AnsiEscapeSequences8Bit treats 8-bit C1 ANSI escape sequences (ECMA-48) as single
|
||||
// grapheme clusters when true. The default is false.
|
||||
//
|
||||
// 8-bit control bytes are not UTF-8 encoded, i.e. not valid UTF-8. If you
|
||||
// choose this option, you are choosing to interpret non-UTF-8 data, caveat
|
||||
// emptor.
|
||||
AnsiEscapeSequences8Bit bool
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -41,6 +50,9 @@ const (
|
||||
esc = 0x1B
|
||||
cr = 0x0D
|
||||
bel = 0x07
|
||||
can = 0x18
|
||||
sub = 0x1A
|
||||
st = 0x9C
|
||||
)
|
||||
|
||||
// Next advances the iterator to the next grapheme cluster.
|
||||
@@ -51,16 +63,21 @@ func (iter *Iterator[T]) Next() bool {
|
||||
}
|
||||
iter.start = iter.pos
|
||||
|
||||
if iter.AnsiEscapeSequences && iter.data[iter.pos] == esc {
|
||||
b := iter.data[iter.pos]
|
||||
if iter.AnsiEscapeSequences && b == esc {
|
||||
if a := ansiEscapeLength(iter.data[iter.pos:]); a > 0 {
|
||||
iter.pos += a
|
||||
return true
|
||||
}
|
||||
}
|
||||
if iter.AnsiEscapeSequences8Bit && b >= 0x80 && b <= 0x9F {
|
||||
if a := ansiEscapeLength8Bit(iter.data[iter.pos:]); a > 0 {
|
||||
iter.pos += a
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// ASCII hot path: any ASCII is one grapheme when next byte is ASCII or end.
|
||||
// Fall through on CR so splitfunc can handle CR+LF as a single cluster.
|
||||
b := iter.data[iter.pos]
|
||||
if b < utf8.RuneSelf && b != cr {
|
||||
if iter.pos+1 >= len(iter.data) || iter.data[iter.pos+1] < utf8.RuneSelf {
|
||||
iter.pos++
|
||||
@@ -68,7 +85,7 @@ func (iter *Iterator[T]) Next() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to actual grapheme parsing
|
||||
// Fall back to UAX29 grapheme parsing
|
||||
remaining := iter.data[iter.pos:]
|
||||
advance, _, err := iter.split(remaining, true)
|
||||
if err != nil {
|
||||
|
||||
+4
-2
@@ -1,5 +1,7 @@
|
||||
language: go
|
||||
|
||||
arch:
|
||||
- AMD64
|
||||
- ppc64le
|
||||
go:
|
||||
- 1.9
|
||||
- tip
|
||||
- tip
|
||||
+93
-2
@@ -4,10 +4,17 @@ Regexp2 is a feature-rich RegExp engine for Go. It doesn't have constant time g
|
||||
## Basis of the engine
|
||||
The engine is ported from the .NET framework's System.Text.RegularExpressions.Regex engine. That engine was open sourced in 2015 under the MIT license. There are some fundamental differences between .NET strings and Go strings that required a bit of borrowing from the Go framework regex engine as well. I cleaned up a couple of the dirtier bits during the port (regexcharclass.cs was terrible), but the parse tree, code emmitted, and therefore patterns matched should be identical.
|
||||
|
||||
## New Code Generation
|
||||
For extra performance use `regexp2` with [`regexp2cg`](https://github.com/dlclark/regexp2cg). It is a code generation utility for `regexp2` and you can likely improve your regexp runtime performance by 3-10x in hot code paths. As always you should benchmark your specifics to confirm the results. Give it a try!
|
||||
|
||||
## Installing
|
||||
This is a go-gettable library, so install is easy:
|
||||
|
||||
go get github.com/dlclark/regexp2/...
|
||||
go get github.com/dlclark/regexp2
|
||||
|
||||
To use the new Code Generation (while it's in beta) you'll need to use the `code_gen` branch:
|
||||
|
||||
go get github.com/dlclark/regexp2@code_gen
|
||||
|
||||
## Usage
|
||||
Usage is similar to the Go `regexp` package. Just like in `regexp`, you start by converting a regex into a state machine via the `Compile` or `MustCompile` methods. They ultimately do the same thing, but `MustCompile` will panic if the regex is invalid. You can then use the provided `Regexp` struct to find matches repeatedly. A `Regexp` struct is safe to use across goroutines.
|
||||
@@ -39,12 +46,30 @@ Group 0 is embedded in the Match. Group 0 is an automatically-assigned group th
|
||||
|
||||
The __last__ capture is embedded in each group, so `g.String()` will return the same thing as `g.Capture.String()` and `g.Captures[len(g.Captures)-1].String()`.
|
||||
|
||||
If you want to find multiple matches from a single input string you should use the `FindNextMatch` method. For example, to implement a function similar to `regexp.FindAllString`:
|
||||
|
||||
```go
|
||||
func regexp2FindAllString(re *regexp2.Regexp, s string) []string {
|
||||
var matches []string
|
||||
m, _ := re.FindStringMatch(s)
|
||||
for m != nil {
|
||||
matches = append(matches, m.String())
|
||||
m, _ = re.FindNextMatch(m)
|
||||
}
|
||||
return matches
|
||||
}
|
||||
```
|
||||
|
||||
`FindNextMatch` is optmized so that it re-uses the underlying string/rune slice.
|
||||
|
||||
The internals of `regexp2` always operate on `[]rune` so `Index` and `Length` data in a `Match` always reference a position in `rune`s rather than `byte`s (even if the input was given as a string). This is a dramatic difference between `regexp` and `regexp2`. It's advisable to use the provided `String()` methods to avoid having to work with indices.
|
||||
|
||||
## Compare `regexp` and `regexp2`
|
||||
| Category | regexp | regexp2 |
|
||||
| --- | --- | --- |
|
||||
| Catastrophic backtracking possible | no, constant execution time guarantees | yes, if your pattern is at risk you can use the `re.MatchTimeout` field |
|
||||
| Python-style capture groups `(?P<name>re)` | yes | no (yes in RE2 compat mode) |
|
||||
| .NET-style capture groups `(?<name>re)` or `(?'name're)` | no | yes |
|
||||
| .NET-style capture groups `(?<name>re)` or `(?'name're)` | yes | yes |
|
||||
| comments `(?#comment)` | no | yes |
|
||||
| branch numbering reset `(?\|a\|b)` | no | no |
|
||||
| possessive match `(?>re)` | no | yes |
|
||||
@@ -62,6 +87,8 @@ The default behavior of `regexp2` is to match the .NET regexp engine, however th
|
||||
* add support for named ascii character classes (e.g. `[[:foo:]]`)
|
||||
* add support for python-style capture groups (e.g. `(P<name>re)`)
|
||||
* change singleline behavior for `$` to only match end of string (like RE2) (see [#24](https://github.com/dlclark/regexp2/issues/24))
|
||||
* change the character classes `\d` `\s` and `\w` to match the same characters as RE2. NOTE: if you also use the `ECMAScript` option then this will change the `\s` character class to match ECMAScript instead of RE2. ECMAScript allows more whitespace characters in `\s` than RE2 (but still fewer than the the default behavior).
|
||||
* allow character escape sequences to have defaults. For example, by default `\_` isn't a known character escape and will fail to compile, but in RE2 mode it will match the literal character `_`
|
||||
|
||||
```go
|
||||
re := regexp2.MustCompile(`Your RE2-compatible pattern`, regexp2.RE2)
|
||||
@@ -72,6 +99,70 @@ if isMatch, _ := re.MatchString(`Something to match`); isMatch {
|
||||
|
||||
This feature is a work in progress and I'm open to ideas for more things to put here (maybe more relaxed character escaping rules?).
|
||||
|
||||
## Catastrophic Backtracking and Timeouts
|
||||
|
||||
`regexp2` supports features that can lead to catastrophic backtracking.
|
||||
`Regexp.MatchTimeout` can be set to to limit the impact of such behavior; the
|
||||
match will fail with an error after approximately MatchTimeout. No timeout
|
||||
checks are done by default.
|
||||
|
||||
Timeout checking is not free. The current timeout checking implementation starts
|
||||
a background worker that updates a clock value approximately once every 100
|
||||
milliseconds. The matching code compares this value against the precomputed
|
||||
deadline for the match. The performance impact is as follows.
|
||||
|
||||
1. A match with a timeout runs almost as fast as a match without a timeout.
|
||||
2. If any live matches have a timeout, there will be a background CPU load
|
||||
(`~0.15%` currently on a modern machine). This load will remain constant
|
||||
regardless of the number of matches done including matches done in parallel.
|
||||
3. If no live matches are using a timeout, the background load will remain
|
||||
until the longest deadline (match timeout + the time when the match started)
|
||||
is reached. E.g., if you set a timeout of one minute the load will persist
|
||||
for approximately a minute even if the match finishes quickly.
|
||||
|
||||
See [PR #58](https://github.com/dlclark/regexp2/pull/58) for more details and
|
||||
alternatives considered.
|
||||
|
||||
## Goroutine leak error
|
||||
If you're using a library during unit tests (e.g. https://github.com/uber-go/goleak) that validates all goroutines are exited then you'll likely get an error if you or any of your dependencies use regex's with a MatchTimeout.
|
||||
To remedy the problem you'll need to tell the unit test to wait until the backgroup timeout goroutine is exited.
|
||||
|
||||
```go
|
||||
func TestSomething(t *testing.T) {
|
||||
defer goleak.VerifyNone(t)
|
||||
defer regexp2.StopTimeoutClock()
|
||||
|
||||
// ... test
|
||||
}
|
||||
|
||||
//or
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
// setup
|
||||
// ...
|
||||
|
||||
// run
|
||||
m.Run()
|
||||
|
||||
//tear down
|
||||
regexp2.StopTimeoutClock()
|
||||
goleak.VerifyNone(t)
|
||||
}
|
||||
```
|
||||
|
||||
This will add ~100ms runtime to each test (or TestMain). If that's too much time you can set the clock cycle rate of the timeout goroutine in an init function in a test file. `regexp2.SetTimeoutCheckPeriod` isn't threadsafe so it must be setup before starting any regex's with Timeouts.
|
||||
|
||||
```go
|
||||
func init() {
|
||||
//speed up testing by making the timeout clock 1ms
|
||||
regexp2.SetTimeoutCheckPeriod(time.Millisecond)
|
||||
}
|
||||
```
|
||||
|
||||
## ECMAScript compatibility mode
|
||||
In this mode the engine provides compatibility with the [regex engine](https://tc39.es/ecma262/multipage/text-processing.html#sec-regexp-regular-expression-objects) described in the ECMAScript specification.
|
||||
|
||||
Additionally a Unicode mode is provided which allows parsing of `\u{CodePoint}` syntax that is only when both are provided.
|
||||
|
||||
## Library features that I'm still working on
|
||||
- Regex split
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package regexp2
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fasttime holds a time value (ticks since clock initialization)
|
||||
type fasttime int64
|
||||
|
||||
// fastclock provides a fast clock implementation.
|
||||
//
|
||||
// A background goroutine periodically stores the current time
|
||||
// into an atomic variable.
|
||||
//
|
||||
// A deadline can be quickly checked for expiration by comparing
|
||||
// its value to the clock stored in the atomic variable.
|
||||
//
|
||||
// The goroutine automatically stops once clockEnd is reached.
|
||||
// (clockEnd covers the largest deadline seen so far + some
|
||||
// extra time). This ensures that if regexp2 with timeouts
|
||||
// stops being used we will stop background work.
|
||||
type fastclock struct {
|
||||
// instances of atomicTime must be at the start of the struct (or at least 64-bit aligned)
|
||||
// otherwise 32-bit architectures will panic
|
||||
|
||||
current atomicTime // Current time (approximate)
|
||||
clockEnd atomicTime // When clock updater is supposed to stop (>= any existing deadline)
|
||||
|
||||
// current and clockEnd can be read via atomic loads.
|
||||
// Reads and writes of other fields require mu to be held.
|
||||
mu sync.Mutex
|
||||
start time.Time // Time corresponding to fasttime(0)
|
||||
running bool // Is a clock updater running?
|
||||
}
|
||||
|
||||
var fast fastclock
|
||||
|
||||
// reached returns true if current time is at or past t.
|
||||
func (t fasttime) reached() bool {
|
||||
return fast.current.read() >= t
|
||||
}
|
||||
|
||||
// makeDeadline returns a time that is approximately time.Now().Add(d)
|
||||
func makeDeadline(d time.Duration) fasttime {
|
||||
// Increase the deadline since the clock we are reading may be
|
||||
// just about to tick forwards.
|
||||
end := fast.current.read() + durationToTicks(d+clockPeriod)
|
||||
|
||||
// Start or extend clock if necessary.
|
||||
if end > fast.clockEnd.read() {
|
||||
// If time.Since(last use) > timeout, there's a chance that
|
||||
// fast.current will no longer be updated, which can lead to
|
||||
// incorrect 'end' calculations that can trigger a false timeout
|
||||
fast.mu.Lock()
|
||||
if !fast.running && !fast.start.IsZero() {
|
||||
// update fast.current
|
||||
fast.current.write(durationToTicks(time.Since(fast.start)))
|
||||
// recalculate our end value
|
||||
end = fast.current.read() + durationToTicks(d+clockPeriod)
|
||||
}
|
||||
fast.mu.Unlock()
|
||||
extendClock(end)
|
||||
}
|
||||
|
||||
return end
|
||||
}
|
||||
|
||||
// extendClock ensures that clock is live and will run until at least end.
|
||||
func extendClock(end fasttime) {
|
||||
fast.mu.Lock()
|
||||
defer fast.mu.Unlock()
|
||||
|
||||
if fast.start.IsZero() {
|
||||
fast.start = time.Now()
|
||||
}
|
||||
|
||||
// Extend the running time to cover end as well as a bit of slop.
|
||||
if shutdown := end + durationToTicks(time.Second); shutdown > fast.clockEnd.read() {
|
||||
fast.clockEnd.write(shutdown)
|
||||
}
|
||||
|
||||
// Start clock if necessary
|
||||
if !fast.running {
|
||||
fast.running = true
|
||||
go runClock()
|
||||
}
|
||||
}
|
||||
|
||||
// stop the timeout clock in the background
|
||||
// should only used for unit tests to abandon the background goroutine
|
||||
func stopClock() {
|
||||
fast.mu.Lock()
|
||||
if fast.running {
|
||||
fast.clockEnd.write(fasttime(0))
|
||||
}
|
||||
fast.mu.Unlock()
|
||||
|
||||
// pause until not running
|
||||
// get and release the lock
|
||||
isRunning := true
|
||||
for isRunning {
|
||||
time.Sleep(clockPeriod / 2)
|
||||
fast.mu.Lock()
|
||||
isRunning = fast.running
|
||||
fast.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func durationToTicks(d time.Duration) fasttime {
|
||||
// Downscale nanoseconds to approximately a millisecond so that we can avoid
|
||||
// overflow even if the caller passes in math.MaxInt64.
|
||||
return fasttime(d) >> 20
|
||||
}
|
||||
|
||||
const DefaultClockPeriod = 100 * time.Millisecond
|
||||
|
||||
// clockPeriod is the approximate interval between updates of approximateClock.
|
||||
var clockPeriod = DefaultClockPeriod
|
||||
|
||||
func runClock() {
|
||||
fast.mu.Lock()
|
||||
defer fast.mu.Unlock()
|
||||
|
||||
for fast.current.read() <= fast.clockEnd.read() {
|
||||
// Unlock while sleeping.
|
||||
fast.mu.Unlock()
|
||||
time.Sleep(clockPeriod)
|
||||
fast.mu.Lock()
|
||||
|
||||
newTime := durationToTicks(time.Since(fast.start))
|
||||
fast.current.write(newTime)
|
||||
}
|
||||
fast.running = false
|
||||
}
|
||||
|
||||
type atomicTime struct{ v int64 } // Should change to atomic.Int64 when we can use go 1.19
|
||||
|
||||
func (t *atomicTime) read() fasttime { return fasttime(atomic.LoadInt64(&t.v)) }
|
||||
func (t *atomicTime) write(v fasttime) { atomic.StoreInt64(&t.v, int64(v)) }
|
||||
+8
-6
@@ -6,8 +6,9 @@ import (
|
||||
)
|
||||
|
||||
// Match is a single regex result match that contains groups and repeated captures
|
||||
// -Groups
|
||||
// -Capture
|
||||
//
|
||||
// -Groups
|
||||
// -Capture
|
||||
type Match struct {
|
||||
Group //embeded group 0
|
||||
|
||||
@@ -43,10 +44,10 @@ type Group struct {
|
||||
type Capture struct {
|
||||
// the original string
|
||||
text []rune
|
||||
// the position in the original string where the first character of
|
||||
// captured substring was found.
|
||||
// Index is the position in the underlying rune slice where the first character of
|
||||
// captured substring was found. Even if you pass in a string this will be in Runes.
|
||||
Index int
|
||||
// the length of the captured substring.
|
||||
// Length is the number of runes in the captured substring.
|
||||
Length int
|
||||
}
|
||||
|
||||
@@ -187,7 +188,8 @@ func (m *Match) addMatch(c, start, l int) {
|
||||
}
|
||||
|
||||
// Nonpublic builder: Add a capture to balance the specified group. This is used by the
|
||||
// balanced match construct. (?<foo-foo2>...)
|
||||
//
|
||||
// balanced match construct. (?<foo-foo2>...)
|
||||
//
|
||||
// If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(c).
|
||||
// However, since we have backtracking, we need to keep track of everything.
|
||||
|
||||
+44
-4
@@ -18,13 +18,21 @@ import (
|
||||
"github.com/dlclark/regexp2/syntax"
|
||||
)
|
||||
|
||||
// Default timeout used when running regexp matches -- "forever"
|
||||
var DefaultMatchTimeout = time.Duration(math.MaxInt64)
|
||||
var (
|
||||
// DefaultMatchTimeout used when running regexp matches -- "forever"
|
||||
DefaultMatchTimeout = time.Duration(math.MaxInt64)
|
||||
// DefaultUnmarshalOptions used when unmarshaling a regex from text
|
||||
DefaultUnmarshalOptions = None
|
||||
)
|
||||
|
||||
// Regexp is the representation of a compiled regular expression.
|
||||
// A Regexp is safe for concurrent use by multiple goroutines.
|
||||
type Regexp struct {
|
||||
//timeout when trying to find matches
|
||||
// A match will time out if it takes (approximately) more than
|
||||
// MatchTimeout. This is a safety check in case the match
|
||||
// encounters catastrophic backtracking. The default value
|
||||
// (DefaultMatchTimeout) causes all time out checking to be
|
||||
// suppressed.
|
||||
MatchTimeout time.Duration
|
||||
|
||||
// read-only after Compile
|
||||
@@ -39,7 +47,7 @@ type Regexp struct {
|
||||
code *syntax.Code // compiled program
|
||||
|
||||
// cache of machines for running regexp
|
||||
muRun sync.Mutex
|
||||
muRun *sync.Mutex
|
||||
runner []*runner
|
||||
}
|
||||
|
||||
@@ -68,6 +76,7 @@ func Compile(expr string, opt RegexOptions) (*Regexp, error) {
|
||||
capsize: code.Capsize,
|
||||
code: code,
|
||||
MatchTimeout: DefaultMatchTimeout,
|
||||
muRun: &sync.Mutex{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -92,6 +101,19 @@ func Unescape(input string) (string, error) {
|
||||
return syntax.Unescape(input)
|
||||
}
|
||||
|
||||
// SetTimeoutPeriod is a debug function that sets the frequency of the timeout goroutine's sleep cycle.
|
||||
// Defaults to 100ms. The only benefit of setting this lower is that the 1 background goroutine that manages
|
||||
// timeouts may exit slightly sooner after all the timeouts have expired. See Github issue #63
|
||||
func SetTimeoutCheckPeriod(d time.Duration) {
|
||||
clockPeriod = d
|
||||
}
|
||||
|
||||
// StopTimeoutClock should only be used in unit tests to prevent the timeout clock goroutine
|
||||
// from appearing like a leaking goroutine
|
||||
func StopTimeoutClock() {
|
||||
stopClock()
|
||||
}
|
||||
|
||||
// String returns the source text used to compile the regular expression.
|
||||
func (re *Regexp) String() string {
|
||||
return re.pattern
|
||||
@@ -121,6 +143,7 @@ const (
|
||||
Debug = 0x0080 // "d"
|
||||
ECMAScript = 0x0100 // "e"
|
||||
RE2 = 0x0200 // RE2 (regexp package) compatibility mode
|
||||
Unicode = 0x0400 // "u"
|
||||
)
|
||||
|
||||
func (re *Regexp) RightToLeft() bool {
|
||||
@@ -353,3 +376,20 @@ func (re *Regexp) GroupNumberFromName(name string) int {
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
// MarshalText implements [encoding.TextMarshaler]. The output
|
||||
// matches that of calling the [Regexp.String] method.
|
||||
func (re *Regexp) MarshalText() ([]byte, error) {
|
||||
return []byte(re.String()), nil
|
||||
}
|
||||
|
||||
// UnmarshalText implements [encoding.TextUnmarshaler] by calling
|
||||
// [Compile] on the encoded value.
|
||||
func (re *Regexp) UnmarshalText(text []byte) error {
|
||||
newRE, err := Compile(string(text), DefaultUnmarshalOptions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*re = *newRE
|
||||
return nil
|
||||
}
|
||||
+23
-43
@@ -58,10 +58,9 @@ type runner struct {
|
||||
|
||||
runmatch *Match // result object
|
||||
|
||||
ignoreTimeout bool
|
||||
timeout time.Duration // timeout in milliseconds (needed for actual)
|
||||
timeoutChecksToSkip int
|
||||
timeoutAt time.Time
|
||||
ignoreTimeout bool
|
||||
timeout time.Duration // timeout in milliseconds (needed for actual)
|
||||
deadline fasttime
|
||||
|
||||
operator syntax.InstOp
|
||||
codepos int
|
||||
@@ -314,12 +313,9 @@ func (r *runner) execute() error {
|
||||
}
|
||||
} else {
|
||||
// The inner expression found an empty match, so we'll go directly to 'back2' if we
|
||||
// backtrack. In this case, we need to push something on the stack, since back2 pops.
|
||||
// However, in the case of ()+? or similar, this empty match may be legitimate, so push the text
|
||||
// position associated with that empty match.
|
||||
r.stackPush(oldMarkPos)
|
||||
|
||||
r.trackPushNeg1(r.stackPeek()) // Save old mark
|
||||
// backtrack. Don't touch the grouping stack here; instead, record the old mark and
|
||||
// a flag indicating that backtracking doesn't need to pop a grouping stack frame.
|
||||
r.trackPushNeg2(oldMarkPos, 0)
|
||||
}
|
||||
r.advance(1)
|
||||
continue
|
||||
@@ -335,18 +331,22 @@ func (r *runner) execute() error {
|
||||
|
||||
r.trackPopN(2)
|
||||
pos := r.trackPeekN(1)
|
||||
r.trackPushNeg1(r.trackPeek()) // Save old mark
|
||||
r.stackPush(pos) // Make new mark
|
||||
r.textto(pos) // Recall position
|
||||
r.goTo(r.operand(0)) // Loop
|
||||
r.trackPushNeg2(r.trackPeek(), 1) // Save old mark, note that we pushed a new mark
|
||||
r.stackPush(pos) // Make new mark
|
||||
r.textto(pos) // Recall position
|
||||
r.goTo(r.operand(0)) // Loop
|
||||
continue
|
||||
|
||||
case syntax.Lazybranchmark | syntax.Back2:
|
||||
// The lazy loop has failed. We'll do a true backtrack and
|
||||
// start over before the lazy loop.
|
||||
r.stackPop()
|
||||
r.trackPop()
|
||||
r.stackPush(r.trackPeek()) // Recall old mark
|
||||
r.trackPopN(2)
|
||||
oldMark := r.trackPeek()
|
||||
needsPop := r.trackPeekN(1)
|
||||
if needsPop != 0 {
|
||||
r.stackPop()
|
||||
}
|
||||
r.stackPush(oldMark) // Recall old mark
|
||||
break
|
||||
|
||||
case syntax.Setcount:
|
||||
@@ -1551,39 +1551,15 @@ func (r *runner) isECMABoundary(index, startpos, endpos int) bool {
|
||||
(index < endpos && syntax.IsECMAWordChar(r.runtext[index]))
|
||||
}
|
||||
|
||||
// this seems like a comment to justify randomly picking 1000 :-P
|
||||
// We have determined this value in a series of experiments where x86 retail
|
||||
// builds (ono-lab-optimized) were run on different pattern/input pairs. Larger values
|
||||
// of TimeoutCheckFrequency did not tend to increase performance; smaller values
|
||||
// of TimeoutCheckFrequency tended to slow down the execution.
|
||||
const timeoutCheckFrequency int = 1000
|
||||
|
||||
func (r *runner) startTimeoutWatch() {
|
||||
if r.ignoreTimeout {
|
||||
return
|
||||
}
|
||||
|
||||
r.timeoutChecksToSkip = timeoutCheckFrequency
|
||||
r.timeoutAt = time.Now().Add(r.timeout)
|
||||
r.deadline = makeDeadline(r.timeout)
|
||||
}
|
||||
|
||||
func (r *runner) checkTimeout() error {
|
||||
if r.ignoreTimeout {
|
||||
return nil
|
||||
}
|
||||
r.timeoutChecksToSkip--
|
||||
if r.timeoutChecksToSkip != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
r.timeoutChecksToSkip = timeoutCheckFrequency
|
||||
return r.doCheckTimeout()
|
||||
}
|
||||
|
||||
func (r *runner) doCheckTimeout() error {
|
||||
current := time.Now()
|
||||
|
||||
if current.Before(r.timeoutAt) {
|
||||
if r.ignoreTimeout || !r.deadline.reached() {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1629,6 +1605,10 @@ func (re *Regexp) getRunner() *runner {
|
||||
// run using re. (The cache empties when re gets garbage collected.)
|
||||
func (re *Regexp) putRunner(r *runner) {
|
||||
re.muRun.Lock()
|
||||
r.runtext = nil
|
||||
if r.runmatch != nil {
|
||||
r.runmatch.text = nil
|
||||
}
|
||||
re.runner = append(re.runner, r)
|
||||
re.muRun.Unlock()
|
||||
}
|
||||
+13
-2
@@ -37,6 +37,8 @@ var (
|
||||
ecmaSpace = []rune{0x0009, 0x000e, 0x0020, 0x0021, 0x00a0, 0x00a1, 0x1680, 0x1681, 0x2000, 0x200b, 0x2028, 0x202a, 0x202f, 0x2030, 0x205f, 0x2060, 0x3000, 0x3001, 0xfeff, 0xff00}
|
||||
ecmaWord = []rune{0x0030, 0x003a, 0x0041, 0x005b, 0x005f, 0x0060, 0x0061, 0x007b}
|
||||
ecmaDigit = []rune{0x0030, 0x003a}
|
||||
|
||||
re2Space = []rune{0x0009, 0x000b, 0x000c, 0x000e, 0x0020, 0x0021}
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -56,6 +58,9 @@ var (
|
||||
NotSpaceClass = getCharSetFromCategoryString(true, false, spaceCategoryText)
|
||||
DigitClass = getCharSetFromCategoryString(false, false, "Nd")
|
||||
NotDigitClass = getCharSetFromCategoryString(false, true, "Nd")
|
||||
|
||||
RE2SpaceClass = getCharSetFromOldString(re2Space, false)
|
||||
NotRE2SpaceClass = getCharSetFromOldString(re2Space, true)
|
||||
)
|
||||
|
||||
var unicodeCategories = func() map[string]*unicode.RangeTable {
|
||||
@@ -401,13 +406,19 @@ func (c *CharSet) addChar(ch rune) {
|
||||
c.addRange(ch, ch)
|
||||
}
|
||||
|
||||
func (c *CharSet) addSpace(ecma, negate bool) {
|
||||
func (c *CharSet) addSpace(ecma, re2, negate bool) {
|
||||
if ecma {
|
||||
if negate {
|
||||
c.addRanges(NotECMASpaceClass().ranges)
|
||||
} else {
|
||||
c.addRanges(ECMASpaceClass().ranges)
|
||||
}
|
||||
} else if re2 {
|
||||
if negate {
|
||||
c.addRanges(NotRE2SpaceClass().ranges)
|
||||
} else {
|
||||
c.addRanges(RE2SpaceClass().ranges)
|
||||
}
|
||||
} else {
|
||||
c.addCategories(category{cat: spaceCategoryText, negate: negate})
|
||||
}
|
||||
@@ -563,7 +574,7 @@ func (c *CharSet) addNamedASCII(name string, negate bool) bool {
|
||||
case "punct": //[!-/:-@[-`{-~]
|
||||
rs = []singleRange{singleRange{'!', '/'}, singleRange{':', '@'}, singleRange{'[', '`'}, singleRange{'{', '~'}}
|
||||
case "space":
|
||||
c.addSpace(true, negate)
|
||||
c.addSpace(true, false, negate)
|
||||
case "upper":
|
||||
rs = []singleRange{singleRange{'A', 'Z'}}
|
||||
case "word":
|
||||
|
||||
+71
-22
@@ -22,6 +22,7 @@ const (
|
||||
Debug = 0x0080 // "d"
|
||||
ECMAScript = 0x0100 // "e"
|
||||
RE2 = 0x0200 // RE2 compat mode
|
||||
Unicode = 0x0400 // "u"
|
||||
)
|
||||
|
||||
func optionFromCode(ch rune) RegexOptions {
|
||||
@@ -43,6 +44,8 @@ func optionFromCode(ch rune) RegexOptions {
|
||||
return Debug
|
||||
case 'e', 'E':
|
||||
return ECMAScript
|
||||
case 'u', 'U':
|
||||
return Unicode
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
@@ -104,7 +107,7 @@ const (
|
||||
ErrBadClassInCharRange = "cannot include class \\%v in character range"
|
||||
ErrUnterminatedBracket = "unterminated [] set"
|
||||
ErrSubtractionMustBeLast = "a subtraction must be the last element in a character class"
|
||||
ErrReversedCharRange = "[x-y] range in reverse order"
|
||||
ErrReversedCharRange = "[%c-%c] range in reverse order"
|
||||
)
|
||||
|
||||
func (e ErrorCode) String() string {
|
||||
@@ -550,10 +553,10 @@ func (p *parser) scanRegex() (*regexNode, error) {
|
||||
}
|
||||
|
||||
case '.':
|
||||
if p.useOptionE() {
|
||||
p.addUnitSet(ECMAAnyClass())
|
||||
} else if p.useOptionS() {
|
||||
if p.useOptionS() {
|
||||
p.addUnitSet(AnyClass())
|
||||
} else if p.useOptionE() {
|
||||
p.addUnitSet(ECMAAnyClass())
|
||||
} else {
|
||||
p.addUnitNotone('\n')
|
||||
}
|
||||
@@ -1121,14 +1124,14 @@ func (p *parser) scanBackslash(scanOnly bool) (*regexNode, error) {
|
||||
|
||||
case 'w':
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
if p.useOptionE() || p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, ECMAWordClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, WordClass()), nil
|
||||
|
||||
case 'W':
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
if p.useOptionE() || p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, NotECMAWordClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, NotWordClass()), nil
|
||||
@@ -1137,6 +1140,8 @@ func (p *parser) scanBackslash(scanOnly bool) (*regexNode, error) {
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
return newRegexNodeSet(ntSet, p.options, ECMASpaceClass()), nil
|
||||
} else if p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, RE2SpaceClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, SpaceClass()), nil
|
||||
|
||||
@@ -1144,19 +1149,21 @@ func (p *parser) scanBackslash(scanOnly bool) (*regexNode, error) {
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
return newRegexNodeSet(ntSet, p.options, NotECMASpaceClass()), nil
|
||||
} else if p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, NotRE2SpaceClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, NotSpaceClass()), nil
|
||||
|
||||
case 'd':
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
if p.useOptionE() || p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, ECMADigitClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, DigitClass()), nil
|
||||
|
||||
case 'D':
|
||||
p.moveRight(1)
|
||||
if p.useOptionE() {
|
||||
if p.useOptionE() || p.useRE2() {
|
||||
return newRegexNodeSet(ntSet, p.options, NotECMADigitClass()), nil
|
||||
}
|
||||
return newRegexNodeSet(ntSet, p.options, NotDigitClass()), nil
|
||||
@@ -1186,19 +1193,24 @@ func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) {
|
||||
return nil, p.getErr(ErrIllegalEndEscape)
|
||||
}
|
||||
angled := false
|
||||
k := false
|
||||
close := '\x00'
|
||||
|
||||
backpos := p.textpos()
|
||||
ch := p.rightChar(0)
|
||||
|
||||
// allow \k<foo> instead of \<foo>, which is now deprecated
|
||||
// Allow \k<foo> instead of \<foo>, which is now deprecated.
|
||||
|
||||
if ch == 'k' {
|
||||
// According to ECMAScript specification, \k<name> is only parsed as a named group reference if
|
||||
// there is at least one group name in the regexp.
|
||||
// See https://www.ecma-international.org/ecma-262/#sec-isvalidregularexpressionliteral, step 7.
|
||||
// Note, during the first (scanOnly) run we may not have all group names scanned, but that's ok.
|
||||
if ch == 'k' && (!p.useOptionE() || len(p.capnames) > 0) {
|
||||
if p.charsRight() >= 2 {
|
||||
p.moveRight(1)
|
||||
ch = p.moveRightGetChar()
|
||||
|
||||
if ch == '<' || ch == '\'' {
|
||||
if ch == '<' || (!p.useOptionE() && ch == '\'') { // No support for \k'name' in ECMAScript
|
||||
angled = true
|
||||
if ch == '\'' {
|
||||
close = '\''
|
||||
@@ -1213,8 +1225,9 @@ func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) {
|
||||
}
|
||||
|
||||
ch = p.rightChar(0)
|
||||
k = true
|
||||
|
||||
} else if (ch == '<' || ch == '\'') && p.charsRight() > 1 { // Note angle without \g
|
||||
} else if !p.useOptionE() && (ch == '<' || ch == '\'') && p.charsRight() > 1 { // Note angle without \g
|
||||
angled = true
|
||||
if ch == '\'' {
|
||||
close = '\''
|
||||
@@ -1257,14 +1270,23 @@ func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) {
|
||||
return nil, p.getErr(ErrUndefinedBackRef, capnum)
|
||||
}
|
||||
|
||||
} else if angled && IsWordChar(ch) {
|
||||
} else if angled {
|
||||
capname := p.scanCapname()
|
||||
|
||||
if p.charsRight() > 0 && p.moveRightGetChar() == close {
|
||||
if capname != "" && p.charsRight() > 0 && p.moveRightGetChar() == close {
|
||||
|
||||
if scanOnly {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if p.isCaptureName(capname) {
|
||||
return newRegexNodeM(ntRef, p.options, p.captureSlotFromName(capname)), nil
|
||||
}
|
||||
return nil, p.getErr(ErrUndefinedNameRef, capname)
|
||||
} else {
|
||||
if k {
|
||||
return nil, p.getErr(ErrMalformedNameRef)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1276,6 +1298,10 @@ func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if scanOnly {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if p.useOptionI() {
|
||||
ch = unicode.ToLower(ch)
|
||||
}
|
||||
@@ -1285,6 +1311,17 @@ func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) {
|
||||
|
||||
// Scans X for \p{X} or \P{X}
|
||||
func (p *parser) parseProperty() (string, error) {
|
||||
// RE2 and PCRE supports \pX syntax (no {} and only 1 letter unicode cats supported)
|
||||
// since this is purely additive syntax it's not behind a flag
|
||||
if p.charsRight() >= 1 && p.rightChar(0) != '{' {
|
||||
ch := string(p.moveRightGetChar())
|
||||
// check if it's a valid cat
|
||||
if !isValidUnicodeCat(ch) {
|
||||
return "", p.getErr(ErrUnknownSlashP, ch)
|
||||
}
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
if p.charsRight() < 3 {
|
||||
return "", p.getErr(ErrIncompleteSlashP)
|
||||
}
|
||||
@@ -1401,7 +1438,7 @@ func (p *parser) scanCapname() string {
|
||||
return string(p.pattern[startpos:p.textpos()])
|
||||
}
|
||||
|
||||
//Scans contents of [] (not including []'s), and converts to a set.
|
||||
// Scans contents of [] (not including []'s), and converts to a set.
|
||||
func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) {
|
||||
ch := '\x00'
|
||||
chPrev := '\x00'
|
||||
@@ -1443,7 +1480,7 @@ func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) {
|
||||
if inRange {
|
||||
return nil, p.getErr(ErrBadClassInCharRange, ch)
|
||||
}
|
||||
cc.addDigit(p.useOptionE(), ch == 'D', p.patternRaw)
|
||||
cc.addDigit(p.useOptionE() || p.useRE2(), ch == 'D', p.patternRaw)
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -1452,7 +1489,7 @@ func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) {
|
||||
if inRange {
|
||||
return nil, p.getErr(ErrBadClassInCharRange, ch)
|
||||
}
|
||||
cc.addSpace(p.useOptionE(), ch == 'S')
|
||||
cc.addSpace(p.useOptionE(), p.useRE2(), ch == 'S')
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -1462,7 +1499,7 @@ func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) {
|
||||
return nil, p.getErr(ErrBadClassInCharRange, ch)
|
||||
}
|
||||
|
||||
cc.addWord(p.useOptionE(), ch == 'W')
|
||||
cc.addWord(p.useOptionE() || p.useRE2(), ch == 'W')
|
||||
}
|
||||
continue
|
||||
|
||||
@@ -1548,7 +1585,7 @@ func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) {
|
||||
} else {
|
||||
// a regular range, like a-z
|
||||
if chPrev > ch {
|
||||
return nil, p.getErr(ErrReversedCharRange)
|
||||
return nil, p.getErr(ErrReversedCharRange, chPrev, ch)
|
||||
}
|
||||
cc.addRange(chPrev, ch)
|
||||
}
|
||||
@@ -1672,7 +1709,13 @@ func (p *parser) scanCharEscape() (r rune, err error) {
|
||||
r, err = p.scanHex(2)
|
||||
}
|
||||
case 'u':
|
||||
r, err = p.scanHex(4)
|
||||
// ECMAscript suppot \u{HEX} only if `u` is also set
|
||||
if p.useOptionE() && p.useOptionU() && p.charsRight() > 0 && p.rightChar(0) == '{' {
|
||||
p.moveRight(1)
|
||||
return p.scanHexUntilBrace()
|
||||
} else {
|
||||
r, err = p.scanHex(4)
|
||||
}
|
||||
case 'a':
|
||||
return '\u0007', nil
|
||||
case 'b':
|
||||
@@ -1692,7 +1735,7 @@ func (p *parser) scanCharEscape() (r rune, err error) {
|
||||
case 'c':
|
||||
r, err = p.scanControl()
|
||||
default:
|
||||
if !p.useOptionE() && IsWordChar(ch) {
|
||||
if !p.useOptionE() && !p.useRE2() && IsWordChar(ch) {
|
||||
return 0, p.getErr(ErrUnrecognizedEscape, string(ch))
|
||||
}
|
||||
return ch, nil
|
||||
@@ -1949,6 +1992,11 @@ func (p *parser) useRE2() bool {
|
||||
return (p.options & RE2) != 0
|
||||
}
|
||||
|
||||
// True if U option enabling ECMAScript's Unicode behavior on.
|
||||
func (p *parser) useOptionU() bool {
|
||||
return (p.options & Unicode) != 0
|
||||
}
|
||||
|
||||
// True if options stack is empty.
|
||||
func (p *parser) emptyOptionsStack() bool {
|
||||
return len(p.optionsStack) == 0
|
||||
@@ -2044,7 +2092,8 @@ func (p *parser) addToConcatenate(pos, cch int, isReplacement bool) {
|
||||
}
|
||||
|
||||
if cch > 1 {
|
||||
str := p.pattern[pos : pos+cch]
|
||||
str := make([]rune, cch)
|
||||
copy(str, p.pattern[pos:pos+cch])
|
||||
|
||||
if p.useOptionI() && !isReplacement {
|
||||
// We do the ToLower character by character for consistency. With surrogate chars, doing
|
||||
|
||||
+1
-1
@@ -712,7 +712,7 @@ func (b *BmPrefix) Scan(text []rune, index, beglimit, endlimit int) int {
|
||||
|
||||
if chTest != b.pattern[match] {
|
||||
advance = b.positive[match]
|
||||
if (chTest & 0xFF80) == 0 {
|
||||
if chTest < 128 {
|
||||
test2 = (match - startmatch) + b.negativeASCII[chTest]
|
||||
} else if chTest < 0xffff && len(b.negativeUnicode) > 0 {
|
||||
unicodeLookup = b.negativeUnicode[chTest>>8]
|
||||
|
||||
+80
-32
@@ -19,15 +19,15 @@ var (
|
||||
// set (regardless of its value). This is a global option and affects all
|
||||
// colors. For more control over each color block use the methods
|
||||
// DisableColor() individually.
|
||||
NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" ||
|
||||
(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
|
||||
NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" || !stdoutIsTerminal()
|
||||
|
||||
// Output defines the standard output of the print functions. By default,
|
||||
// os.Stdout is used.
|
||||
Output = colorable.NewColorableStdout()
|
||||
// stdOut() is used.
|
||||
Output = stdOut()
|
||||
|
||||
// Error defines a color supporting writer for os.Stderr.
|
||||
Error = colorable.NewColorableStderr()
|
||||
// Error defines the standard error of the print functions. By default,
|
||||
// stdErr() is used.
|
||||
Error = stdErr()
|
||||
|
||||
// colorsCache is used to reduce the count of created Color objects and
|
||||
// allows to reuse already created objects with required Attribute.
|
||||
@@ -40,6 +40,33 @@ func noColorIsSet() bool {
|
||||
return os.Getenv("NO_COLOR") != ""
|
||||
}
|
||||
|
||||
// stdoutIsTerminal returns true if os.Stdout is a terminal.
|
||||
// Returns false if os.Stdout is nil (e.g., when running as a Windows service).
|
||||
func stdoutIsTerminal() bool {
|
||||
if os.Stdout == nil {
|
||||
return false
|
||||
}
|
||||
return isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
|
||||
}
|
||||
|
||||
// stdOut returns a writer for color output.
|
||||
// Returns io.Discard if os.Stdout is nil (e.g., when running as a Windows service).
|
||||
func stdOut() io.Writer {
|
||||
if os.Stdout == nil {
|
||||
return io.Discard
|
||||
}
|
||||
return colorable.NewColorableStdout()
|
||||
}
|
||||
|
||||
// stdErr returns a writer for color error output.
|
||||
// Returns io.Discard if os.Stderr is nil (e.g., when running as a Windows service).
|
||||
func stdErr() io.Writer {
|
||||
if os.Stderr == nil {
|
||||
return io.Discard
|
||||
}
|
||||
return colorable.NewColorableStderr()
|
||||
}
|
||||
|
||||
// Color defines a custom color object which is defined by SGR parameters.
|
||||
type Color struct {
|
||||
params []Attribute
|
||||
@@ -220,26 +247,30 @@ func (c *Color) unset() {
|
||||
// a low-level function, and users should use the higher-level functions, such
|
||||
// as color.Fprint, color.Print, etc.
|
||||
func (c *Color) SetWriter(w io.Writer) *Color {
|
||||
_, _ = c.setWriter(w)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Color) setWriter(w io.Writer) (int, error) {
|
||||
if c.isNoColorSet() {
|
||||
return c
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
fmt.Fprint(w, c.format())
|
||||
return c
|
||||
return fmt.Fprint(w, c.format())
|
||||
}
|
||||
|
||||
// UnsetWriter resets all escape attributes and clears the output with the give
|
||||
// io.Writer. Usually should be called after SetWriter().
|
||||
func (c *Color) UnsetWriter(w io.Writer) {
|
||||
_, _ = c.unsetWriter(w)
|
||||
}
|
||||
|
||||
func (c *Color) unsetWriter(w io.Writer) (int, error) {
|
||||
if c.isNoColorSet() {
|
||||
return
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if NoColor {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "%s[%dm", escape, Reset)
|
||||
return fmt.Fprintf(w, "%s[%dm", escape, Reset)
|
||||
}
|
||||
|
||||
// Add is used to chain SGR parameters. Use as many as parameters to combine
|
||||
@@ -255,10 +286,20 @@ func (c *Color) Add(value ...Attribute) *Color {
|
||||
// On Windows, users should wrap w with colorable.NewColorable() if w is of
|
||||
// type *os.File.
|
||||
func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
c.SetWriter(w)
|
||||
defer c.UnsetWriter(w)
|
||||
n, err = c.setWriter(w)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return fmt.Fprint(w, a...)
|
||||
nn, err := fmt.Fprint(w, a...)
|
||||
n += nn
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
nn, err = c.unsetWriter(w)
|
||||
n += nn
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Print formats using the default formats for its operands and writes to
|
||||
@@ -278,10 +319,20 @@ func (c *Color) Print(a ...interface{}) (n int, err error) {
|
||||
// On Windows, users should wrap w with colorable.NewColorable() if w is of
|
||||
// type *os.File.
|
||||
func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
|
||||
c.SetWriter(w)
|
||||
defer c.UnsetWriter(w)
|
||||
n, err = c.setWriter(w)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
|
||||
return fmt.Fprintf(w, format, a...)
|
||||
nn, err := fmt.Fprintf(w, format, a...)
|
||||
n += nn
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
nn, err = c.unsetWriter(w)
|
||||
n += nn
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Printf formats according to a format specifier and writes to standard output.
|
||||
@@ -475,29 +526,26 @@ func (c *Color) Equals(c2 *Color) bool {
|
||||
if c == nil || c2 == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(c.params) != len(c2.params) {
|
||||
return false
|
||||
}
|
||||
|
||||
counts := make(map[Attribute]int, len(c.params))
|
||||
for _, attr := range c.params {
|
||||
if !c2.attrExists(attr) {
|
||||
counts[attr]++
|
||||
}
|
||||
|
||||
for _, attr := range c2.params {
|
||||
if counts[attr] == 0 {
|
||||
return false
|
||||
}
|
||||
counts[attr]--
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Color) attrExists(a Attribute) bool {
|
||||
for _, attr := range c.params {
|
||||
if attr == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
+3
@@ -9,6 +9,9 @@ import (
|
||||
func init() {
|
||||
// Opt-in for ansi color support for current process.
|
||||
// https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#output-sequences
|
||||
if os.Stdout == nil {
|
||||
return
|
||||
}
|
||||
var outMode uint32
|
||||
out := windows.Handle(os.Stdout.Fd())
|
||||
if err := windows.GetConsoleMode(out, &outMode); err != nil {
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
linters-settings:
|
||||
staticcheck:
|
||||
checks: [
|
||||
"all",
|
||||
"-SA1019" # There are valid use cases of strings.Title
|
||||
]
|
||||
nakedret:
|
||||
max-func-lines: 0 # Disallow any unnamed return statement
|
||||
|
||||
linters:
|
||||
enable:
|
||||
- deadcode
|
||||
- errcheck
|
||||
- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- staticcheck
|
||||
- structcheck
|
||||
- typecheck
|
||||
- unused
|
||||
- varcheck
|
||||
- nakedret
|
||||
- gofmt
|
||||
- rowserrcheck
|
||||
- unconvert
|
||||
- goimports
|
||||
- unparam
|
||||
@@ -30,3 +30,4 @@ _testmain.go
|
||||
cover.html
|
||||
README.html
|
||||
.idea
|
||||
.claude/
|
||||
+5
@@ -53,3 +53,8 @@ linters:
|
||||
- varnamelen
|
||||
- wrapcheck
|
||||
- wsl
|
||||
- gomodguard
|
||||
settings:
|
||||
govet:
|
||||
disable:
|
||||
- inline
|
||||
+7
-2
@@ -51,7 +51,8 @@ Validator returns only InvalidValidationError for bad validation input, nil or V
|
||||
|
||||
```go
|
||||
err := validate.Struct(mystruct)
|
||||
validationErrors := err.(validator.ValidationErrors)
|
||||
var validationErrors validator.ValidationErrors
|
||||
errors.As(err, &validationErrors)
|
||||
```
|
||||
|
||||
Usage and documentation
|
||||
@@ -128,6 +129,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| url | URL String |
|
||||
| http_url | HTTP(s) URL String |
|
||||
| https_url | HTTPS-only URL String |
|
||||
| origin | Web origin (URL with HTTP(S) scheme and host, but no path/query/fragment) |
|
||||
| url_encoded | URL Encoded |
|
||||
| urn_rfc2141 | Urn RFC 2141 String |
|
||||
|
||||
@@ -169,6 +171,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| bic_iso_9362_2014 | Business Identifier Code (ISO 9362:2014) |
|
||||
| bic | Business Identifier Code (ISO 9362:2022) |
|
||||
| bcp47_language_tag | Language tag (BCP 47) |
|
||||
| bcp47_strict_language_tag | Language tag (BCP 47), strictly following RFC 5646 |
|
||||
| btc_addr | Bitcoin Address |
|
||||
| btc_addr_bech32 | Bitcoin Bech32 Address (segwit) |
|
||||
| credit_card | Credit Card Number |
|
||||
@@ -222,7 +225,7 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| sha384 | SHA384 hash |
|
||||
| sha512 | SHA512 hash |
|
||||
| ripemd128 | RIPEMD-128 hash |
|
||||
| ripemd128 | RIPEMD-160 hash |
|
||||
| ripemd160 | RIPEMD-160 hash |
|
||||
| tiger128 | TIGER128 hash |
|
||||
| tiger160 | TIGER160 hash |
|
||||
| tiger192 | TIGER192 hash |
|
||||
@@ -250,11 +253,13 @@ validate := validator.New(validator.WithRequiredStructEnabled())
|
||||
| file | Existing File |
|
||||
| filepath | File Path |
|
||||
| image | Image |
|
||||
| mimetype | MIME Type |
|
||||
| isdefault | Is Default |
|
||||
| len | Length |
|
||||
| max | Maximum |
|
||||
| min | Minimum |
|
||||
| oneof | One Of |
|
||||
| noneof | None Of |
|
||||
| required | Required |
|
||||
| required_if | Required If |
|
||||
| required_unless | Required Unless |
|
||||
|
||||
+314
-94
@@ -3,7 +3,6 @@ package validator
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
@@ -16,7 +15,9 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -141,6 +142,7 @@ var (
|
||||
"http_url": isHttpURL,
|
||||
"https_url": isHttpsURL,
|
||||
"uri": isURI,
|
||||
"origin": isOrigin,
|
||||
"urn_rfc2141": isUrnRFC2141, // RFC 2141
|
||||
"file": isFile,
|
||||
"filepath": isFilePath,
|
||||
@@ -159,6 +161,7 @@ var (
|
||||
"startsnotwith": startsNotWith,
|
||||
"endsnotwith": endsNotWith,
|
||||
"image": isImage,
|
||||
"mimetype": isMIMEType,
|
||||
"isbn": isISBN,
|
||||
"isbn10": isISBN10,
|
||||
"isbn13": isISBN13,
|
||||
@@ -217,6 +220,8 @@ var (
|
||||
"unique": isUnique,
|
||||
"oneof": isOneOf,
|
||||
"oneofci": isOneOfCI,
|
||||
"noneof": isNoneOf,
|
||||
"noneofci": isNoneOfCI,
|
||||
"html": isHTML,
|
||||
"html_encoded": isHTMLEncoded,
|
||||
"url_encoded": isURLEncoded,
|
||||
@@ -240,6 +245,7 @@ var (
|
||||
"iso4217": isIso4217,
|
||||
"iso4217_numeric": isIso4217Numeric,
|
||||
"bcp47_language_tag": isBCP47LanguageTag,
|
||||
"bcp47_strict_language_tag": isBCP47StrictLanguageTag,
|
||||
"postcode_iso3166_alpha2": isPostcodeByIso3166Alpha2,
|
||||
"postcode_iso3166_alpha2_field": isPostcodeByIso3166Alpha2Field,
|
||||
"bic_iso_9362_2014": isIsoBic2014Format,
|
||||
@@ -261,6 +267,33 @@ var (
|
||||
var (
|
||||
oneofValsCache = map[string][]string{}
|
||||
oneofValsCacheRWLock = sync.RWMutex{}
|
||||
|
||||
// BCP47 language tag
|
||||
// according to https://www.rfc-editor.org/rfc/bcp/bcp47.txt
|
||||
bcp47LanguageTagRe = regexp.MustCompile(strings.Join([]string{
|
||||
// group 1:
|
||||
`^(`,
|
||||
// irregular
|
||||
`en-gb-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|`,
|
||||
`sgn-be-fr|sgn-be-nl|sgn-ch-de|`,
|
||||
// regular
|
||||
`art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang|`,
|
||||
// privateuse
|
||||
`x-[a-z0-9]{1,8}`,
|
||||
`)$`,
|
||||
|
||||
`|`,
|
||||
|
||||
// langtag
|
||||
`^`,
|
||||
`((?:[a-z]{2,3}(?:-[a-z]{3}){0,3})|[a-z]{4}|[a-z]{5,8})`, // group 2: language
|
||||
`(?:-([a-z]{4}))?`, // group 3: script
|
||||
`(?:-([a-z]{2}|[0-9]{3}))?`, // group 4: region
|
||||
`(?:-((?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3})(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*))?`, // group 5: variant
|
||||
`(?:-((?:[a-wyz0-9](?:-[a-z0-9]{2,8})+)(?:-(?:[a-wyz0-9](?:-[a-z0-9]{2,8})+))*))?`, // group 6: extension
|
||||
`(?:-x(?:-[a-z0-9]{1,8})+)?`,
|
||||
`$`,
|
||||
}, ""))
|
||||
)
|
||||
|
||||
func parseOneOfParam2(s string) []string {
|
||||
@@ -307,12 +340,8 @@ func isOneOf(fl FieldLevel) bool {
|
||||
default:
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
for i := 0; i < len(vals); i++ {
|
||||
if vals[i] == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
return slices.Contains(vals, v)
|
||||
}
|
||||
|
||||
// isOneOfCI is the validation function for validating if the current field's value is one of the provided string values (case insensitive).
|
||||
@@ -323,13 +352,20 @@ func isOneOfCI(fl FieldLevel) bool {
|
||||
if field.Kind() != reflect.String {
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
v := field.String()
|
||||
for _, val := range vals {
|
||||
if strings.EqualFold(val, v) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
||||
return slices.ContainsFunc(vals, func(val string) bool {
|
||||
return strings.EqualFold(val, field.String())
|
||||
})
|
||||
}
|
||||
|
||||
// isNoneOf validates that the current field's value is not one of the provided string or integer values
|
||||
func isNoneOf(fl FieldLevel) bool {
|
||||
return !isOneOf(fl)
|
||||
}
|
||||
|
||||
// isNoneOfCI validates that the current field's value is not one of the provided string values (case insensitive)
|
||||
func isNoneOfCI(fl FieldLevel) bool {
|
||||
return !isOneOfCI(fl)
|
||||
}
|
||||
|
||||
// isUnique is the validation function for validating if each array|slice|map value is unique
|
||||
@@ -1526,6 +1562,64 @@ func isURI(fl FieldLevel) bool {
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
// isOrigin checks if a field value is a valid web origin URL with HTTP(S) scheme and host defined, but no path, query, or fragment.
|
||||
func isOrigin(fl FieldLevel) bool {
|
||||
field := fl.Field()
|
||||
|
||||
if field.Kind() == reflect.String {
|
||||
s := field.String()
|
||||
|
||||
if len(s) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Fragments with empty content ("#") are not detectable after parse and
|
||||
// u.Fragment will be empty even if # is present in the URL.
|
||||
if strings.Contains(s, "#") {
|
||||
return false
|
||||
}
|
||||
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
|
||||
if u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if u.User != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
hostname := u.Hostname()
|
||||
if hostname == "" {
|
||||
return false
|
||||
}
|
||||
if net.ParseIP(hostname) == nil && !hostnameRegexRFC1123().MatchString(hostname) {
|
||||
return false
|
||||
}
|
||||
|
||||
portStr := u.Port()
|
||||
if portStr != "" {
|
||||
// Port 0 is reserved (RFC 6335) and has no valid use as an origin port.
|
||||
// https://www.rfc-editor.org/rfc/rfc6335.html#section-6
|
||||
port, portErr := strconv.ParseUint(portStr, 10, 16)
|
||||
if portErr != nil || port == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
// isURL is the validation function for validating if the current field's value is a valid URL.
|
||||
func isURL(fl FieldLevel) bool {
|
||||
field := fl.Field()
|
||||
@@ -1635,6 +1729,63 @@ func isFile(fl FieldLevel) bool {
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
func detectFileMIMEType(field reflect.Value) (string, bool) {
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
filePath := field.String()
|
||||
fileInfo, err := os.Stat(filePath)
|
||||
if err != nil || fileInfo.IsDir() {
|
||||
return "", false
|
||||
}
|
||||
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
mime, err := mimetype.DetectReader(file)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return mime.String(), true
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
func matchesMIMEType(mime, expected string) bool {
|
||||
expectedType, expectedSubtype, ok := strings.Cut(strings.TrimSpace(expected), "/")
|
||||
if !ok || expectedType == "" || expectedSubtype == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
mimeType, mimeSubtype, ok := strings.Cut(mime, "/")
|
||||
if !ok || mimeType == "" || mimeSubtype == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if expectedSubtype == "*" {
|
||||
return mimeType == expectedType
|
||||
}
|
||||
|
||||
return mimeType == expectedType && mimeSubtype == expectedSubtype
|
||||
}
|
||||
|
||||
// isMIMEType is the validation function for validating if the current field's value contains the path to a file
|
||||
// whose detected MIME type matches the provided validator param in the form type/subtype or type/*.
|
||||
func isMIMEType(fl FieldLevel) bool {
|
||||
mime, ok := detectFileMIMEType(fl.Field())
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
return matchesMIMEType(mime, fl.Param())
|
||||
}
|
||||
|
||||
// isImage is the validation function for validating if the current field's value contains the path to a valid image file
|
||||
func isImage(fl FieldLevel) bool {
|
||||
mimetypes := map[string]bool{
|
||||
@@ -1663,39 +1814,14 @@ func isImage(fl FieldLevel) bool {
|
||||
"image/x-xpixmap": true,
|
||||
"image/x-xwindowdump": true,
|
||||
}
|
||||
field := fl.Field()
|
||||
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
filePath := field.String()
|
||||
fileInfo, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if fileInfo.IsDir() {
|
||||
return false
|
||||
}
|
||||
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
mime, err := mimetype.DetectReader(file)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
if _, ok := mimetypes[mime.String()]; ok {
|
||||
return true
|
||||
}
|
||||
mime, ok := detectFileMIMEType(fl.Field())
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
_, ok = mimetypes[mime]
|
||||
return ok
|
||||
}
|
||||
|
||||
// isFilePath is the validation function for validating if the current field's value is a valid file path.
|
||||
@@ -3081,6 +3207,150 @@ func isBCP47LanguageTag(fl FieldLevel) bool {
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
// isBCP47StrictLanguageTag is the validation function for validating if the current field's value is a valid BCP 47 language tag
|
||||
// according to https://www.rfc-editor.org/rfc/bcp/bcp47.txt
|
||||
func isBCP47StrictLanguageTag(fl FieldLevel) bool {
|
||||
field := fl.Field()
|
||||
|
||||
if field.Kind() != reflect.String {
|
||||
panic(fmt.Sprintf("Bad field type %s", field.Type()))
|
||||
}
|
||||
|
||||
lower := strings.ToLower(field.String())
|
||||
lowerTagDash := lower + "-"
|
||||
|
||||
m := bcp47LanguageTagRe.FindStringSubmatch(lower)
|
||||
if m == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
grandfatheredOrPrivateuse := m[1]
|
||||
lang := m[2]
|
||||
script := m[3]
|
||||
region := m[4]
|
||||
variant := m[5]
|
||||
extension := m[6]
|
||||
|
||||
if grandfatheredOrPrivateuse != "" {
|
||||
return true
|
||||
}
|
||||
|
||||
// language = 2*3ALPHA ; shortest ISO 639 code
|
||||
// ["-" extlang] ; sometimes followed by
|
||||
// ; extended language subtags
|
||||
// / 4ALPHA ; or reserved for future use
|
||||
// / 5*8ALPHA ; or registered language subtag
|
||||
switch n := len(lang); {
|
||||
// 2*3ALPHA "-" extlang
|
||||
case strings.Contains(lang, "-"):
|
||||
parts := strings.Split(lang, "-")
|
||||
|
||||
baseLang := parts[0]
|
||||
base, err := language.ParseBase(baseLang)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// base.String() normalizes the base to the shortest code
|
||||
// for the language
|
||||
if base.String() != baseLang {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, e := range parts[1:] {
|
||||
prefixes, ok := iana_subtag_registry_extlangs[e]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(prefixes) > 0 {
|
||||
found := false
|
||||
for _, p := range prefixes {
|
||||
if strings.HasPrefix(lowerTagDash, p) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2*3ALPHA ; shortest ISO 639 code
|
||||
case n <= 3:
|
||||
base, err := language.ParseBase(lang)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// base.String() normalizes the base to the shortest code
|
||||
// for the language
|
||||
if base.String() != lang {
|
||||
return false
|
||||
}
|
||||
// 4ALPHA ; or reserved for future use
|
||||
case n == 4:
|
||||
return false
|
||||
// 5*8ALPHA ; or registered language subtag
|
||||
default:
|
||||
// registered language subtag with 5+ characters.
|
||||
// As of today there aren't any.
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
return false
|
||||
}
|
||||
|
||||
// script = 4ALPHA ; ISO 15924 code
|
||||
if script != "" {
|
||||
_, err := language.ParseScript(script)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// region = 2ALPHA ; ISO 3166-1 code
|
||||
// 3DIGIT ; UN M.49 code
|
||||
if region != "" {
|
||||
if len(region) == 2 {
|
||||
_, err := language.ParseRegion(region)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
// Can't use language.ParseRegion() here because not all
|
||||
// UN M.49 region codes are allowed, just the subset present
|
||||
// in the IANA subtag registry.
|
||||
_, ok := iana_subtag_registry_m49_codes[region]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// variant = 5*8alphanum ; registered variants
|
||||
// / (DIGIT 3alphanum)
|
||||
if variant != "" {
|
||||
for v := range strings.SplitSeq(variant, "-") {
|
||||
_, err := language.ParseVariant(v)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
_, ok := iana_subtag_registry_variants[v]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if extension != "" {
|
||||
_, err := language.ParseExtension(extension)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// isIsoBic2014Format is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362 2014
|
||||
func isIsoBic2014Format(fl FieldLevel) bool {
|
||||
bicString := fl.Field().String()
|
||||
@@ -3235,59 +3505,9 @@ func isEIN(fl FieldLevel) bool {
|
||||
return einRegex().MatchString(field.String())
|
||||
}
|
||||
|
||||
func isValidateFn(fl FieldLevel) bool {
|
||||
const defaultParam = `Validate`
|
||||
|
||||
field := fl.Field()
|
||||
validateFn := cmp.Or(fl.Param(), defaultParam)
|
||||
|
||||
ok, err := tryCallValidateFn(field, validateFn)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
var (
|
||||
errMethodNotFound = errors.New(`method not found`)
|
||||
errMethodReturnNoValues = errors.New(`method return o values (void)`)
|
||||
errMethodReturnInvalidType = errors.New(`method should return invalid type`)
|
||||
)
|
||||
|
||||
func tryCallValidateFn(field reflect.Value, validateFn string) (bool, error) {
|
||||
method := field.MethodByName(validateFn)
|
||||
if field.CanAddr() && !method.IsValid() {
|
||||
method = field.Addr().MethodByName(validateFn)
|
||||
}
|
||||
|
||||
if !method.IsValid() {
|
||||
return false, fmt.Errorf("unable to call %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodNotFound)
|
||||
}
|
||||
|
||||
returnValues := method.Call([]reflect.Value{})
|
||||
if len(returnValues) == 0 {
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodReturnNoValues)
|
||||
}
|
||||
|
||||
firstReturnValue := returnValues[0]
|
||||
|
||||
switch firstReturnValue.Kind() {
|
||||
case reflect.Bool:
|
||||
return firstReturnValue.Bool(), nil
|
||||
case reflect.Interface:
|
||||
errorType := reflect.TypeOf((*error)(nil)).Elem()
|
||||
|
||||
if firstReturnValue.Type().Implements(errorType) {
|
||||
return firstReturnValue.IsNil(), nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got interface %v expect error)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
default:
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got %v expect error or bool)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -144,7 +144,7 @@ func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStr
|
||||
|
||||
if v.hasTagNameFunc {
|
||||
name := v.tagNameFunc(fld)
|
||||
if len(name) > 0 {
|
||||
if len(name) > 0 || v.omitBlankFieldNames {
|
||||
customName = name
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -1175,3 +1175,15 @@ var iso3166_2 = map[string]struct{}{
|
||||
"ZW-BU": {}, "ZW-HA": {}, "ZW-MA": {}, "ZW-MC": {}, "ZW-ME": {},
|
||||
"ZW-MI": {}, "ZW-MN": {}, "ZW-MS": {}, "ZW-MV": {}, "ZW-MW": {},
|
||||
}
|
||||
|
||||
// Subset of UN M.49 region codes present in the IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_m49_codes = map[string]struct{}{
|
||||
"001": {}, "002": {}, "003": {}, "005": {}, "009": {},
|
||||
"011": {}, "013": {}, "014": {}, "015": {}, "017": {},
|
||||
"018": {}, "019": {}, "021": {}, "029": {}, "030": {},
|
||||
"034": {}, "035": {}, "039": {}, "053": {}, "054": {},
|
||||
"057": {}, "061": {}, "142": {}, "143": {}, "145": {},
|
||||
"150": {}, "151": {}, "154": {}, "155": {}, "202": {},
|
||||
"419": {},
|
||||
}
|
||||
+42
@@ -184,6 +184,12 @@ so the above will become excludesall=0x7C
|
||||
Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
|
||||
}
|
||||
|
||||
# Build tags
|
||||
|
||||
The library provides a build tag for build size optimizations. If you are not using
|
||||
`validateFn` you can add the `validator_novalidatefn` build tag to enabled better dead
|
||||
code elimination. With this build tag, any usage of `validateFn` tags will panic.
|
||||
|
||||
# Baked In Validators and Tags
|
||||
|
||||
Here is a list of the current built in validators:
|
||||
@@ -546,6 +552,24 @@ Works the same as oneof but is case insensitive and therefore only accepts strin
|
||||
Usage: oneofci=red green
|
||||
oneofci='red green' 'blue yellow'
|
||||
|
||||
# None Of
|
||||
|
||||
For strings, ints, and uints, noneof will ensure that the value is not one of
|
||||
the values in the parameter. The parameter should be a list of values separated by whitespace.
|
||||
Values may be strings or numbers. To inversely match strings with spaces in them, include the target string between single quotes.
|
||||
Kind of like an 'enum'.
|
||||
|
||||
Usage: noneof=red green
|
||||
noneof='red green' 'blue yellow'
|
||||
noneof=5 7 9
|
||||
|
||||
|
||||
# None Of Case Insensitive
|
||||
Works the same as noneof but is case insensitive and therefore only accepts strings.
|
||||
|
||||
Usage: noneofci=red green
|
||||
noneofci='red green' 'blue yellow'
|
||||
|
||||
# Greater Than
|
||||
|
||||
For numbers, this will ensure that the value is greater than the
|
||||
@@ -969,6 +993,16 @@ This is done using os.Stat and github.com/gabriel-vasile/mimetype
|
||||
|
||||
Usage: image
|
||||
|
||||
# MIME type path
|
||||
|
||||
This validates that a string value contains a valid file path and that
|
||||
the file exists on the machine and matches the provided MIME type in the
|
||||
form type/subtype or type/*.
|
||||
This is done using os.Stat and github.com/gabriel-vasile/mimetype
|
||||
|
||||
Usage: mimetype=image/png
|
||||
Usage: mimetype=image/*
|
||||
|
||||
# File Path
|
||||
|
||||
This validates that a string value contains a valid file path but does not
|
||||
@@ -1442,6 +1476,14 @@ More information on https://pkg.go.dev/golang.org/x/text/language
|
||||
|
||||
Usage: bcp47_language_tag
|
||||
|
||||
# BCP 47 Strict Language Tag
|
||||
|
||||
This validates that a string value is a valid BCP 47 language tag strictly following RFC 5646 rules,
|
||||
unlike language.Parse which also accepts Unicode extensions.
|
||||
see https://www.rfc-editor.org/rfc/bcp/bcp47.txt
|
||||
|
||||
Usage: bcp47_strict_language_tag
|
||||
|
||||
BIC (SWIFT code - 2022 standard)
|
||||
|
||||
This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362:2022.
|
||||
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
package validator
|
||||
|
||||
// Type: variant and their associated primary language prefixes from the
|
||||
// IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_variants = map[string][]string{
|
||||
"1606nict": {"frm"},
|
||||
"1694acad": {"fr"},
|
||||
"1901": {"de"},
|
||||
"1959acad": {"be"},
|
||||
"1994": {"sl-rozaj", "sl-rozaj-biske", "sl-rozaj-njiva", "sl-rozaj-osojs", "sl-rozaj-solba"},
|
||||
"1996": {"de"},
|
||||
"abl1943": {"pt-BR"},
|
||||
"akhmimic": {"cop"},
|
||||
"akuapem": {"tw"},
|
||||
"alalc97": {},
|
||||
"aluku": {"djk"},
|
||||
"anpezo": {"lld"},
|
||||
"ao1990": {"pt", "gl"},
|
||||
"aranes": {"oc"},
|
||||
"arevela": {"hy"},
|
||||
"arevmda": {"hy"},
|
||||
"arkaika": {"eo"},
|
||||
"asante": {"tw"},
|
||||
"auvern": {"oc"},
|
||||
"baku1926": {"az", "ba", "crh", "kk", "krc", "ky", "sah", "tk", "tt", "uz"},
|
||||
"balanka": {"blo"},
|
||||
"barla": {"kea"},
|
||||
"basiceng": {"en"},
|
||||
"bauddha": {"sa"},
|
||||
"bciav": {"zbl"},
|
||||
"bcizbl": {"zbl"},
|
||||
"biscayan": {"eu"},
|
||||
"biske": {"sl-rozaj"},
|
||||
"blasl": {"ase", "sgn-ase"},
|
||||
"bohairic": {"cop"},
|
||||
"bohoric": {"sl"},
|
||||
"boont": {"en"},
|
||||
"bornholm": {"da"},
|
||||
"cisaup": {"oc"},
|
||||
"colb1945": {"pt"},
|
||||
"cornu": {"en"},
|
||||
"creiss": {"oc"},
|
||||
"dajnko": {"sl"},
|
||||
"ekavsk": {"sr", "sr-Latn", "sr-Cyrl"},
|
||||
"emodeng": {"en"},
|
||||
"fascia": {"lld"},
|
||||
"fayyumic": {"cop"},
|
||||
"fodom": {"lld"},
|
||||
"fonipa": {},
|
||||
"fonkirsh": {},
|
||||
"fonnapa": {},
|
||||
"fonupa": {},
|
||||
"fonxsamp": {},
|
||||
"gallo": {"fr"},
|
||||
"gascon": {"oc"},
|
||||
"gherd": {"lld"},
|
||||
"grclass": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"},
|
||||
"grital": {"oc", "oc-cisaup", "oc-nicard", "oc-provenc"},
|
||||
"grmistr": {"oc", "oc-aranes", "oc-auvern", "oc-cisaup", "oc-creiss", "oc-gascon", "oc-lemosin", "oc-lengadoc", "oc-nicard", "oc-provenc", "oc-vivaraup"},
|
||||
"hanoi": {"vi"},
|
||||
"hepburn": {"ja-Latn"},
|
||||
"heploc": {"ja-Latn-hepburn"},
|
||||
"hognorsk": {"nn"},
|
||||
"hsistemo": {"eo"},
|
||||
"huett": {"vi"},
|
||||
"ijekavsk": {"sr", "sr-Latn", "sr-Cyrl"},
|
||||
"itihasa": {"sa"},
|
||||
"ivanchov": {"bg"},
|
||||
"jauer": {"rm"},
|
||||
"jyutping": {"yue"},
|
||||
"kkcor": {"kw"},
|
||||
"kleinsch": {"kl", "kl-tunumiit"},
|
||||
"kociewie": {"pl"},
|
||||
"kscor": {"kw"},
|
||||
"laukika": {"sa"},
|
||||
"leidentr": {"egy"},
|
||||
"lemosin": {"oc"},
|
||||
"lengadoc": {"oc"},
|
||||
"lipaw": {"sl-rozaj"},
|
||||
"ltg1929": {"ltg"},
|
||||
"ltg2007": {"ltg"},
|
||||
"luna1918": {"ru"},
|
||||
"lycopol": {"cop"},
|
||||
"mdcegyp": {"egy"},
|
||||
"mdctrans": {"egy"},
|
||||
"mesokem": {"cop"},
|
||||
"metelko": {"sl"},
|
||||
"monoton": {"el"},
|
||||
"ndyuka": {"djk"},
|
||||
"nedis": {"sl"},
|
||||
"newfound": {"en-CA"},
|
||||
"nicard": {"oc"},
|
||||
"njiva": {"sl-rozaj"},
|
||||
"nulik": {"vo"},
|
||||
"osojs": {"sl-rozaj"},
|
||||
"oxendict": {"en"},
|
||||
"pahawh2": {"mww", "hnj"},
|
||||
"pahawh3": {"mww", "hnj"},
|
||||
"pahawh4": {"mww", "hnj"},
|
||||
"pamaka": {"djk"},
|
||||
"peano": {"la"},
|
||||
"pehoeji": {"nan-Latn"},
|
||||
"petr1708": {"ru"},
|
||||
"pinyin": {"zh-Latn", "bo-Latn"},
|
||||
"polyton": {"el"},
|
||||
"provenc": {"oc"},
|
||||
"puter": {"rm"},
|
||||
"rigik": {"vo"},
|
||||
"rozaj": {"sl"},
|
||||
"rumgr": {"rm"},
|
||||
"sahidic": {"cop"},
|
||||
"saigon": {"vi"},
|
||||
"scotland": {"en"},
|
||||
"scouse": {"en"},
|
||||
"simple": {},
|
||||
"solba": {"sl-rozaj"},
|
||||
"sotav": {"kea"},
|
||||
"spanglis": {"en", "es"},
|
||||
"surmiran": {"rm"},
|
||||
"sursilv": {"rm"},
|
||||
"sutsilv": {"rm"},
|
||||
"synnejyl": {"da"},
|
||||
"tailo": {"nan-Latn"},
|
||||
"tarask": {"be"},
|
||||
"tongyong": {"zh-Latn"},
|
||||
"tunumiit": {"kl"},
|
||||
"uccor": {"kw"},
|
||||
"ucrcor": {"kw"},
|
||||
"ulster": {"sco"},
|
||||
"unifon": {"en", "hup", "kyh", "tol", "yur"},
|
||||
"vaidika": {"sa"},
|
||||
"valbadia": {"lld"},
|
||||
"valencia": {"ca"},
|
||||
"vallader": {"rm"},
|
||||
"vecdruka": {"lv"},
|
||||
"viennese": {"de"},
|
||||
"vivaraup": {"oc"},
|
||||
"wadegile": {"zh-Latn"},
|
||||
"xsistemo": {"eo"},
|
||||
}
|
||||
|
||||
// Type: extlang and their associated primary language prefixes from the
|
||||
// IANA Language Subtag Registry:
|
||||
// https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
|
||||
var iana_subtag_registry_extlangs = map[string][]string{
|
||||
"aao": {"ar"},
|
||||
"abh": {"ar"},
|
||||
"abv": {"ar"},
|
||||
"acm": {"ar"},
|
||||
"acq": {"ar"},
|
||||
"acw": {"ar"},
|
||||
"acx": {"ar"},
|
||||
"acy": {"ar"},
|
||||
"adf": {"ar"},
|
||||
"ads": {"sgn"},
|
||||
"aeb": {"ar"},
|
||||
"aec": {"ar"},
|
||||
"aed": {"sgn"},
|
||||
"aen": {"sgn"},
|
||||
"afb": {"ar"},
|
||||
"afg": {"sgn"},
|
||||
"ajp": {"ar"},
|
||||
"ajs": {"sgn"},
|
||||
"apc": {"ar"},
|
||||
"apd": {"ar"},
|
||||
"arb": {"ar"},
|
||||
"arq": {"ar"},
|
||||
"ars": {"ar"},
|
||||
"ary": {"ar"},
|
||||
"arz": {"ar"},
|
||||
"ase": {"sgn"},
|
||||
"asf": {"sgn"},
|
||||
"asp": {"sgn"},
|
||||
"asq": {"sgn"},
|
||||
"asw": {"sgn"},
|
||||
"auz": {"ar"},
|
||||
"avl": {"ar"},
|
||||
"ayh": {"ar"},
|
||||
"ayl": {"ar"},
|
||||
"ayn": {"ar"},
|
||||
"ayp": {"ar"},
|
||||
"bbz": {"ar"},
|
||||
"bfi": {"sgn"},
|
||||
"bfk": {"sgn"},
|
||||
"bjn": {"ms"},
|
||||
"bog": {"sgn"},
|
||||
"bqn": {"sgn"},
|
||||
"bqy": {"sgn"},
|
||||
"btj": {"ms"},
|
||||
"bve": {"ms"},
|
||||
"bvl": {"sgn"},
|
||||
"bvu": {"ms"},
|
||||
"bzs": {"sgn"},
|
||||
"cdo": {"zh"},
|
||||
"cds": {"sgn"},
|
||||
"cjy": {"zh"},
|
||||
"cmn": {"zh"},
|
||||
"cnp": {"zh"},
|
||||
"coa": {"ms"},
|
||||
"cpx": {"zh"},
|
||||
"csc": {"sgn"},
|
||||
"csd": {"sgn"},
|
||||
"cse": {"sgn"},
|
||||
"csf": {"sgn"},
|
||||
"csg": {"sgn"},
|
||||
"csl": {"sgn"},
|
||||
"csn": {"sgn"},
|
||||
"csp": {"zh"},
|
||||
"csq": {"sgn"},
|
||||
"csr": {"sgn"},
|
||||
"csx": {"sgn"},
|
||||
"czh": {"zh"},
|
||||
"czo": {"zh"},
|
||||
"doq": {"sgn"},
|
||||
"dse": {"sgn"},
|
||||
"dsl": {"sgn"},
|
||||
"dsz": {"sgn"},
|
||||
"dup": {"ms"},
|
||||
"ecs": {"sgn"},
|
||||
"ehs": {"sgn"},
|
||||
"esl": {"sgn"},
|
||||
"esn": {"sgn"},
|
||||
"eso": {"sgn"},
|
||||
"eth": {"sgn"},
|
||||
"fcs": {"sgn"},
|
||||
"fse": {"sgn"},
|
||||
"fsl": {"sgn"},
|
||||
"fss": {"sgn"},
|
||||
"gan": {"zh"},
|
||||
"gds": {"sgn"},
|
||||
"gom": {"kok"},
|
||||
"gse": {"sgn"},
|
||||
"gsg": {"sgn"},
|
||||
"gsm": {"sgn"},
|
||||
"gss": {"sgn"},
|
||||
"gus": {"sgn"},
|
||||
"hab": {"sgn"},
|
||||
"haf": {"sgn"},
|
||||
"hak": {"zh"},
|
||||
"hds": {"sgn"},
|
||||
"hji": {"ms"},
|
||||
"hks": {"sgn"},
|
||||
"hnm": {"zh"},
|
||||
"hos": {"sgn"},
|
||||
"hps": {"sgn"},
|
||||
"hsh": {"sgn"},
|
||||
"hsl": {"sgn"},
|
||||
"hsn": {"zh"},
|
||||
"icl": {"sgn"},
|
||||
"iks": {"sgn"},
|
||||
"ils": {"sgn"},
|
||||
"inl": {"sgn"},
|
||||
"ins": {"sgn"},
|
||||
"ise": {"sgn"},
|
||||
"isg": {"sgn"},
|
||||
"isr": {"sgn"},
|
||||
"jak": {"ms"},
|
||||
"jax": {"ms"},
|
||||
"jcs": {"sgn"},
|
||||
"jhs": {"sgn"},
|
||||
"jks": {"sgn"},
|
||||
"jls": {"sgn"},
|
||||
"jos": {"sgn"},
|
||||
"jsl": {"sgn"},
|
||||
"jus": {"sgn"},
|
||||
"kgi": {"sgn"},
|
||||
"knn": {"kok"},
|
||||
"kvb": {"ms"},
|
||||
"kvk": {"sgn"},
|
||||
"kvr": {"ms"},
|
||||
"kxd": {"ms"},
|
||||
"lbs": {"sgn"},
|
||||
"lce": {"ms"},
|
||||
"lcf": {"ms"},
|
||||
"lgs": {"sgn"},
|
||||
"liw": {"ms"},
|
||||
"lls": {"sgn"},
|
||||
"lsb": {"sgn"},
|
||||
"lsc": {"sgn"},
|
||||
"lsg": {"sgn"},
|
||||
"lsl": {"sgn"},
|
||||
"lsn": {"sgn"},
|
||||
"lso": {"sgn"},
|
||||
"lsp": {"sgn"},
|
||||
"lst": {"sgn"},
|
||||
"lsv": {"sgn"},
|
||||
"lsw": {"sgn"},
|
||||
"lsy": {"sgn"},
|
||||
"ltg": {"lv"},
|
||||
"luh": {"zh"},
|
||||
"lvs": {"lv"},
|
||||
"lws": {"sgn"},
|
||||
"lzh": {"zh"},
|
||||
"max": {"ms"},
|
||||
"mdl": {"sgn"},
|
||||
"meo": {"ms"},
|
||||
"mfa": {"ms"},
|
||||
"mfb": {"ms"},
|
||||
"mfs": {"sgn"},
|
||||
"min": {"ms"},
|
||||
"mnp": {"zh"},
|
||||
"mqg": {"ms"},
|
||||
"mre": {"sgn"},
|
||||
"msd": {"sgn"},
|
||||
"msi": {"ms"},
|
||||
"msr": {"sgn"},
|
||||
"mui": {"ms"},
|
||||
"mzc": {"sgn"},
|
||||
"mzg": {"sgn"},
|
||||
"mzy": {"sgn"},
|
||||
"nan": {"zh"},
|
||||
"nbs": {"sgn"},
|
||||
"ncs": {"sgn"},
|
||||
"nsi": {"sgn"},
|
||||
"nsl": {"sgn"},
|
||||
"nsp": {"sgn"},
|
||||
"nsr": {"sgn"},
|
||||
"nzs": {"sgn"},
|
||||
"okl": {"sgn"},
|
||||
"orn": {"ms"},
|
||||
"ors": {"ms"},
|
||||
"pel": {"ms"},
|
||||
"pga": {"ar"},
|
||||
"pgz": {"sgn"},
|
||||
"pks": {"sgn"},
|
||||
"prl": {"sgn"},
|
||||
"prz": {"sgn"},
|
||||
"psc": {"sgn"},
|
||||
"psd": {"sgn"},
|
||||
"pse": {"ms"},
|
||||
"psg": {"sgn"},
|
||||
"psl": {"sgn"},
|
||||
"pso": {"sgn"},
|
||||
"psp": {"sgn"},
|
||||
"psr": {"sgn"},
|
||||
"pys": {"sgn"},
|
||||
"rib": {"sgn"},
|
||||
"rms": {"sgn"},
|
||||
"rnb": {"sgn"},
|
||||
"rsi": {"sgn"},
|
||||
"rsl": {"sgn"},
|
||||
"rsm": {"sgn"},
|
||||
"rsn": {"sgn"},
|
||||
"sdl": {"sgn"},
|
||||
"sfb": {"sgn"},
|
||||
"sfs": {"sgn"},
|
||||
"sgg": {"sgn"},
|
||||
"sgx": {"sgn"},
|
||||
"shu": {"ar"},
|
||||
"sjc": {"zh"},
|
||||
"slf": {"sgn"},
|
||||
"sls": {"sgn"},
|
||||
"sqk": {"sgn"},
|
||||
"sqs": {"sgn"},
|
||||
"sqx": {"sgn"},
|
||||
"ssh": {"ar"},
|
||||
"ssp": {"sgn"},
|
||||
"ssr": {"sgn"},
|
||||
"svk": {"sgn"},
|
||||
"swc": {"sw"},
|
||||
"swh": {"sw"},
|
||||
"swl": {"sgn"},
|
||||
"syy": {"sgn"},
|
||||
"szs": {"sgn"},
|
||||
"tmw": {"ms"},
|
||||
"tse": {"sgn"},
|
||||
"tsm": {"sgn"},
|
||||
"tsq": {"sgn"},
|
||||
"tss": {"sgn"},
|
||||
"tsy": {"sgn"},
|
||||
"tza": {"sgn"},
|
||||
"ugn": {"sgn"},
|
||||
"ugy": {"sgn"},
|
||||
"ukl": {"sgn"},
|
||||
"uks": {"sgn"},
|
||||
"urk": {"ms"},
|
||||
"uzn": {"uz"},
|
||||
"uzs": {"uz"},
|
||||
"vgt": {"sgn"},
|
||||
"vkk": {"ms"},
|
||||
"vkt": {"ms"},
|
||||
"vsi": {"sgn"},
|
||||
"vsl": {"sgn"},
|
||||
"vsv": {"sgn"},
|
||||
"wbs": {"sgn"},
|
||||
"wuu": {"zh"},
|
||||
"xki": {"sgn"},
|
||||
"xml": {"sgn"},
|
||||
"xmm": {"ms"},
|
||||
"xms": {"sgn"},
|
||||
"yds": {"sgn"},
|
||||
"ygs": {"sgn"},
|
||||
"yhs": {"sgn"},
|
||||
"ysl": {"sgn"},
|
||||
"ysm": {"sgn"},
|
||||
"yue": {"zh"},
|
||||
"zib": {"sgn"},
|
||||
"zlm": {"ms"},
|
||||
"zmi": {"ms"},
|
||||
"zsl": {"sgn"},
|
||||
"zsm": {"ms"},
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
//go:build !validator_novalidatefn
|
||||
|
||||
package validator
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
func isValidateFn(fl FieldLevel) bool {
|
||||
const defaultParam = `Validate`
|
||||
|
||||
field := fl.Field()
|
||||
validateFn := cmp.Or(fl.Param(), defaultParam)
|
||||
|
||||
ok, err := tryCallValidateFn(field, validateFn)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func tryCallValidateFn(field reflect.Value, validateFn string) (bool, error) {
|
||||
method := field.MethodByName(validateFn)
|
||||
if field.CanAddr() && !method.IsValid() {
|
||||
method = field.Addr().MethodByName(validateFn)
|
||||
}
|
||||
|
||||
if !method.IsValid() {
|
||||
return false, fmt.Errorf("unable to call %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodNotFound)
|
||||
}
|
||||
|
||||
returnValues := method.Call([]reflect.Value{})
|
||||
if len(returnValues) == 0 {
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w",
|
||||
validateFn, field.Type().String(), errMethodReturnNoValues)
|
||||
}
|
||||
|
||||
firstReturnValue := returnValues[0]
|
||||
|
||||
switch firstReturnValue.Kind() {
|
||||
case reflect.Bool:
|
||||
return firstReturnValue.Bool(), nil
|
||||
case reflect.Interface:
|
||||
errorType := reflect.TypeOf((*error)(nil)).Elem()
|
||||
|
||||
if firstReturnValue.Type().Implements(errorType) {
|
||||
return firstReturnValue.IsNil(), nil
|
||||
}
|
||||
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got interface %v expect error)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
default:
|
||||
return false, fmt.Errorf("unable to use result of method %q on type %q: %w (got %v expect error or bool)",
|
||||
validateFn, field.Type().String(), errMethodReturnInvalidType, firstReturnValue.Type().String())
|
||||
}
|
||||
}
|
||||
+14
@@ -24,3 +24,17 @@ func WithPrivateFieldValidation() Option {
|
||||
v.privateFieldValidation = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithTagNameFuncBlankOmit makes a blank return from a RegisterTagNameFunc omit
|
||||
// the field from the error namespace instead of silently falling back to the
|
||||
// struct field name.
|
||||
//
|
||||
// This was made opt-in behaviour to maintain backward compatibility with
|
||||
// existing callers that rely on the fallback for error namespaces.
|
||||
//
|
||||
// It is recommended you enable this as it will be the default behaviour in v11+.
|
||||
func WithTagNameFuncBlankOmit() Option {
|
||||
return func(v *Validate) {
|
||||
v.omitBlankFieldNames = true
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -33,7 +33,7 @@ const (
|
||||
uUID3RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
|
||||
uUID4RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
|
||||
uUID5RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
|
||||
uUIDRegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
|
||||
uUIDRegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
uUID3RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-3[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
uUID4RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
|
||||
uUID5RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-5[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
|
||||
@@ -56,12 +56,12 @@ const (
|
||||
latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
|
||||
longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
|
||||
sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$`
|
||||
hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952
|
||||
hostnameRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62}){1}(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123
|
||||
hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // https://tools.ietf.org/html/rfc952
|
||||
hostnameRegexStringRFC1123 = `^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123
|
||||
fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9-]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.')
|
||||
btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address
|
||||
btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address
|
||||
btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32
|
||||
ethAddressRegexString = `^0x[0-9a-fA-F]{40}$`
|
||||
ethAddressUpperRegexString = `^0x[0-9A-F]{40}$`
|
||||
ethAddressLowerRegexString = `^0x[0-9a-f]{40}$`
|
||||
@@ -77,7 +77,7 @@ const (
|
||||
cveRegexString = `^CVE-(1999|2\d{3})-(0[^0]\d{2}|0\d[^0]\d{1}|0\d{2}[^0]|[1-9]{1}\d{3,})$` // CVE Format Id https://cve.mitre.org/cve/identifiers/syntaxchange.html
|
||||
mongodbIdRegexString = "^[a-f\\d]{24}$"
|
||||
mongodbConnStringRegexString = "^mongodb(\\+srv)?:\\/\\/(([a-zA-Z\\d]+):([a-zA-Z\\d$:\\/?#\\[\\]@]+)@)?(([a-z\\d.-]+)(:[\\d]+)?)((,(([a-z\\d.-]+)(:(\\d+))?))*)?(\\/[a-zA-Z-_]{1,64})?(\\?(([a-zA-Z]+)=([a-zA-Z\\d]+))(&(([a-zA-Z\\d]+)=([a-zA-Z\\d]+))?)*)?$"
|
||||
cronRegexString = `(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|((\*|\d+)(\/|-)\d+)|\d+|\*) ?){5,7})`
|
||||
cronRegexString = `^((@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|(([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])( +([A-Za-z0-9*?][A-Za-z0-9*?/,#L-]+|[*?0-9])){4,6}))$`
|
||||
spicedbIDRegexString = `^(([a-zA-Z0-9/_|\-=+]{1,})|\*)$`
|
||||
spicedbPermissionRegexString = "^([a-z][a-z0-9_]{1,62}[a-z0-9])?$"
|
||||
spicedbTypeRegexString = "^([a-z][a-z0-9_]{1,61}[a-z0-9]/)?[a-z][a-z0-9_]{1,62}[a-z0-9]$"
|
||||
|
||||
+15
@@ -1466,6 +1466,11 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
return t
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: "timezone",
|
||||
translation: "{0} must be a valid time zone",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "postcode_iso3166_alpha2",
|
||||
translation: "{0} does not match postcode format of {1} country",
|
||||
@@ -1504,11 +1509,21 @@ func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (er
|
||||
translation: "{0} must be a valid image",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "mimetype",
|
||||
translation: "{0} must be a valid MIME type",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "cve",
|
||||
translation: "{0} must be a valid cve identifier",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "bcp47_strict_language_tag",
|
||||
translation: "{0} must be a valid BCP 47 language tag",
|
||||
override: false,
|
||||
},
|
||||
{
|
||||
tag: "validateFn",
|
||||
translation: "{0} must be a valid object",
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//go:build validator_novalidatefn
|
||||
|
||||
package validator
|
||||
|
||||
func isValidateFn(fl FieldLevel) bool {
|
||||
panic("validateFn is not supported with 'no-validate-fn' tag")
|
||||
}
|
||||
+20
-6
@@ -116,7 +116,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr
|
||||
|
||||
if ct.hasTag {
|
||||
if kind == reflect.Invalid {
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
} else {
|
||||
@@ -138,7 +138,7 @@ func (v *validate) traverseField(ctx context.Context, parent reflect.Value, curr
|
||||
return
|
||||
}
|
||||
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
} else {
|
||||
@@ -192,7 +192,9 @@ OUTER:
|
||||
// VarWithField - this allows for validating against each field within the struct against a specific value
|
||||
// pretty handy in certain situations
|
||||
if len(cf.name) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
if len(cf.altName) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
}
|
||||
structNs = append(append(structNs, cf.name...), '.')
|
||||
}
|
||||
|
||||
@@ -212,7 +214,9 @@ OUTER:
|
||||
// VarWithField - this allows for validating against each field within the struct against a specific value
|
||||
// pretty handy in certain situations
|
||||
if len(cf.name) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
if len(cf.altName) > 0 {
|
||||
ns = append(append(ns, cf.altName...), '.')
|
||||
}
|
||||
structNs = append(append(structNs, cf.name...), '.')
|
||||
}
|
||||
|
||||
@@ -409,7 +413,7 @@ OUTER:
|
||||
|
||||
if ct.isBlockEnd || ct.next == nil {
|
||||
// if we get here, no valid 'or' value and no more tags
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
@@ -468,7 +472,7 @@ OUTER:
|
||||
v.ct = ct
|
||||
|
||||
if !ct.fn(ctx, v) {
|
||||
v.str1 = string(append(ns, cf.altName...))
|
||||
v.str1 = appendAltName(ns, cf.altName)
|
||||
|
||||
if v.v.hasTagNameFunc {
|
||||
v.str2 = string(append(structNs, cf.name...))
|
||||
@@ -499,6 +503,16 @@ OUTER:
|
||||
}
|
||||
}
|
||||
|
||||
func appendAltName(ns []byte, altName string) string {
|
||||
if len(altName) > 0 {
|
||||
return string(append(ns, altName...))
|
||||
}
|
||||
if n := len(ns); n > 0 && ns[n-1] == '.' {
|
||||
return string(ns[:n-1])
|
||||
}
|
||||
return string(ns)
|
||||
}
|
||||
|
||||
func getValue(val reflect.Value) interface{} {
|
||||
if val.CanInterface() {
|
||||
return val.Interface()
|
||||
|
||||
+6
-5
@@ -68,7 +68,7 @@ type FilterFunc func(ns []byte) bool
|
||||
|
||||
// CustomTypeFunc allows for overriding or adding custom field type handler functions
|
||||
// field = field value of the type to return a value to be validated
|
||||
// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29
|
||||
// example Valuer from sql driver see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29
|
||||
type CustomTypeFunc func(field reflect.Value) interface{}
|
||||
|
||||
// TagNameFunc allows for adding of a custom tag name parser
|
||||
@@ -96,6 +96,7 @@ type Validate struct {
|
||||
hasTagNameFunc bool
|
||||
requiredStructEnabled bool
|
||||
privateFieldValidation bool
|
||||
omitBlankFieldNames bool
|
||||
}
|
||||
|
||||
// New returns a new instance of 'validate' with sane defaults.
|
||||
@@ -428,7 +429,7 @@ func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn Filt
|
||||
}
|
||||
|
||||
// StructPartial validates the fields passed in only, ignoring all others.
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -439,7 +440,7 @@ func (v *Validate) StructPartial(s interface{}, fields ...string) error {
|
||||
|
||||
// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual
|
||||
// validation information via context.Context
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -514,7 +515,7 @@ func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields .
|
||||
}
|
||||
|
||||
// StructExcept validates all fields except the ones passed in.
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
@@ -525,7 +526,7 @@ func (v *Validate) StructExcept(s interface{}, fields ...string) error {
|
||||
|
||||
// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual
|
||||
// validation information via context.Context
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// Fields may be provided in a namespaced fashion relative to the struct provided
|
||||
// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name
|
||||
//
|
||||
// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise.
|
||||
|
||||
+81
-22
@@ -3,6 +3,7 @@ package runewidth
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/clipperhouse/uax29/v2/graphemes"
|
||||
)
|
||||
@@ -23,10 +24,48 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
zerowidth table // combining + nonprint merged for faster zero-width lookup
|
||||
widewidth table // ambiguous + doublewidth merged for EA path
|
||||
)
|
||||
|
||||
func init() {
|
||||
zerowidth = mergeIntervals(combining, nonprint)
|
||||
widewidth = mergeIntervals(ambiguous, doublewidth)
|
||||
handleEnv()
|
||||
}
|
||||
|
||||
func mergeIntervals(t1, t2 table) table {
|
||||
merged := make(table, 0, len(t1)+len(t2))
|
||||
i, j := 0, 0
|
||||
for i < len(t1) && j < len(t2) {
|
||||
if t1[i].first <= t2[j].first {
|
||||
merged = append(merged, t1[i])
|
||||
i++
|
||||
} else {
|
||||
merged = append(merged, t2[j])
|
||||
j++
|
||||
}
|
||||
}
|
||||
merged = append(merged, t1[i:]...)
|
||||
merged = append(merged, t2[j:]...)
|
||||
if len(merged) == 0 {
|
||||
return merged
|
||||
}
|
||||
result := merged[:1]
|
||||
for _, iv := range merged[1:] {
|
||||
last := &result[len(result)-1]
|
||||
if iv.first <= last.last+1 {
|
||||
if iv.last > last.last {
|
||||
last.last = iv.last
|
||||
}
|
||||
} else {
|
||||
result = append(result, iv)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func handleEnv() {
|
||||
env := os.Getenv("RUNEWIDTH_EASTASIAN")
|
||||
if env == "" {
|
||||
@@ -51,15 +90,6 @@ type interval struct {
|
||||
|
||||
type table []interval
|
||||
|
||||
func inTables(r rune, ts ...table) bool {
|
||||
for _, t := range ts {
|
||||
if inTable(r, t) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func inTable(r rune, t table) bool {
|
||||
if r < t[0].first {
|
||||
return false
|
||||
@@ -130,9 +160,7 @@ func (c *Condition) RuneWidth(r rune) int {
|
||||
return 0
|
||||
case r < 0x300:
|
||||
return 1
|
||||
case inTable(r, narrow):
|
||||
return 1
|
||||
case inTables(r, nonprint, combining):
|
||||
case inTable(r, zerowidth):
|
||||
return 0
|
||||
case inTable(r, doublewidth):
|
||||
return 2
|
||||
@@ -141,13 +169,13 @@ func (c *Condition) RuneWidth(r rune) int {
|
||||
}
|
||||
} else {
|
||||
switch {
|
||||
case inTables(r, nonprint, combining):
|
||||
case inTable(r, zerowidth):
|
||||
return 0
|
||||
case inTable(r, narrow):
|
||||
return 1
|
||||
case inTables(r, ambiguous, doublewidth):
|
||||
case inTable(r, widewidth):
|
||||
return 2
|
||||
case !c.StrictEmojiNeutral && inTables(r, ambiguous, emoji, narrow):
|
||||
case !c.StrictEmojiNeutral && inTable(r, emoji):
|
||||
return 2
|
||||
default:
|
||||
return 1
|
||||
@@ -178,6 +206,22 @@ func (c *Condition) CreateLUT() {
|
||||
|
||||
// StringWidth return width as you can see
|
||||
func (c *Condition) StringWidth(s string) (width int) {
|
||||
if len(s) > 0 && len(s) <= utf8.UTFMax {
|
||||
r, size := utf8.DecodeRuneInString(s)
|
||||
if size == len(s) {
|
||||
return c.RuneWidth(r)
|
||||
}
|
||||
}
|
||||
// ASCII fast path: no grapheme clustering needed for pure ASCII
|
||||
if isAllASCII(s) {
|
||||
for i := 0; i < len(s); i++ {
|
||||
b := s[i]
|
||||
if b >= 0x20 && b != 0x7F {
|
||||
width++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
g := graphemes.FromString(s)
|
||||
for g.Next() {
|
||||
var chWidth int
|
||||
@@ -192,6 +236,15 @@ func (c *Condition) StringWidth(s string) (width int) {
|
||||
return
|
||||
}
|
||||
|
||||
func isAllASCII(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] >= 0x80 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Truncate return string truncated with w cells
|
||||
func (c *Condition) Truncate(s string, w int, tail string) string {
|
||||
if c.StringWidth(s) <= w {
|
||||
@@ -257,24 +310,25 @@ func (c *Condition) TruncateLeft(s string, w int, prefix string) string {
|
||||
// Wrap return string wrapped with w cells
|
||||
func (c *Condition) Wrap(s string, w int) string {
|
||||
width := 0
|
||||
out := ""
|
||||
var out strings.Builder
|
||||
out.Grow(len(s) + len(s)/w + 1)
|
||||
for _, r := range s {
|
||||
cw := c.RuneWidth(r)
|
||||
if r == '\n' {
|
||||
out += string(r)
|
||||
out.WriteRune(r)
|
||||
width = 0
|
||||
continue
|
||||
} else if width+cw > w {
|
||||
out += "\n"
|
||||
out.WriteByte('\n')
|
||||
width = 0
|
||||
out += string(r)
|
||||
out.WriteRune(r)
|
||||
width += cw
|
||||
continue
|
||||
}
|
||||
out += string(r)
|
||||
out.WriteRune(r)
|
||||
width += cw
|
||||
}
|
||||
return out
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// FillLeft return string filled in left by spaces in w cells
|
||||
@@ -313,7 +367,12 @@ func RuneWidth(r rune) int {
|
||||
|
||||
// IsAmbiguousWidth returns whether is ambiguous width or not.
|
||||
func IsAmbiguousWidth(r rune) bool {
|
||||
return inTables(r, private, ambiguous)
|
||||
return inTable(r, private) || inTable(r, ambiguous)
|
||||
}
|
||||
|
||||
// IsCombiningWidth returns whether is combining width or not.
|
||||
func IsCombiningWidth(r rune) bool {
|
||||
return inTable(r, combining)
|
||||
}
|
||||
|
||||
// IsNeutralWidth returns whether is neutral width or not.
|
||||
|
||||
+344
-306
@@ -5,47 +5,50 @@ package runewidth
|
||||
var combining = table{
|
||||
{0x0300, 0x036F}, {0x0483, 0x0489}, {0x07EB, 0x07F3},
|
||||
{0x0C00, 0x0C00}, {0x0C04, 0x0C04}, {0x0CF3, 0x0CF3},
|
||||
{0x0D00, 0x0D01}, {0x135D, 0x135F}, {0x1A7F, 0x1A7F},
|
||||
{0x1AB0, 0x1ACE}, {0x1B6B, 0x1B73}, {0x1DC0, 0x1DFF},
|
||||
{0x0D00, 0x0D01}, {0x135D, 0x135F}, {0x180B, 0x180D},
|
||||
{0x180F, 0x180F}, {0x1A7F, 0x1A7F}, {0x1AB0, 0x1ADD},
|
||||
{0x1AE0, 0x1AEB}, {0x1B6B, 0x1B73}, {0x1DC0, 0x1DFF},
|
||||
{0x20D0, 0x20F0}, {0x2CEF, 0x2CF1}, {0x2DE0, 0x2DFF},
|
||||
{0x3099, 0x309A}, {0xA66F, 0xA672}, {0xA674, 0xA67D},
|
||||
{0xA69E, 0xA69F}, {0xA6F0, 0xA6F1}, {0xA8E0, 0xA8F1},
|
||||
{0xFE20, 0xFE2F}, {0x101FD, 0x101FD}, {0x10376, 0x1037A},
|
||||
{0x10EAB, 0x10EAC}, {0x10F46, 0x10F50}, {0x10F82, 0x10F85},
|
||||
{0x11300, 0x11301}, {0x1133B, 0x1133C}, {0x11366, 0x1136C},
|
||||
{0x11370, 0x11374}, {0x16AF0, 0x16AF4}, {0x1CF00, 0x1CF2D},
|
||||
{0x1CF30, 0x1CF46}, {0x1D165, 0x1D169}, {0x1D16D, 0x1D172},
|
||||
{0x1D17B, 0x1D182}, {0x1D185, 0x1D18B}, {0x1D1AA, 0x1D1AD},
|
||||
{0x1D242, 0x1D244}, {0x1E000, 0x1E006}, {0x1E008, 0x1E018},
|
||||
{0x1E01B, 0x1E021}, {0x1E023, 0x1E024}, {0x1E026, 0x1E02A},
|
||||
{0x1E08F, 0x1E08F}, {0x1E8D0, 0x1E8D6},
|
||||
{0xFE00, 0xFE0F}, {0xFE20, 0xFE2F}, {0x101FD, 0x101FD},
|
||||
{0x10376, 0x1037A}, {0x10EAB, 0x10EAC}, {0x10F46, 0x10F50},
|
||||
{0x10F82, 0x10F85}, {0x11300, 0x11301}, {0x1133B, 0x1133C},
|
||||
{0x11366, 0x1136C}, {0x11370, 0x11374}, {0x16AF0, 0x16AF4},
|
||||
{0x1CF00, 0x1CF2D}, {0x1CF30, 0x1CF46}, {0x1D165, 0x1D169},
|
||||
{0x1D16D, 0x1D172}, {0x1D17B, 0x1D182}, {0x1D185, 0x1D18B},
|
||||
{0x1D1AA, 0x1D1AD}, {0x1D242, 0x1D244}, {0x1E000, 0x1E006},
|
||||
{0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E023, 0x1E024},
|
||||
{0x1E026, 0x1E02A}, {0x1E08F, 0x1E08F}, {0x1E8D0, 0x1E8D6},
|
||||
{0xE0100, 0xE01EF},
|
||||
}
|
||||
|
||||
var doublewidth = table{
|
||||
{0x1100, 0x115F}, {0x231A, 0x231B}, {0x2329, 0x232A},
|
||||
{0x23E9, 0x23EC}, {0x23F0, 0x23F0}, {0x23F3, 0x23F3},
|
||||
{0x25FD, 0x25FE}, {0x2614, 0x2615}, {0x2648, 0x2653},
|
||||
{0x267F, 0x267F}, {0x2693, 0x2693}, {0x26A1, 0x26A1},
|
||||
{0x26AA, 0x26AB}, {0x26BD, 0x26BE}, {0x26C4, 0x26C5},
|
||||
{0x26CE, 0x26CE}, {0x26D4, 0x26D4}, {0x26EA, 0x26EA},
|
||||
{0x26F2, 0x26F3}, {0x26F5, 0x26F5}, {0x26FA, 0x26FA},
|
||||
{0x26FD, 0x26FD}, {0x2705, 0x2705}, {0x270A, 0x270B},
|
||||
{0x2728, 0x2728}, {0x274C, 0x274C}, {0x274E, 0x274E},
|
||||
{0x2753, 0x2755}, {0x2757, 0x2757}, {0x2795, 0x2797},
|
||||
{0x27B0, 0x27B0}, {0x27BF, 0x27BF}, {0x2B1B, 0x2B1C},
|
||||
{0x2B50, 0x2B50}, {0x2B55, 0x2B55}, {0x2E80, 0x2E99},
|
||||
{0x2E9B, 0x2EF3}, {0x2F00, 0x2FD5}, {0x2FF0, 0x303E},
|
||||
{0x3041, 0x3096}, {0x3099, 0x30FF}, {0x3105, 0x312F},
|
||||
{0x3131, 0x318E}, {0x3190, 0x31E3}, {0x31EF, 0x321E},
|
||||
{0x3220, 0x3247}, {0x3250, 0x4DBF}, {0x4E00, 0xA48C},
|
||||
{0xA490, 0xA4C6}, {0xA960, 0xA97C}, {0xAC00, 0xD7A3},
|
||||
{0xF900, 0xFAFF}, {0xFE10, 0xFE19}, {0xFE30, 0xFE52},
|
||||
{0xFE54, 0xFE66}, {0xFE68, 0xFE6B}, {0xFF01, 0xFF60},
|
||||
{0xFFE0, 0xFFE6}, {0x16FE0, 0x16FE4}, {0x16FF0, 0x16FF1},
|
||||
{0x17000, 0x187F7}, {0x18800, 0x18CD5}, {0x18D00, 0x18D08},
|
||||
{0x1AFF0, 0x1AFF3}, {0x1AFF5, 0x1AFFB}, {0x1AFFD, 0x1AFFE},
|
||||
{0x1B000, 0x1B122}, {0x1B132, 0x1B132}, {0x1B150, 0x1B152},
|
||||
{0x1B155, 0x1B155}, {0x1B164, 0x1B167}, {0x1B170, 0x1B2FB},
|
||||
{0x25FD, 0x25FE}, {0x2614, 0x2615}, {0x2630, 0x2637},
|
||||
{0x2648, 0x2653}, {0x267F, 0x267F}, {0x268A, 0x268F},
|
||||
{0x2693, 0x2693}, {0x26A1, 0x26A1}, {0x26AA, 0x26AB},
|
||||
{0x26BD, 0x26BE}, {0x26C4, 0x26C5}, {0x26CE, 0x26CE},
|
||||
{0x26D4, 0x26D4}, {0x26EA, 0x26EA}, {0x26F2, 0x26F3},
|
||||
{0x26F5, 0x26F5}, {0x26FA, 0x26FA}, {0x26FD, 0x26FD},
|
||||
{0x2705, 0x2705}, {0x270A, 0x270B}, {0x2728, 0x2728},
|
||||
{0x274C, 0x274C}, {0x274E, 0x274E}, {0x2753, 0x2755},
|
||||
{0x2757, 0x2757}, {0x2795, 0x2797}, {0x27B0, 0x27B0},
|
||||
{0x27BF, 0x27BF}, {0x2B1B, 0x2B1C}, {0x2B50, 0x2B50},
|
||||
{0x2B55, 0x2B55}, {0x2E80, 0x2E99}, {0x2E9B, 0x2EF3},
|
||||
{0x2F00, 0x2FD5}, {0x2FF0, 0x303E}, {0x3041, 0x3096},
|
||||
{0x3099, 0x30FF}, {0x3105, 0x312F}, {0x3131, 0x318E},
|
||||
{0x3190, 0x31E5}, {0x31EF, 0x321E}, {0x3220, 0x3247},
|
||||
{0x3250, 0xA48C}, {0xA490, 0xA4C6}, {0xA960, 0xA97C},
|
||||
{0xAC00, 0xD7A3}, {0xF900, 0xFAFF}, {0xFE10, 0xFE19},
|
||||
{0xFE30, 0xFE52}, {0xFE54, 0xFE66}, {0xFE68, 0xFE6B},
|
||||
{0xFF01, 0xFF60}, {0xFFE0, 0xFFE6}, {0x16FE0, 0x16FE4},
|
||||
{0x16FF0, 0x16FF6}, {0x17000, 0x18CD5}, {0x18CFF, 0x18D1E},
|
||||
{0x18D80, 0x18DF2}, {0x1AFF0, 0x1AFF3}, {0x1AFF5, 0x1AFFB},
|
||||
{0x1AFFD, 0x1AFFE}, {0x1B000, 0x1B122}, {0x1B132, 0x1B132},
|
||||
{0x1B150, 0x1B152}, {0x1B155, 0x1B155}, {0x1B164, 0x1B167},
|
||||
{0x1B170, 0x1B2FB}, {0x1D300, 0x1D356}, {0x1D360, 0x1D376},
|
||||
{0x1F004, 0x1F004}, {0x1F0CF, 0x1F0CF}, {0x1F18E, 0x1F18E},
|
||||
{0x1F191, 0x1F19A}, {0x1F200, 0x1F202}, {0x1F210, 0x1F23B},
|
||||
{0x1F240, 0x1F248}, {0x1F250, 0x1F251}, {0x1F260, 0x1F265},
|
||||
@@ -56,12 +59,12 @@ var doublewidth = table{
|
||||
{0x1F54B, 0x1F54E}, {0x1F550, 0x1F567}, {0x1F57A, 0x1F57A},
|
||||
{0x1F595, 0x1F596}, {0x1F5A4, 0x1F5A4}, {0x1F5FB, 0x1F64F},
|
||||
{0x1F680, 0x1F6C5}, {0x1F6CC, 0x1F6CC}, {0x1F6D0, 0x1F6D2},
|
||||
{0x1F6D5, 0x1F6D7}, {0x1F6DC, 0x1F6DF}, {0x1F6EB, 0x1F6EC},
|
||||
{0x1F6D5, 0x1F6D8}, {0x1F6DC, 0x1F6DF}, {0x1F6EB, 0x1F6EC},
|
||||
{0x1F6F4, 0x1F6FC}, {0x1F7E0, 0x1F7EB}, {0x1F7F0, 0x1F7F0},
|
||||
{0x1F90C, 0x1F93A}, {0x1F93C, 0x1F945}, {0x1F947, 0x1F9FF},
|
||||
{0x1FA70, 0x1FA7C}, {0x1FA80, 0x1FA88}, {0x1FA90, 0x1FABD},
|
||||
{0x1FABF, 0x1FAC5}, {0x1FACE, 0x1FADB}, {0x1FAE0, 0x1FAE8},
|
||||
{0x1FAF0, 0x1FAF8}, {0x20000, 0x2FFFD}, {0x30000, 0x3FFFD},
|
||||
{0x1FA70, 0x1FA7C}, {0x1FA80, 0x1FA8A}, {0x1FA8E, 0x1FAC6},
|
||||
{0x1FAC8, 0x1FAC8}, {0x1FACD, 0x1FADC}, {0x1FADF, 0x1FAEA},
|
||||
{0x1FAEF, 0x1FAF8}, {0x20000, 0x2FFFD}, {0x30000, 0x3FFFD},
|
||||
}
|
||||
|
||||
var ambiguous = table{
|
||||
@@ -121,10 +124,9 @@ var ambiguous = table{
|
||||
{0x26F4, 0x26F4}, {0x26F6, 0x26F9}, {0x26FB, 0x26FC},
|
||||
{0x26FE, 0x26FF}, {0x273D, 0x273D}, {0x2776, 0x277F},
|
||||
{0x2B56, 0x2B59}, {0x3248, 0x324F}, {0xE000, 0xF8FF},
|
||||
{0xFE00, 0xFE0F}, {0xFFFD, 0xFFFD}, {0x1F100, 0x1F10A},
|
||||
{0x1F110, 0x1F12D}, {0x1F130, 0x1F169}, {0x1F170, 0x1F18D},
|
||||
{0x1F18F, 0x1F190}, {0x1F19B, 0x1F1AC}, {0xE0100, 0xE01EF},
|
||||
{0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD},
|
||||
{0xFFFD, 0xFFFD}, {0x1F100, 0x1F10A}, {0x1F110, 0x1F12D},
|
||||
{0x1F130, 0x1F169}, {0x1F170, 0x1F18D}, {0x1F18F, 0x1F190},
|
||||
{0x1F19B, 0x1F1AC}, {0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD},
|
||||
}
|
||||
var narrow = table{
|
||||
{0x0020, 0x007E}, {0x00A2, 0x00A3}, {0x00A5, 0x00A6},
|
||||
@@ -159,115 +161,116 @@ var neutral = table{
|
||||
{0x0600, 0x070D}, {0x070F, 0x074A}, {0x074D, 0x07B1},
|
||||
{0x07C0, 0x07FA}, {0x07FD, 0x082D}, {0x0830, 0x083E},
|
||||
{0x0840, 0x085B}, {0x085E, 0x085E}, {0x0860, 0x086A},
|
||||
{0x0870, 0x088E}, {0x0890, 0x0891}, {0x0898, 0x0983},
|
||||
{0x0985, 0x098C}, {0x098F, 0x0990}, {0x0993, 0x09A8},
|
||||
{0x09AA, 0x09B0}, {0x09B2, 0x09B2}, {0x09B6, 0x09B9},
|
||||
{0x09BC, 0x09C4}, {0x09C7, 0x09C8}, {0x09CB, 0x09CE},
|
||||
{0x09D7, 0x09D7}, {0x09DC, 0x09DD}, {0x09DF, 0x09E3},
|
||||
{0x09E6, 0x09FE}, {0x0A01, 0x0A03}, {0x0A05, 0x0A0A},
|
||||
{0x0A0F, 0x0A10}, {0x0A13, 0x0A28}, {0x0A2A, 0x0A30},
|
||||
{0x0A32, 0x0A33}, {0x0A35, 0x0A36}, {0x0A38, 0x0A39},
|
||||
{0x0A3C, 0x0A3C}, {0x0A3E, 0x0A42}, {0x0A47, 0x0A48},
|
||||
{0x0A4B, 0x0A4D}, {0x0A51, 0x0A51}, {0x0A59, 0x0A5C},
|
||||
{0x0A5E, 0x0A5E}, {0x0A66, 0x0A76}, {0x0A81, 0x0A83},
|
||||
{0x0A85, 0x0A8D}, {0x0A8F, 0x0A91}, {0x0A93, 0x0AA8},
|
||||
{0x0AAA, 0x0AB0}, {0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9},
|
||||
{0x0ABC, 0x0AC5}, {0x0AC7, 0x0AC9}, {0x0ACB, 0x0ACD},
|
||||
{0x0AD0, 0x0AD0}, {0x0AE0, 0x0AE3}, {0x0AE6, 0x0AF1},
|
||||
{0x0AF9, 0x0AFF}, {0x0B01, 0x0B03}, {0x0B05, 0x0B0C},
|
||||
{0x0B0F, 0x0B10}, {0x0B13, 0x0B28}, {0x0B2A, 0x0B30},
|
||||
{0x0B32, 0x0B33}, {0x0B35, 0x0B39}, {0x0B3C, 0x0B44},
|
||||
{0x0B47, 0x0B48}, {0x0B4B, 0x0B4D}, {0x0B55, 0x0B57},
|
||||
{0x0B5C, 0x0B5D}, {0x0B5F, 0x0B63}, {0x0B66, 0x0B77},
|
||||
{0x0B82, 0x0B83}, {0x0B85, 0x0B8A}, {0x0B8E, 0x0B90},
|
||||
{0x0B92, 0x0B95}, {0x0B99, 0x0B9A}, {0x0B9C, 0x0B9C},
|
||||
{0x0B9E, 0x0B9F}, {0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA},
|
||||
{0x0BAE, 0x0BB9}, {0x0BBE, 0x0BC2}, {0x0BC6, 0x0BC8},
|
||||
{0x0BCA, 0x0BCD}, {0x0BD0, 0x0BD0}, {0x0BD7, 0x0BD7},
|
||||
{0x0BE6, 0x0BFA}, {0x0C00, 0x0C0C}, {0x0C0E, 0x0C10},
|
||||
{0x0C12, 0x0C28}, {0x0C2A, 0x0C39}, {0x0C3C, 0x0C44},
|
||||
{0x0C46, 0x0C48}, {0x0C4A, 0x0C4D}, {0x0C55, 0x0C56},
|
||||
{0x0C58, 0x0C5A}, {0x0C5D, 0x0C5D}, {0x0C60, 0x0C63},
|
||||
{0x0C66, 0x0C6F}, {0x0C77, 0x0C8C}, {0x0C8E, 0x0C90},
|
||||
{0x0C92, 0x0CA8}, {0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9},
|
||||
{0x0CBC, 0x0CC4}, {0x0CC6, 0x0CC8}, {0x0CCA, 0x0CCD},
|
||||
{0x0CD5, 0x0CD6}, {0x0CDD, 0x0CDE}, {0x0CE0, 0x0CE3},
|
||||
{0x0CE6, 0x0CEF}, {0x0CF1, 0x0CF3}, {0x0D00, 0x0D0C},
|
||||
{0x0D0E, 0x0D10}, {0x0D12, 0x0D44}, {0x0D46, 0x0D48},
|
||||
{0x0D4A, 0x0D4F}, {0x0D54, 0x0D63}, {0x0D66, 0x0D7F},
|
||||
{0x0D81, 0x0D83}, {0x0D85, 0x0D96}, {0x0D9A, 0x0DB1},
|
||||
{0x0DB3, 0x0DBB}, {0x0DBD, 0x0DBD}, {0x0DC0, 0x0DC6},
|
||||
{0x0DCA, 0x0DCA}, {0x0DCF, 0x0DD4}, {0x0DD6, 0x0DD6},
|
||||
{0x0DD8, 0x0DDF}, {0x0DE6, 0x0DEF}, {0x0DF2, 0x0DF4},
|
||||
{0x0E01, 0x0E3A}, {0x0E3F, 0x0E5B}, {0x0E81, 0x0E82},
|
||||
{0x0E84, 0x0E84}, {0x0E86, 0x0E8A}, {0x0E8C, 0x0EA3},
|
||||
{0x0EA5, 0x0EA5}, {0x0EA7, 0x0EBD}, {0x0EC0, 0x0EC4},
|
||||
{0x0EC6, 0x0EC6}, {0x0EC8, 0x0ECE}, {0x0ED0, 0x0ED9},
|
||||
{0x0EDC, 0x0EDF}, {0x0F00, 0x0F47}, {0x0F49, 0x0F6C},
|
||||
{0x0F71, 0x0F97}, {0x0F99, 0x0FBC}, {0x0FBE, 0x0FCC},
|
||||
{0x0FCE, 0x0FDA}, {0x1000, 0x10C5}, {0x10C7, 0x10C7},
|
||||
{0x10CD, 0x10CD}, {0x10D0, 0x10FF}, {0x1160, 0x1248},
|
||||
{0x124A, 0x124D}, {0x1250, 0x1256}, {0x1258, 0x1258},
|
||||
{0x125A, 0x125D}, {0x1260, 0x1288}, {0x128A, 0x128D},
|
||||
{0x1290, 0x12B0}, {0x12B2, 0x12B5}, {0x12B8, 0x12BE},
|
||||
{0x12C0, 0x12C0}, {0x12C2, 0x12C5}, {0x12C8, 0x12D6},
|
||||
{0x12D8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135A},
|
||||
{0x135D, 0x137C}, {0x1380, 0x1399}, {0x13A0, 0x13F5},
|
||||
{0x13F8, 0x13FD}, {0x1400, 0x169C}, {0x16A0, 0x16F8},
|
||||
{0x1700, 0x1715}, {0x171F, 0x1736}, {0x1740, 0x1753},
|
||||
{0x1760, 0x176C}, {0x176E, 0x1770}, {0x1772, 0x1773},
|
||||
{0x1780, 0x17DD}, {0x17E0, 0x17E9}, {0x17F0, 0x17F9},
|
||||
{0x1800, 0x1819}, {0x1820, 0x1878}, {0x1880, 0x18AA},
|
||||
{0x18B0, 0x18F5}, {0x1900, 0x191E}, {0x1920, 0x192B},
|
||||
{0x1930, 0x193B}, {0x1940, 0x1940}, {0x1944, 0x196D},
|
||||
{0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9},
|
||||
{0x19D0, 0x19DA}, {0x19DE, 0x1A1B}, {0x1A1E, 0x1A5E},
|
||||
{0x1A60, 0x1A7C}, {0x1A7F, 0x1A89}, {0x1A90, 0x1A99},
|
||||
{0x1AA0, 0x1AAD}, {0x1AB0, 0x1ACE}, {0x1B00, 0x1B4C},
|
||||
{0x1B50, 0x1B7E}, {0x1B80, 0x1BF3}, {0x1BFC, 0x1C37},
|
||||
{0x1C3B, 0x1C49}, {0x1C4D, 0x1C88}, {0x1C90, 0x1CBA},
|
||||
{0x1CBD, 0x1CC7}, {0x1CD0, 0x1CFA}, {0x1D00, 0x1F15},
|
||||
{0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, {0x1F48, 0x1F4D},
|
||||
{0x1F50, 0x1F57}, {0x1F59, 0x1F59}, {0x1F5B, 0x1F5B},
|
||||
{0x1F5D, 0x1F5D}, {0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4},
|
||||
{0x1FB6, 0x1FC4}, {0x1FC6, 0x1FD3}, {0x1FD6, 0x1FDB},
|
||||
{0x1FDD, 0x1FEF}, {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFE},
|
||||
{0x2000, 0x200F}, {0x2011, 0x2012}, {0x2017, 0x2017},
|
||||
{0x201A, 0x201B}, {0x201E, 0x201F}, {0x2023, 0x2023},
|
||||
{0x2028, 0x202F}, {0x2031, 0x2031}, {0x2034, 0x2034},
|
||||
{0x2036, 0x203A}, {0x203C, 0x203D}, {0x203F, 0x2064},
|
||||
{0x2066, 0x2071}, {0x2075, 0x207E}, {0x2080, 0x2080},
|
||||
{0x2085, 0x208E}, {0x2090, 0x209C}, {0x20A0, 0x20A8},
|
||||
{0x20AA, 0x20AB}, {0x20AD, 0x20C0}, {0x20D0, 0x20F0},
|
||||
{0x2100, 0x2102}, {0x2104, 0x2104}, {0x2106, 0x2108},
|
||||
{0x210A, 0x2112}, {0x2114, 0x2115}, {0x2117, 0x2120},
|
||||
{0x2123, 0x2125}, {0x2127, 0x212A}, {0x212C, 0x2152},
|
||||
{0x2155, 0x215A}, {0x215F, 0x215F}, {0x216C, 0x216F},
|
||||
{0x217A, 0x2188}, {0x218A, 0x218B}, {0x219A, 0x21B7},
|
||||
{0x21BA, 0x21D1}, {0x21D3, 0x21D3}, {0x21D5, 0x21E6},
|
||||
{0x21E8, 0x21FF}, {0x2201, 0x2201}, {0x2204, 0x2206},
|
||||
{0x2209, 0x220A}, {0x220C, 0x220E}, {0x2210, 0x2210},
|
||||
{0x2212, 0x2214}, {0x2216, 0x2219}, {0x221B, 0x221C},
|
||||
{0x2221, 0x2222}, {0x2224, 0x2224}, {0x2226, 0x2226},
|
||||
{0x222D, 0x222D}, {0x222F, 0x2233}, {0x2238, 0x223B},
|
||||
{0x223E, 0x2247}, {0x2249, 0x224B}, {0x224D, 0x2251},
|
||||
{0x2253, 0x225F}, {0x2262, 0x2263}, {0x2268, 0x2269},
|
||||
{0x226C, 0x226D}, {0x2270, 0x2281}, {0x2284, 0x2285},
|
||||
{0x2288, 0x2294}, {0x2296, 0x2298}, {0x229A, 0x22A4},
|
||||
{0x22A6, 0x22BE}, {0x22C0, 0x2311}, {0x2313, 0x2319},
|
||||
{0x231C, 0x2328}, {0x232B, 0x23E8}, {0x23ED, 0x23EF},
|
||||
{0x23F1, 0x23F2}, {0x23F4, 0x2426}, {0x2440, 0x244A},
|
||||
{0x24EA, 0x24EA}, {0x254C, 0x254F}, {0x2574, 0x257F},
|
||||
{0x2590, 0x2591}, {0x2596, 0x259F}, {0x25A2, 0x25A2},
|
||||
{0x25AA, 0x25B1}, {0x25B4, 0x25B5}, {0x25B8, 0x25BB},
|
||||
{0x25BE, 0x25BF}, {0x25C2, 0x25C5}, {0x25C9, 0x25CA},
|
||||
{0x25CC, 0x25CD}, {0x25D2, 0x25E1}, {0x25E6, 0x25EE},
|
||||
{0x25F0, 0x25FC}, {0x25FF, 0x2604}, {0x2607, 0x2608},
|
||||
{0x260A, 0x260D}, {0x2610, 0x2613}, {0x2616, 0x261B},
|
||||
{0x261D, 0x261D}, {0x261F, 0x263F}, {0x2641, 0x2641},
|
||||
{0x2643, 0x2647}, {0x2654, 0x265F}, {0x2662, 0x2662},
|
||||
{0x2666, 0x2666}, {0x266B, 0x266B}, {0x266E, 0x266E},
|
||||
{0x2670, 0x267E}, {0x2680, 0x2692}, {0x2694, 0x269D},
|
||||
{0x0870, 0x0891}, {0x0897, 0x0983}, {0x0985, 0x098C},
|
||||
{0x098F, 0x0990}, {0x0993, 0x09A8}, {0x09AA, 0x09B0},
|
||||
{0x09B2, 0x09B2}, {0x09B6, 0x09B9}, {0x09BC, 0x09C4},
|
||||
{0x09C7, 0x09C8}, {0x09CB, 0x09CE}, {0x09D7, 0x09D7},
|
||||
{0x09DC, 0x09DD}, {0x09DF, 0x09E3}, {0x09E6, 0x09FE},
|
||||
{0x0A01, 0x0A03}, {0x0A05, 0x0A0A}, {0x0A0F, 0x0A10},
|
||||
{0x0A13, 0x0A28}, {0x0A2A, 0x0A30}, {0x0A32, 0x0A33},
|
||||
{0x0A35, 0x0A36}, {0x0A38, 0x0A39}, {0x0A3C, 0x0A3C},
|
||||
{0x0A3E, 0x0A42}, {0x0A47, 0x0A48}, {0x0A4B, 0x0A4D},
|
||||
{0x0A51, 0x0A51}, {0x0A59, 0x0A5C}, {0x0A5E, 0x0A5E},
|
||||
{0x0A66, 0x0A76}, {0x0A81, 0x0A83}, {0x0A85, 0x0A8D},
|
||||
{0x0A8F, 0x0A91}, {0x0A93, 0x0AA8}, {0x0AAA, 0x0AB0},
|
||||
{0x0AB2, 0x0AB3}, {0x0AB5, 0x0AB9}, {0x0ABC, 0x0AC5},
|
||||
{0x0AC7, 0x0AC9}, {0x0ACB, 0x0ACD}, {0x0AD0, 0x0AD0},
|
||||
{0x0AE0, 0x0AE3}, {0x0AE6, 0x0AF1}, {0x0AF9, 0x0AFF},
|
||||
{0x0B01, 0x0B03}, {0x0B05, 0x0B0C}, {0x0B0F, 0x0B10},
|
||||
{0x0B13, 0x0B28}, {0x0B2A, 0x0B30}, {0x0B32, 0x0B33},
|
||||
{0x0B35, 0x0B39}, {0x0B3C, 0x0B44}, {0x0B47, 0x0B48},
|
||||
{0x0B4B, 0x0B4D}, {0x0B55, 0x0B57}, {0x0B5C, 0x0B5D},
|
||||
{0x0B5F, 0x0B63}, {0x0B66, 0x0B77}, {0x0B82, 0x0B83},
|
||||
{0x0B85, 0x0B8A}, {0x0B8E, 0x0B90}, {0x0B92, 0x0B95},
|
||||
{0x0B99, 0x0B9A}, {0x0B9C, 0x0B9C}, {0x0B9E, 0x0B9F},
|
||||
{0x0BA3, 0x0BA4}, {0x0BA8, 0x0BAA}, {0x0BAE, 0x0BB9},
|
||||
{0x0BBE, 0x0BC2}, {0x0BC6, 0x0BC8}, {0x0BCA, 0x0BCD},
|
||||
{0x0BD0, 0x0BD0}, {0x0BD7, 0x0BD7}, {0x0BE6, 0x0BFA},
|
||||
{0x0C00, 0x0C0C}, {0x0C0E, 0x0C10}, {0x0C12, 0x0C28},
|
||||
{0x0C2A, 0x0C39}, {0x0C3C, 0x0C44}, {0x0C46, 0x0C48},
|
||||
{0x0C4A, 0x0C4D}, {0x0C55, 0x0C56}, {0x0C58, 0x0C5A},
|
||||
{0x0C5C, 0x0C5D}, {0x0C60, 0x0C63}, {0x0C66, 0x0C6F},
|
||||
{0x0C77, 0x0C8C}, {0x0C8E, 0x0C90}, {0x0C92, 0x0CA8},
|
||||
{0x0CAA, 0x0CB3}, {0x0CB5, 0x0CB9}, {0x0CBC, 0x0CC4},
|
||||
{0x0CC6, 0x0CC8}, {0x0CCA, 0x0CCD}, {0x0CD5, 0x0CD6},
|
||||
{0x0CDC, 0x0CDE}, {0x0CE0, 0x0CE3}, {0x0CE6, 0x0CEF},
|
||||
{0x0CF1, 0x0CF3}, {0x0D00, 0x0D0C}, {0x0D0E, 0x0D10},
|
||||
{0x0D12, 0x0D44}, {0x0D46, 0x0D48}, {0x0D4A, 0x0D4F},
|
||||
{0x0D54, 0x0D63}, {0x0D66, 0x0D7F}, {0x0D81, 0x0D83},
|
||||
{0x0D85, 0x0D96}, {0x0D9A, 0x0DB1}, {0x0DB3, 0x0DBB},
|
||||
{0x0DBD, 0x0DBD}, {0x0DC0, 0x0DC6}, {0x0DCA, 0x0DCA},
|
||||
{0x0DCF, 0x0DD4}, {0x0DD6, 0x0DD6}, {0x0DD8, 0x0DDF},
|
||||
{0x0DE6, 0x0DEF}, {0x0DF2, 0x0DF4}, {0x0E01, 0x0E3A},
|
||||
{0x0E3F, 0x0E5B}, {0x0E81, 0x0E82}, {0x0E84, 0x0E84},
|
||||
{0x0E86, 0x0E8A}, {0x0E8C, 0x0EA3}, {0x0EA5, 0x0EA5},
|
||||
{0x0EA7, 0x0EBD}, {0x0EC0, 0x0EC4}, {0x0EC6, 0x0EC6},
|
||||
{0x0EC8, 0x0ECE}, {0x0ED0, 0x0ED9}, {0x0EDC, 0x0EDF},
|
||||
{0x0F00, 0x0F47}, {0x0F49, 0x0F6C}, {0x0F71, 0x0F97},
|
||||
{0x0F99, 0x0FBC}, {0x0FBE, 0x0FCC}, {0x0FCE, 0x0FDA},
|
||||
{0x1000, 0x10C5}, {0x10C7, 0x10C7}, {0x10CD, 0x10CD},
|
||||
{0x10D0, 0x10FF}, {0x1160, 0x1248}, {0x124A, 0x124D},
|
||||
{0x1250, 0x1256}, {0x1258, 0x1258}, {0x125A, 0x125D},
|
||||
{0x1260, 0x1288}, {0x128A, 0x128D}, {0x1290, 0x12B0},
|
||||
{0x12B2, 0x12B5}, {0x12B8, 0x12BE}, {0x12C0, 0x12C0},
|
||||
{0x12C2, 0x12C5}, {0x12C8, 0x12D6}, {0x12D8, 0x1310},
|
||||
{0x1312, 0x1315}, {0x1318, 0x135A}, {0x135D, 0x137C},
|
||||
{0x1380, 0x1399}, {0x13A0, 0x13F5}, {0x13F8, 0x13FD},
|
||||
{0x1400, 0x169C}, {0x16A0, 0x16F8}, {0x1700, 0x1715},
|
||||
{0x171F, 0x1736}, {0x1740, 0x1753}, {0x1760, 0x176C},
|
||||
{0x176E, 0x1770}, {0x1772, 0x1773}, {0x1780, 0x17DD},
|
||||
{0x17E0, 0x17E9}, {0x17F0, 0x17F9}, {0x1800, 0x180A},
|
||||
{0x180E, 0x180E}, {0x1810, 0x1819}, {0x1820, 0x1878},
|
||||
{0x1880, 0x18AA}, {0x18B0, 0x18F5}, {0x1900, 0x191E},
|
||||
{0x1920, 0x192B}, {0x1930, 0x193B}, {0x1940, 0x1940},
|
||||
{0x1944, 0x196D}, {0x1970, 0x1974}, {0x1980, 0x19AB},
|
||||
{0x19B0, 0x19C9}, {0x19D0, 0x19DA}, {0x19DE, 0x1A1B},
|
||||
{0x1A1E, 0x1A5E}, {0x1A60, 0x1A7C}, {0x1A7F, 0x1A89},
|
||||
{0x1A90, 0x1A99}, {0x1AA0, 0x1AAD}, {0x1AB0, 0x1ADD},
|
||||
{0x1AE0, 0x1AEB}, {0x1B00, 0x1B4C}, {0x1B4E, 0x1BF3},
|
||||
{0x1BFC, 0x1C37}, {0x1C3B, 0x1C49}, {0x1C4D, 0x1C8A},
|
||||
{0x1C90, 0x1CBA}, {0x1CBD, 0x1CC7}, {0x1CD0, 0x1CFA},
|
||||
{0x1D00, 0x1F15}, {0x1F18, 0x1F1D}, {0x1F20, 0x1F45},
|
||||
{0x1F48, 0x1F4D}, {0x1F50, 0x1F57}, {0x1F59, 0x1F59},
|
||||
{0x1F5B, 0x1F5B}, {0x1F5D, 0x1F5D}, {0x1F5F, 0x1F7D},
|
||||
{0x1F80, 0x1FB4}, {0x1FB6, 0x1FC4}, {0x1FC6, 0x1FD3},
|
||||
{0x1FD6, 0x1FDB}, {0x1FDD, 0x1FEF}, {0x1FF2, 0x1FF4},
|
||||
{0x1FF6, 0x1FFE}, {0x2000, 0x200F}, {0x2011, 0x2012},
|
||||
{0x2017, 0x2017}, {0x201A, 0x201B}, {0x201E, 0x201F},
|
||||
{0x2023, 0x2023}, {0x2028, 0x202F}, {0x2031, 0x2031},
|
||||
{0x2034, 0x2034}, {0x2036, 0x203A}, {0x203C, 0x203D},
|
||||
{0x203F, 0x2064}, {0x2066, 0x2071}, {0x2075, 0x207E},
|
||||
{0x2080, 0x2080}, {0x2085, 0x208E}, {0x2090, 0x209C},
|
||||
{0x20A0, 0x20A8}, {0x20AA, 0x20AB}, {0x20AD, 0x20C1},
|
||||
{0x20D0, 0x20F0}, {0x2100, 0x2102}, {0x2104, 0x2104},
|
||||
{0x2106, 0x2108}, {0x210A, 0x2112}, {0x2114, 0x2115},
|
||||
{0x2117, 0x2120}, {0x2123, 0x2125}, {0x2127, 0x212A},
|
||||
{0x212C, 0x2152}, {0x2155, 0x215A}, {0x215F, 0x215F},
|
||||
{0x216C, 0x216F}, {0x217A, 0x2188}, {0x218A, 0x218B},
|
||||
{0x219A, 0x21B7}, {0x21BA, 0x21D1}, {0x21D3, 0x21D3},
|
||||
{0x21D5, 0x21E6}, {0x21E8, 0x21FF}, {0x2201, 0x2201},
|
||||
{0x2204, 0x2206}, {0x2209, 0x220A}, {0x220C, 0x220E},
|
||||
{0x2210, 0x2210}, {0x2212, 0x2214}, {0x2216, 0x2219},
|
||||
{0x221B, 0x221C}, {0x2221, 0x2222}, {0x2224, 0x2224},
|
||||
{0x2226, 0x2226}, {0x222D, 0x222D}, {0x222F, 0x2233},
|
||||
{0x2238, 0x223B}, {0x223E, 0x2247}, {0x2249, 0x224B},
|
||||
{0x224D, 0x2251}, {0x2253, 0x225F}, {0x2262, 0x2263},
|
||||
{0x2268, 0x2269}, {0x226C, 0x226D}, {0x2270, 0x2281},
|
||||
{0x2284, 0x2285}, {0x2288, 0x2294}, {0x2296, 0x2298},
|
||||
{0x229A, 0x22A4}, {0x22A6, 0x22BE}, {0x22C0, 0x2311},
|
||||
{0x2313, 0x2319}, {0x231C, 0x2328}, {0x232B, 0x23E8},
|
||||
{0x23ED, 0x23EF}, {0x23F1, 0x23F2}, {0x23F4, 0x2429},
|
||||
{0x2440, 0x244A}, {0x24EA, 0x24EA}, {0x254C, 0x254F},
|
||||
{0x2574, 0x257F}, {0x2590, 0x2591}, {0x2596, 0x259F},
|
||||
{0x25A2, 0x25A2}, {0x25AA, 0x25B1}, {0x25B4, 0x25B5},
|
||||
{0x25B8, 0x25BB}, {0x25BE, 0x25BF}, {0x25C2, 0x25C5},
|
||||
{0x25C9, 0x25CA}, {0x25CC, 0x25CD}, {0x25D2, 0x25E1},
|
||||
{0x25E6, 0x25EE}, {0x25F0, 0x25FC}, {0x25FF, 0x2604},
|
||||
{0x2607, 0x2608}, {0x260A, 0x260D}, {0x2610, 0x2613},
|
||||
{0x2616, 0x261B}, {0x261D, 0x261D}, {0x261F, 0x262F},
|
||||
{0x2638, 0x263F}, {0x2641, 0x2641}, {0x2643, 0x2647},
|
||||
{0x2654, 0x265F}, {0x2662, 0x2662}, {0x2666, 0x2666},
|
||||
{0x266B, 0x266B}, {0x266E, 0x266E}, {0x2670, 0x267E},
|
||||
{0x2680, 0x2689}, {0x2690, 0x2692}, {0x2694, 0x269D},
|
||||
{0x26A0, 0x26A0}, {0x26A2, 0x26A9}, {0x26AC, 0x26BC},
|
||||
{0x26C0, 0x26C3}, {0x26E2, 0x26E2}, {0x26E4, 0x26E7},
|
||||
{0x2700, 0x2704}, {0x2706, 0x2709}, {0x270C, 0x2727},
|
||||
@@ -276,175 +279,210 @@ var neutral = table{
|
||||
{0x2780, 0x2794}, {0x2798, 0x27AF}, {0x27B1, 0x27BE},
|
||||
{0x27C0, 0x27E5}, {0x27EE, 0x2984}, {0x2987, 0x2B1A},
|
||||
{0x2B1D, 0x2B4F}, {0x2B51, 0x2B54}, {0x2B5A, 0x2B73},
|
||||
{0x2B76, 0x2B95}, {0x2B97, 0x2CF3}, {0x2CF9, 0x2D25},
|
||||
{0x2D27, 0x2D27}, {0x2D2D, 0x2D2D}, {0x2D30, 0x2D67},
|
||||
{0x2D6F, 0x2D70}, {0x2D7F, 0x2D96}, {0x2DA0, 0x2DA6},
|
||||
{0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE},
|
||||
{0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE}, {0x2DD0, 0x2DD6},
|
||||
{0x2DD8, 0x2DDE}, {0x2DE0, 0x2E5D}, {0x303F, 0x303F},
|
||||
{0x4DC0, 0x4DFF}, {0xA4D0, 0xA62B}, {0xA640, 0xA6F7},
|
||||
{0xA700, 0xA7CA}, {0xA7D0, 0xA7D1}, {0xA7D3, 0xA7D3},
|
||||
{0xA7D5, 0xA7D9}, {0xA7F2, 0xA82C}, {0xA830, 0xA839},
|
||||
{0xA840, 0xA877}, {0xA880, 0xA8C5}, {0xA8CE, 0xA8D9},
|
||||
{0xA8E0, 0xA953}, {0xA95F, 0xA95F}, {0xA980, 0xA9CD},
|
||||
{0xA9CF, 0xA9D9}, {0xA9DE, 0xA9FE}, {0xAA00, 0xAA36},
|
||||
{0xAA40, 0xAA4D}, {0xAA50, 0xAA59}, {0xAA5C, 0xAAC2},
|
||||
{0xAADB, 0xAAF6}, {0xAB01, 0xAB06}, {0xAB09, 0xAB0E},
|
||||
{0xAB11, 0xAB16}, {0xAB20, 0xAB26}, {0xAB28, 0xAB2E},
|
||||
{0xAB30, 0xAB6B}, {0xAB70, 0xABED}, {0xABF0, 0xABF9},
|
||||
{0xD7B0, 0xD7C6}, {0xD7CB, 0xD7FB}, {0xD800, 0xDFFF},
|
||||
{0xFB00, 0xFB06}, {0xFB13, 0xFB17}, {0xFB1D, 0xFB36},
|
||||
{0xFB38, 0xFB3C}, {0xFB3E, 0xFB3E}, {0xFB40, 0xFB41},
|
||||
{0xFB43, 0xFB44}, {0xFB46, 0xFBC2}, {0xFBD3, 0xFD8F},
|
||||
{0xFD92, 0xFDC7}, {0xFDCF, 0xFDCF}, {0xFDF0, 0xFDFF},
|
||||
{0xFE20, 0xFE2F}, {0xFE70, 0xFE74}, {0xFE76, 0xFEFC},
|
||||
{0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFC}, {0x10000, 0x1000B},
|
||||
{0x1000D, 0x10026}, {0x10028, 0x1003A}, {0x1003C, 0x1003D},
|
||||
{0x1003F, 0x1004D}, {0x10050, 0x1005D}, {0x10080, 0x100FA},
|
||||
{0x10100, 0x10102}, {0x10107, 0x10133}, {0x10137, 0x1018E},
|
||||
{0x10190, 0x1019C}, {0x101A0, 0x101A0}, {0x101D0, 0x101FD},
|
||||
{0x10280, 0x1029C}, {0x102A0, 0x102D0}, {0x102E0, 0x102FB},
|
||||
{0x10300, 0x10323}, {0x1032D, 0x1034A}, {0x10350, 0x1037A},
|
||||
{0x10380, 0x1039D}, {0x1039F, 0x103C3}, {0x103C8, 0x103D5},
|
||||
{0x10400, 0x1049D}, {0x104A0, 0x104A9}, {0x104B0, 0x104D3},
|
||||
{0x104D8, 0x104FB}, {0x10500, 0x10527}, {0x10530, 0x10563},
|
||||
{0x1056F, 0x1057A}, {0x1057C, 0x1058A}, {0x1058C, 0x10592},
|
||||
{0x10594, 0x10595}, {0x10597, 0x105A1}, {0x105A3, 0x105B1},
|
||||
{0x105B3, 0x105B9}, {0x105BB, 0x105BC}, {0x10600, 0x10736},
|
||||
{0x10740, 0x10755}, {0x10760, 0x10767}, {0x10780, 0x10785},
|
||||
{0x10787, 0x107B0}, {0x107B2, 0x107BA}, {0x10800, 0x10805},
|
||||
{0x10808, 0x10808}, {0x1080A, 0x10835}, {0x10837, 0x10838},
|
||||
{0x1083C, 0x1083C}, {0x1083F, 0x10855}, {0x10857, 0x1089E},
|
||||
{0x108A7, 0x108AF}, {0x108E0, 0x108F2}, {0x108F4, 0x108F5},
|
||||
{0x108FB, 0x1091B}, {0x1091F, 0x10939}, {0x1093F, 0x1093F},
|
||||
{0x10980, 0x109B7}, {0x109BC, 0x109CF}, {0x109D2, 0x10A03},
|
||||
{0x10A05, 0x10A06}, {0x10A0C, 0x10A13}, {0x10A15, 0x10A17},
|
||||
{0x10A19, 0x10A35}, {0x10A38, 0x10A3A}, {0x10A3F, 0x10A48},
|
||||
{0x10A50, 0x10A58}, {0x10A60, 0x10A9F}, {0x10AC0, 0x10AE6},
|
||||
{0x10AEB, 0x10AF6}, {0x10B00, 0x10B35}, {0x10B39, 0x10B55},
|
||||
{0x10B58, 0x10B72}, {0x10B78, 0x10B91}, {0x10B99, 0x10B9C},
|
||||
{0x10BA9, 0x10BAF}, {0x10C00, 0x10C48}, {0x10C80, 0x10CB2},
|
||||
{0x10CC0, 0x10CF2}, {0x10CFA, 0x10D27}, {0x10D30, 0x10D39},
|
||||
{0x10E60, 0x10E7E}, {0x10E80, 0x10EA9}, {0x10EAB, 0x10EAD},
|
||||
{0x10EB0, 0x10EB1}, {0x10EFD, 0x10F27}, {0x10F30, 0x10F59},
|
||||
{0x10F70, 0x10F89}, {0x10FB0, 0x10FCB}, {0x10FE0, 0x10FF6},
|
||||
{0x11000, 0x1104D}, {0x11052, 0x11075}, {0x1107F, 0x110C2},
|
||||
{0x110CD, 0x110CD}, {0x110D0, 0x110E8}, {0x110F0, 0x110F9},
|
||||
{0x11100, 0x11134}, {0x11136, 0x11147}, {0x11150, 0x11176},
|
||||
{0x11180, 0x111DF}, {0x111E1, 0x111F4}, {0x11200, 0x11211},
|
||||
{0x11213, 0x11241}, {0x11280, 0x11286}, {0x11288, 0x11288},
|
||||
{0x1128A, 0x1128D}, {0x1128F, 0x1129D}, {0x1129F, 0x112A9},
|
||||
{0x112B0, 0x112EA}, {0x112F0, 0x112F9}, {0x11300, 0x11303},
|
||||
{0x11305, 0x1130C}, {0x1130F, 0x11310}, {0x11313, 0x11328},
|
||||
{0x1132A, 0x11330}, {0x11332, 0x11333}, {0x11335, 0x11339},
|
||||
{0x1133B, 0x11344}, {0x11347, 0x11348}, {0x1134B, 0x1134D},
|
||||
{0x11350, 0x11350}, {0x11357, 0x11357}, {0x1135D, 0x11363},
|
||||
{0x11366, 0x1136C}, {0x11370, 0x11374}, {0x11400, 0x1145B},
|
||||
{0x2B76, 0x2CF3}, {0x2CF9, 0x2D25}, {0x2D27, 0x2D27},
|
||||
{0x2D2D, 0x2D2D}, {0x2D30, 0x2D67}, {0x2D6F, 0x2D70},
|
||||
{0x2D7F, 0x2D96}, {0x2DA0, 0x2DA6}, {0x2DA8, 0x2DAE},
|
||||
{0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE}, {0x2DC0, 0x2DC6},
|
||||
{0x2DC8, 0x2DCE}, {0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE},
|
||||
{0x2DE0, 0x2E5D}, {0x303F, 0x303F}, {0xA4D0, 0xA62B},
|
||||
{0xA640, 0xA6F7}, {0xA700, 0xA7DC}, {0xA7F1, 0xA82C},
|
||||
{0xA830, 0xA839}, {0xA840, 0xA877}, {0xA880, 0xA8C5},
|
||||
{0xA8CE, 0xA8D9}, {0xA8E0, 0xA953}, {0xA95F, 0xA95F},
|
||||
{0xA980, 0xA9CD}, {0xA9CF, 0xA9D9}, {0xA9DE, 0xA9FE},
|
||||
{0xAA00, 0xAA36}, {0xAA40, 0xAA4D}, {0xAA50, 0xAA59},
|
||||
{0xAA5C, 0xAAC2}, {0xAADB, 0xAAF6}, {0xAB01, 0xAB06},
|
||||
{0xAB09, 0xAB0E}, {0xAB11, 0xAB16}, {0xAB20, 0xAB26},
|
||||
{0xAB28, 0xAB2E}, {0xAB30, 0xAB6B}, {0xAB70, 0xABED},
|
||||
{0xABF0, 0xABF9}, {0xD7B0, 0xD7C6}, {0xD7CB, 0xD7FB},
|
||||
{0xD800, 0xDFFF}, {0xFB00, 0xFB06}, {0xFB13, 0xFB17},
|
||||
{0xFB1D, 0xFB36}, {0xFB38, 0xFB3C}, {0xFB3E, 0xFB3E},
|
||||
{0xFB40, 0xFB41}, {0xFB43, 0xFB44}, {0xFB46, 0xFDCF},
|
||||
{0xFDF0, 0xFDFF}, {0xFE20, 0xFE2F}, {0xFE70, 0xFE74},
|
||||
{0xFE76, 0xFEFC}, {0xFEFF, 0xFEFF}, {0xFFF9, 0xFFFC},
|
||||
{0x10000, 0x1000B}, {0x1000D, 0x10026}, {0x10028, 0x1003A},
|
||||
{0x1003C, 0x1003D}, {0x1003F, 0x1004D}, {0x10050, 0x1005D},
|
||||
{0x10080, 0x100FA}, {0x10100, 0x10102}, {0x10107, 0x10133},
|
||||
{0x10137, 0x1018E}, {0x10190, 0x1019C}, {0x101A0, 0x101A0},
|
||||
{0x101D0, 0x101FD}, {0x10280, 0x1029C}, {0x102A0, 0x102D0},
|
||||
{0x102E0, 0x102FB}, {0x10300, 0x10323}, {0x1032D, 0x1034A},
|
||||
{0x10350, 0x1037A}, {0x10380, 0x1039D}, {0x1039F, 0x103C3},
|
||||
{0x103C8, 0x103D5}, {0x10400, 0x1049D}, {0x104A0, 0x104A9},
|
||||
{0x104B0, 0x104D3}, {0x104D8, 0x104FB}, {0x10500, 0x10527},
|
||||
{0x10530, 0x10563}, {0x1056F, 0x1057A}, {0x1057C, 0x1058A},
|
||||
{0x1058C, 0x10592}, {0x10594, 0x10595}, {0x10597, 0x105A1},
|
||||
{0x105A3, 0x105B1}, {0x105B3, 0x105B9}, {0x105BB, 0x105BC},
|
||||
{0x105C0, 0x105F3}, {0x10600, 0x10736}, {0x10740, 0x10755},
|
||||
{0x10760, 0x10767}, {0x10780, 0x10785}, {0x10787, 0x107B0},
|
||||
{0x107B2, 0x107BA}, {0x10800, 0x10805}, {0x10808, 0x10808},
|
||||
{0x1080A, 0x10835}, {0x10837, 0x10838}, {0x1083C, 0x1083C},
|
||||
{0x1083F, 0x10855}, {0x10857, 0x1089E}, {0x108A7, 0x108AF},
|
||||
{0x108E0, 0x108F2}, {0x108F4, 0x108F5}, {0x108FB, 0x1091B},
|
||||
{0x1091F, 0x10939}, {0x1093F, 0x10959}, {0x10980, 0x109B7},
|
||||
{0x109BC, 0x109CF}, {0x109D2, 0x10A03}, {0x10A05, 0x10A06},
|
||||
{0x10A0C, 0x10A13}, {0x10A15, 0x10A17}, {0x10A19, 0x10A35},
|
||||
{0x10A38, 0x10A3A}, {0x10A3F, 0x10A48}, {0x10A50, 0x10A58},
|
||||
{0x10A60, 0x10A9F}, {0x10AC0, 0x10AE6}, {0x10AEB, 0x10AF6},
|
||||
{0x10B00, 0x10B35}, {0x10B39, 0x10B55}, {0x10B58, 0x10B72},
|
||||
{0x10B78, 0x10B91}, {0x10B99, 0x10B9C}, {0x10BA9, 0x10BAF},
|
||||
{0x10C00, 0x10C48}, {0x10C80, 0x10CB2}, {0x10CC0, 0x10CF2},
|
||||
{0x10CFA, 0x10D27}, {0x10D30, 0x10D39}, {0x10D40, 0x10D65},
|
||||
{0x10D69, 0x10D85}, {0x10D8E, 0x10D8F}, {0x10E60, 0x10E7E},
|
||||
{0x10E80, 0x10EA9}, {0x10EAB, 0x10EAD}, {0x10EB0, 0x10EB1},
|
||||
{0x10EC2, 0x10EC7}, {0x10ED0, 0x10ED8}, {0x10EFA, 0x10F27},
|
||||
{0x10F30, 0x10F59}, {0x10F70, 0x10F89}, {0x10FB0, 0x10FCB},
|
||||
{0x10FE0, 0x10FF6}, {0x11000, 0x1104D}, {0x11052, 0x11075},
|
||||
{0x1107F, 0x110C2}, {0x110CD, 0x110CD}, {0x110D0, 0x110E8},
|
||||
{0x110F0, 0x110F9}, {0x11100, 0x11134}, {0x11136, 0x11147},
|
||||
{0x11150, 0x11176}, {0x11180, 0x111DF}, {0x111E1, 0x111F4},
|
||||
{0x11200, 0x11211}, {0x11213, 0x11241}, {0x11280, 0x11286},
|
||||
{0x11288, 0x11288}, {0x1128A, 0x1128D}, {0x1128F, 0x1129D},
|
||||
{0x1129F, 0x112A9}, {0x112B0, 0x112EA}, {0x112F0, 0x112F9},
|
||||
{0x11300, 0x11303}, {0x11305, 0x1130C}, {0x1130F, 0x11310},
|
||||
{0x11313, 0x11328}, {0x1132A, 0x11330}, {0x11332, 0x11333},
|
||||
{0x11335, 0x11339}, {0x1133B, 0x11344}, {0x11347, 0x11348},
|
||||
{0x1134B, 0x1134D}, {0x11350, 0x11350}, {0x11357, 0x11357},
|
||||
{0x1135D, 0x11363}, {0x11366, 0x1136C}, {0x11370, 0x11374},
|
||||
{0x11380, 0x11389}, {0x1138B, 0x1138B}, {0x1138E, 0x1138E},
|
||||
{0x11390, 0x113B5}, {0x113B7, 0x113C0}, {0x113C2, 0x113C2},
|
||||
{0x113C5, 0x113C5}, {0x113C7, 0x113CA}, {0x113CC, 0x113D5},
|
||||
{0x113D7, 0x113D8}, {0x113E1, 0x113E2}, {0x11400, 0x1145B},
|
||||
{0x1145D, 0x11461}, {0x11480, 0x114C7}, {0x114D0, 0x114D9},
|
||||
{0x11580, 0x115B5}, {0x115B8, 0x115DD}, {0x11600, 0x11644},
|
||||
{0x11650, 0x11659}, {0x11660, 0x1166C}, {0x11680, 0x116B9},
|
||||
{0x116C0, 0x116C9}, {0x11700, 0x1171A}, {0x1171D, 0x1172B},
|
||||
{0x11730, 0x11746}, {0x11800, 0x1183B}, {0x118A0, 0x118F2},
|
||||
{0x118FF, 0x11906}, {0x11909, 0x11909}, {0x1190C, 0x11913},
|
||||
{0x11915, 0x11916}, {0x11918, 0x11935}, {0x11937, 0x11938},
|
||||
{0x1193B, 0x11946}, {0x11950, 0x11959}, {0x119A0, 0x119A7},
|
||||
{0x119AA, 0x119D7}, {0x119DA, 0x119E4}, {0x11A00, 0x11A47},
|
||||
{0x11A50, 0x11AA2}, {0x11AB0, 0x11AF8}, {0x11B00, 0x11B09},
|
||||
{0x11C00, 0x11C08}, {0x11C0A, 0x11C36}, {0x11C38, 0x11C45},
|
||||
{0x11C50, 0x11C6C}, {0x11C70, 0x11C8F}, {0x11C92, 0x11CA7},
|
||||
{0x11CA9, 0x11CB6}, {0x11D00, 0x11D06}, {0x11D08, 0x11D09},
|
||||
{0x11D0B, 0x11D36}, {0x11D3A, 0x11D3A}, {0x11D3C, 0x11D3D},
|
||||
{0x11D3F, 0x11D47}, {0x11D50, 0x11D59}, {0x11D60, 0x11D65},
|
||||
{0x11D67, 0x11D68}, {0x11D6A, 0x11D8E}, {0x11D90, 0x11D91},
|
||||
{0x11D93, 0x11D98}, {0x11DA0, 0x11DA9}, {0x11EE0, 0x11EF8},
|
||||
{0x11F00, 0x11F10}, {0x11F12, 0x11F3A}, {0x11F3E, 0x11F59},
|
||||
{0x116C0, 0x116C9}, {0x116D0, 0x116E3}, {0x11700, 0x1171A},
|
||||
{0x1171D, 0x1172B}, {0x11730, 0x11746}, {0x11800, 0x1183B},
|
||||
{0x118A0, 0x118F2}, {0x118FF, 0x11906}, {0x11909, 0x11909},
|
||||
{0x1190C, 0x11913}, {0x11915, 0x11916}, {0x11918, 0x11935},
|
||||
{0x11937, 0x11938}, {0x1193B, 0x11946}, {0x11950, 0x11959},
|
||||
{0x119A0, 0x119A7}, {0x119AA, 0x119D7}, {0x119DA, 0x119E4},
|
||||
{0x11A00, 0x11A47}, {0x11A50, 0x11AA2}, {0x11AB0, 0x11AF8},
|
||||
{0x11B00, 0x11B09}, {0x11B60, 0x11B67}, {0x11BC0, 0x11BE1},
|
||||
{0x11BF0, 0x11BF9}, {0x11C00, 0x11C08}, {0x11C0A, 0x11C36},
|
||||
{0x11C38, 0x11C45}, {0x11C50, 0x11C6C}, {0x11C70, 0x11C8F},
|
||||
{0x11C92, 0x11CA7}, {0x11CA9, 0x11CB6}, {0x11D00, 0x11D06},
|
||||
{0x11D08, 0x11D09}, {0x11D0B, 0x11D36}, {0x11D3A, 0x11D3A},
|
||||
{0x11D3C, 0x11D3D}, {0x11D3F, 0x11D47}, {0x11D50, 0x11D59},
|
||||
{0x11D60, 0x11D65}, {0x11D67, 0x11D68}, {0x11D6A, 0x11D8E},
|
||||
{0x11D90, 0x11D91}, {0x11D93, 0x11D98}, {0x11DA0, 0x11DA9},
|
||||
{0x11DB0, 0x11DDB}, {0x11DE0, 0x11DE9}, {0x11EE0, 0x11EF8},
|
||||
{0x11F00, 0x11F10}, {0x11F12, 0x11F3A}, {0x11F3E, 0x11F5A},
|
||||
{0x11FB0, 0x11FB0}, {0x11FC0, 0x11FF1}, {0x11FFF, 0x12399},
|
||||
{0x12400, 0x1246E}, {0x12470, 0x12474}, {0x12480, 0x12543},
|
||||
{0x12F90, 0x12FF2}, {0x13000, 0x13455}, {0x14400, 0x14646},
|
||||
{0x16800, 0x16A38}, {0x16A40, 0x16A5E}, {0x16A60, 0x16A69},
|
||||
{0x16A6E, 0x16ABE}, {0x16AC0, 0x16AC9}, {0x16AD0, 0x16AED},
|
||||
{0x16AF0, 0x16AF5}, {0x16B00, 0x16B45}, {0x16B50, 0x16B59},
|
||||
{0x16B5B, 0x16B61}, {0x16B63, 0x16B77}, {0x16B7D, 0x16B8F},
|
||||
{0x16E40, 0x16E9A}, {0x16F00, 0x16F4A}, {0x16F4F, 0x16F87},
|
||||
{0x16F8F, 0x16F9F}, {0x1BC00, 0x1BC6A}, {0x1BC70, 0x1BC7C},
|
||||
{0x1BC80, 0x1BC88}, {0x1BC90, 0x1BC99}, {0x1BC9C, 0x1BCA3},
|
||||
{0x12F90, 0x12FF2}, {0x13000, 0x13455}, {0x13460, 0x143FA},
|
||||
{0x14400, 0x14646}, {0x16100, 0x16139}, {0x16800, 0x16A38},
|
||||
{0x16A40, 0x16A5E}, {0x16A60, 0x16A69}, {0x16A6E, 0x16ABE},
|
||||
{0x16AC0, 0x16AC9}, {0x16AD0, 0x16AED}, {0x16AF0, 0x16AF5},
|
||||
{0x16B00, 0x16B45}, {0x16B50, 0x16B59}, {0x16B5B, 0x16B61},
|
||||
{0x16B63, 0x16B77}, {0x16B7D, 0x16B8F}, {0x16D40, 0x16D79},
|
||||
{0x16E40, 0x16E9A}, {0x16EA0, 0x16EB8}, {0x16EBB, 0x16ED3},
|
||||
{0x16F00, 0x16F4A}, {0x16F4F, 0x16F87}, {0x16F8F, 0x16F9F},
|
||||
{0x1BC00, 0x1BC6A}, {0x1BC70, 0x1BC7C}, {0x1BC80, 0x1BC88},
|
||||
{0x1BC90, 0x1BC99}, {0x1BC9C, 0x1BCA3}, {0x1CC00, 0x1CCFC},
|
||||
{0x1CD00, 0x1CEB3}, {0x1CEBA, 0x1CED0}, {0x1CEE0, 0x1CEF0},
|
||||
{0x1CF00, 0x1CF2D}, {0x1CF30, 0x1CF46}, {0x1CF50, 0x1CFC3},
|
||||
{0x1D000, 0x1D0F5}, {0x1D100, 0x1D126}, {0x1D129, 0x1D1EA},
|
||||
{0x1D200, 0x1D245}, {0x1D2C0, 0x1D2D3}, {0x1D2E0, 0x1D2F3},
|
||||
{0x1D300, 0x1D356}, {0x1D360, 0x1D378}, {0x1D400, 0x1D454},
|
||||
{0x1D456, 0x1D49C}, {0x1D49E, 0x1D49F}, {0x1D4A2, 0x1D4A2},
|
||||
{0x1D4A5, 0x1D4A6}, {0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B9},
|
||||
{0x1D4BB, 0x1D4BB}, {0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D505},
|
||||
{0x1D507, 0x1D50A}, {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C},
|
||||
{0x1D51E, 0x1D539}, {0x1D53B, 0x1D53E}, {0x1D540, 0x1D544},
|
||||
{0x1D546, 0x1D546}, {0x1D54A, 0x1D550}, {0x1D552, 0x1D6A5},
|
||||
{0x1D6A8, 0x1D7CB}, {0x1D7CE, 0x1DA8B}, {0x1DA9B, 0x1DA9F},
|
||||
{0x1DAA1, 0x1DAAF}, {0x1DF00, 0x1DF1E}, {0x1DF25, 0x1DF2A},
|
||||
{0x1E000, 0x1E006}, {0x1E008, 0x1E018}, {0x1E01B, 0x1E021},
|
||||
{0x1E023, 0x1E024}, {0x1E026, 0x1E02A}, {0x1E030, 0x1E06D},
|
||||
{0x1E08F, 0x1E08F}, {0x1E100, 0x1E12C}, {0x1E130, 0x1E13D},
|
||||
{0x1E140, 0x1E149}, {0x1E14E, 0x1E14F}, {0x1E290, 0x1E2AE},
|
||||
{0x1E2C0, 0x1E2F9}, {0x1E2FF, 0x1E2FF}, {0x1E4D0, 0x1E4F9},
|
||||
{0x1E7E0, 0x1E7E6}, {0x1E7E8, 0x1E7EB}, {0x1E7ED, 0x1E7EE},
|
||||
{0x1E7F0, 0x1E7FE}, {0x1E800, 0x1E8C4}, {0x1E8C7, 0x1E8D6},
|
||||
{0x1E900, 0x1E94B}, {0x1E950, 0x1E959}, {0x1E95E, 0x1E95F},
|
||||
{0x1EC71, 0x1ECB4}, {0x1ED01, 0x1ED3D}, {0x1EE00, 0x1EE03},
|
||||
{0x1EE05, 0x1EE1F}, {0x1EE21, 0x1EE22}, {0x1EE24, 0x1EE24},
|
||||
{0x1EE27, 0x1EE27}, {0x1EE29, 0x1EE32}, {0x1EE34, 0x1EE37},
|
||||
{0x1EE39, 0x1EE39}, {0x1EE3B, 0x1EE3B}, {0x1EE42, 0x1EE42},
|
||||
{0x1EE47, 0x1EE47}, {0x1EE49, 0x1EE49}, {0x1EE4B, 0x1EE4B},
|
||||
{0x1EE4D, 0x1EE4F}, {0x1EE51, 0x1EE52}, {0x1EE54, 0x1EE54},
|
||||
{0x1EE57, 0x1EE57}, {0x1EE59, 0x1EE59}, {0x1EE5B, 0x1EE5B},
|
||||
{0x1EE5D, 0x1EE5D}, {0x1EE5F, 0x1EE5F}, {0x1EE61, 0x1EE62},
|
||||
{0x1EE64, 0x1EE64}, {0x1EE67, 0x1EE6A}, {0x1EE6C, 0x1EE72},
|
||||
{0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C}, {0x1EE7E, 0x1EE7E},
|
||||
{0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B}, {0x1EEA1, 0x1EEA3},
|
||||
{0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB}, {0x1EEF0, 0x1EEF1},
|
||||
{0x1F000, 0x1F003}, {0x1F005, 0x1F02B}, {0x1F030, 0x1F093},
|
||||
{0x1F0A0, 0x1F0AE}, {0x1F0B1, 0x1F0BF}, {0x1F0C1, 0x1F0CE},
|
||||
{0x1F0D1, 0x1F0F5}, {0x1F10B, 0x1F10F}, {0x1F12E, 0x1F12F},
|
||||
{0x1F16A, 0x1F16F}, {0x1F1AD, 0x1F1AD}, {0x1F1E6, 0x1F1FF},
|
||||
{0x1F321, 0x1F32C}, {0x1F336, 0x1F336}, {0x1F37D, 0x1F37D},
|
||||
{0x1F394, 0x1F39F}, {0x1F3CB, 0x1F3CE}, {0x1F3D4, 0x1F3DF},
|
||||
{0x1F3F1, 0x1F3F3}, {0x1F3F5, 0x1F3F7}, {0x1F43F, 0x1F43F},
|
||||
{0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FE}, {0x1F53E, 0x1F54A},
|
||||
{0x1F54F, 0x1F54F}, {0x1F568, 0x1F579}, {0x1F57B, 0x1F594},
|
||||
{0x1F597, 0x1F5A3}, {0x1F5A5, 0x1F5FA}, {0x1F650, 0x1F67F},
|
||||
{0x1F6C6, 0x1F6CB}, {0x1F6CD, 0x1F6CF}, {0x1F6D3, 0x1F6D4},
|
||||
{0x1F6E0, 0x1F6EA}, {0x1F6F0, 0x1F6F3}, {0x1F700, 0x1F776},
|
||||
{0x1F77B, 0x1F7D9}, {0x1F800, 0x1F80B}, {0x1F810, 0x1F847},
|
||||
{0x1D377, 0x1D378}, {0x1D400, 0x1D454}, {0x1D456, 0x1D49C},
|
||||
{0x1D49E, 0x1D49F}, {0x1D4A2, 0x1D4A2}, {0x1D4A5, 0x1D4A6},
|
||||
{0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B9}, {0x1D4BB, 0x1D4BB},
|
||||
{0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D505}, {0x1D507, 0x1D50A},
|
||||
{0x1D50D, 0x1D514}, {0x1D516, 0x1D51C}, {0x1D51E, 0x1D539},
|
||||
{0x1D53B, 0x1D53E}, {0x1D540, 0x1D544}, {0x1D546, 0x1D546},
|
||||
{0x1D54A, 0x1D550}, {0x1D552, 0x1D6A5}, {0x1D6A8, 0x1D7CB},
|
||||
{0x1D7CE, 0x1DA8B}, {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF},
|
||||
{0x1DF00, 0x1DF1E}, {0x1DF25, 0x1DF2A}, {0x1E000, 0x1E006},
|
||||
{0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E023, 0x1E024},
|
||||
{0x1E026, 0x1E02A}, {0x1E030, 0x1E06D}, {0x1E08F, 0x1E08F},
|
||||
{0x1E100, 0x1E12C}, {0x1E130, 0x1E13D}, {0x1E140, 0x1E149},
|
||||
{0x1E14E, 0x1E14F}, {0x1E290, 0x1E2AE}, {0x1E2C0, 0x1E2F9},
|
||||
{0x1E2FF, 0x1E2FF}, {0x1E4D0, 0x1E4F9}, {0x1E5D0, 0x1E5FA},
|
||||
{0x1E5FF, 0x1E5FF}, {0x1E6C0, 0x1E6DE}, {0x1E6E0, 0x1E6F5},
|
||||
{0x1E6FE, 0x1E6FF}, {0x1E7E0, 0x1E7E6}, {0x1E7E8, 0x1E7EB},
|
||||
{0x1E7ED, 0x1E7EE}, {0x1E7F0, 0x1E7FE}, {0x1E800, 0x1E8C4},
|
||||
{0x1E8C7, 0x1E8D6}, {0x1E900, 0x1E94B}, {0x1E950, 0x1E959},
|
||||
{0x1E95E, 0x1E95F}, {0x1EC71, 0x1ECB4}, {0x1ED01, 0x1ED3D},
|
||||
{0x1EE00, 0x1EE03}, {0x1EE05, 0x1EE1F}, {0x1EE21, 0x1EE22},
|
||||
{0x1EE24, 0x1EE24}, {0x1EE27, 0x1EE27}, {0x1EE29, 0x1EE32},
|
||||
{0x1EE34, 0x1EE37}, {0x1EE39, 0x1EE39}, {0x1EE3B, 0x1EE3B},
|
||||
{0x1EE42, 0x1EE42}, {0x1EE47, 0x1EE47}, {0x1EE49, 0x1EE49},
|
||||
{0x1EE4B, 0x1EE4B}, {0x1EE4D, 0x1EE4F}, {0x1EE51, 0x1EE52},
|
||||
{0x1EE54, 0x1EE54}, {0x1EE57, 0x1EE57}, {0x1EE59, 0x1EE59},
|
||||
{0x1EE5B, 0x1EE5B}, {0x1EE5D, 0x1EE5D}, {0x1EE5F, 0x1EE5F},
|
||||
{0x1EE61, 0x1EE62}, {0x1EE64, 0x1EE64}, {0x1EE67, 0x1EE6A},
|
||||
{0x1EE6C, 0x1EE72}, {0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C},
|
||||
{0x1EE7E, 0x1EE7E}, {0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B},
|
||||
{0x1EEA1, 0x1EEA3}, {0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB},
|
||||
{0x1EEF0, 0x1EEF1}, {0x1F000, 0x1F003}, {0x1F005, 0x1F02B},
|
||||
{0x1F030, 0x1F093}, {0x1F0A0, 0x1F0AE}, {0x1F0B1, 0x1F0BF},
|
||||
{0x1F0C1, 0x1F0CE}, {0x1F0D1, 0x1F0F5}, {0x1F10B, 0x1F10F},
|
||||
{0x1F12E, 0x1F12F}, {0x1F16A, 0x1F16F}, {0x1F1AD, 0x1F1AD},
|
||||
{0x1F1E6, 0x1F1FF}, {0x1F321, 0x1F32C}, {0x1F336, 0x1F336},
|
||||
{0x1F37D, 0x1F37D}, {0x1F394, 0x1F39F}, {0x1F3CB, 0x1F3CE},
|
||||
{0x1F3D4, 0x1F3DF}, {0x1F3F1, 0x1F3F3}, {0x1F3F5, 0x1F3F7},
|
||||
{0x1F43F, 0x1F43F}, {0x1F441, 0x1F441}, {0x1F4FD, 0x1F4FE},
|
||||
{0x1F53E, 0x1F54A}, {0x1F54F, 0x1F54F}, {0x1F568, 0x1F579},
|
||||
{0x1F57B, 0x1F594}, {0x1F597, 0x1F5A3}, {0x1F5A5, 0x1F5FA},
|
||||
{0x1F650, 0x1F67F}, {0x1F6C6, 0x1F6CB}, {0x1F6CD, 0x1F6CF},
|
||||
{0x1F6D3, 0x1F6D4}, {0x1F6E0, 0x1F6EA}, {0x1F6F0, 0x1F6F3},
|
||||
{0x1F700, 0x1F7D9}, {0x1F800, 0x1F80B}, {0x1F810, 0x1F847},
|
||||
{0x1F850, 0x1F859}, {0x1F860, 0x1F887}, {0x1F890, 0x1F8AD},
|
||||
{0x1F8B0, 0x1F8B1}, {0x1F900, 0x1F90B}, {0x1F93B, 0x1F93B},
|
||||
{0x1F946, 0x1F946}, {0x1FA00, 0x1FA53}, {0x1FA60, 0x1FA6D},
|
||||
{0x1FB00, 0x1FB92}, {0x1FB94, 0x1FBCA}, {0x1FBF0, 0x1FBF9},
|
||||
{0xE0001, 0xE0001}, {0xE0020, 0xE007F},
|
||||
{0x1F8B0, 0x1F8BB}, {0x1F8C0, 0x1F8C1}, {0x1F8D0, 0x1F8D8},
|
||||
{0x1F900, 0x1F90B}, {0x1F93B, 0x1F93B}, {0x1F946, 0x1F946},
|
||||
{0x1FA00, 0x1FA57}, {0x1FA60, 0x1FA6D}, {0x1FB00, 0x1FB92},
|
||||
{0x1FB94, 0x1FBFA}, {0xE0001, 0xE0001}, {0xE0020, 0xE007F},
|
||||
}
|
||||
|
||||
var emoji = table{
|
||||
{0x203C, 0x203C}, {0x2049, 0x2049}, {0x2122, 0x2122},
|
||||
{0x2139, 0x2139}, {0x2194, 0x2199}, {0x21A9, 0x21AA},
|
||||
{0x231A, 0x231B}, {0x2328, 0x2328}, {0x2388, 0x2388},
|
||||
{0x23CF, 0x23CF}, {0x23E9, 0x23F3}, {0x23F8, 0x23FA},
|
||||
{0x24C2, 0x24C2}, {0x25AA, 0x25AB}, {0x25B6, 0x25B6},
|
||||
{0x25C0, 0x25C0}, {0x25FB, 0x25FE}, {0x2600, 0x2605},
|
||||
{0x2607, 0x2612}, {0x2614, 0x2685}, {0x2690, 0x2705},
|
||||
{0x2708, 0x2712}, {0x2714, 0x2714}, {0x2716, 0x2716},
|
||||
{0x271D, 0x271D}, {0x2721, 0x2721}, {0x2728, 0x2728},
|
||||
{0x2733, 0x2734}, {0x2744, 0x2744}, {0x2747, 0x2747},
|
||||
{0x274C, 0x274C}, {0x274E, 0x274E}, {0x2753, 0x2755},
|
||||
{0x2757, 0x2757}, {0x2763, 0x2767}, {0x2795, 0x2797},
|
||||
{0x27A1, 0x27A1}, {0x27B0, 0x27B0}, {0x27BF, 0x27BF},
|
||||
{0x2934, 0x2935}, {0x2B05, 0x2B07}, {0x2B1B, 0x2B1C},
|
||||
{0x2B50, 0x2B50}, {0x2B55, 0x2B55}, {0x3030, 0x3030},
|
||||
{0x303D, 0x303D}, {0x3297, 0x3297}, {0x3299, 0x3299},
|
||||
{0x1F000, 0x1F0FF}, {0x1F10D, 0x1F10F}, {0x1F12F, 0x1F12F},
|
||||
{0x1F16C, 0x1F171}, {0x1F17E, 0x1F17F}, {0x1F18E, 0x1F18E},
|
||||
{0x1F191, 0x1F19A}, {0x1F1AD, 0x1F1E5}, {0x1F201, 0x1F20F},
|
||||
{0x1F21A, 0x1F21A}, {0x1F22F, 0x1F22F}, {0x1F232, 0x1F23A},
|
||||
{0x1F23C, 0x1F23F}, {0x1F249, 0x1F3FA}, {0x1F400, 0x1F53D},
|
||||
{0x1F546, 0x1F64F}, {0x1F680, 0x1F6FF}, {0x1F774, 0x1F77F},
|
||||
{0x1F7D5, 0x1F7FF}, {0x1F80C, 0x1F80F}, {0x1F848, 0x1F84F},
|
||||
{0x1F85A, 0x1F85F}, {0x1F888, 0x1F88F}, {0x1F8AE, 0x1F8FF},
|
||||
{0x1F90C, 0x1F93A}, {0x1F93C, 0x1F945}, {0x1F947, 0x1FAFF},
|
||||
{0x231A, 0x231B}, {0x2328, 0x2328}, {0x23CF, 0x23CF},
|
||||
{0x23E9, 0x23F3}, {0x23F8, 0x23FA}, {0x24C2, 0x24C2},
|
||||
{0x25AA, 0x25AB}, {0x25B6, 0x25B6}, {0x25C0, 0x25C0},
|
||||
{0x25FB, 0x25FE}, {0x2600, 0x2604}, {0x260E, 0x260E},
|
||||
{0x2611, 0x2611}, {0x2614, 0x2615}, {0x2618, 0x2618},
|
||||
{0x261D, 0x261D}, {0x2620, 0x2620}, {0x2622, 0x2623},
|
||||
{0x2626, 0x2626}, {0x262A, 0x262A}, {0x262E, 0x262F},
|
||||
{0x2638, 0x263A}, {0x2640, 0x2640}, {0x2642, 0x2642},
|
||||
{0x2648, 0x2653}, {0x265F, 0x2660}, {0x2663, 0x2663},
|
||||
{0x2665, 0x2666}, {0x2668, 0x2668}, {0x267B, 0x267B},
|
||||
{0x267E, 0x267F}, {0x2692, 0x2697}, {0x2699, 0x2699},
|
||||
{0x269B, 0x269C}, {0x26A0, 0x26A1}, {0x26A7, 0x26A7},
|
||||
{0x26AA, 0x26AB}, {0x26B0, 0x26B1}, {0x26BD, 0x26BE},
|
||||
{0x26C4, 0x26C5}, {0x26C8, 0x26C8}, {0x26CE, 0x26CF},
|
||||
{0x26D1, 0x26D1}, {0x26D3, 0x26D4}, {0x26E9, 0x26EA},
|
||||
{0x26F0, 0x26F5}, {0x26F7, 0x26FA}, {0x26FD, 0x26FD},
|
||||
{0x2702, 0x2702}, {0x2705, 0x2705}, {0x2708, 0x270D},
|
||||
{0x270F, 0x270F}, {0x2712, 0x2712}, {0x2714, 0x2714},
|
||||
{0x2716, 0x2716}, {0x271D, 0x271D}, {0x2721, 0x2721},
|
||||
{0x2728, 0x2728}, {0x2733, 0x2734}, {0x2744, 0x2744},
|
||||
{0x2747, 0x2747}, {0x274C, 0x274C}, {0x274E, 0x274E},
|
||||
{0x2753, 0x2755}, {0x2757, 0x2757}, {0x2763, 0x2764},
|
||||
{0x2795, 0x2797}, {0x27A1, 0x27A1}, {0x27B0, 0x27B0},
|
||||
{0x27BF, 0x27BF}, {0x2934, 0x2935}, {0x2B05, 0x2B07},
|
||||
{0x2B1B, 0x2B1C}, {0x2B50, 0x2B50}, {0x2B55, 0x2B55},
|
||||
{0x3030, 0x3030}, {0x303D, 0x303D}, {0x3297, 0x3297},
|
||||
{0x3299, 0x3299}, {0x1F004, 0x1F004}, {0x1F02C, 0x1F02F},
|
||||
{0x1F094, 0x1F09F}, {0x1F0AF, 0x1F0B0}, {0x1F0C0, 0x1F0C0},
|
||||
{0x1F0CF, 0x1F0D0}, {0x1F0F6, 0x1F0FF}, {0x1F170, 0x1F171},
|
||||
{0x1F17E, 0x1F17F}, {0x1F18E, 0x1F18E}, {0x1F191, 0x1F19A},
|
||||
{0x1F1AE, 0x1F1E5}, {0x1F201, 0x1F20F}, {0x1F21A, 0x1F21A},
|
||||
{0x1F22F, 0x1F22F}, {0x1F232, 0x1F23A}, {0x1F23C, 0x1F23F},
|
||||
{0x1F249, 0x1F25F}, {0x1F266, 0x1F321}, {0x1F324, 0x1F393},
|
||||
{0x1F396, 0x1F397}, {0x1F399, 0x1F39B}, {0x1F39E, 0x1F3F0},
|
||||
{0x1F3F3, 0x1F3F5}, {0x1F3F7, 0x1F3FA}, {0x1F400, 0x1F4FD},
|
||||
{0x1F4FF, 0x1F53D}, {0x1F549, 0x1F54E}, {0x1F550, 0x1F567},
|
||||
{0x1F56F, 0x1F570}, {0x1F573, 0x1F57A}, {0x1F587, 0x1F587},
|
||||
{0x1F58A, 0x1F58D}, {0x1F590, 0x1F590}, {0x1F595, 0x1F596},
|
||||
{0x1F5A4, 0x1F5A5}, {0x1F5A8, 0x1F5A8}, {0x1F5B1, 0x1F5B2},
|
||||
{0x1F5BC, 0x1F5BC}, {0x1F5C2, 0x1F5C4}, {0x1F5D1, 0x1F5D3},
|
||||
{0x1F5DC, 0x1F5DE}, {0x1F5E1, 0x1F5E1}, {0x1F5E3, 0x1F5E3},
|
||||
{0x1F5E8, 0x1F5E8}, {0x1F5EF, 0x1F5EF}, {0x1F5F3, 0x1F5F3},
|
||||
{0x1F5FA, 0x1F64F}, {0x1F680, 0x1F6C5}, {0x1F6CB, 0x1F6D2},
|
||||
{0x1F6D5, 0x1F6E5}, {0x1F6E9, 0x1F6E9}, {0x1F6EB, 0x1F6F0},
|
||||
{0x1F6F3, 0x1F6FF}, {0x1F7DA, 0x1F7FF}, {0x1F80C, 0x1F80F},
|
||||
{0x1F848, 0x1F84F}, {0x1F85A, 0x1F85F}, {0x1F888, 0x1F88F},
|
||||
{0x1F8AE, 0x1F8AF}, {0x1F8BC, 0x1F8BF}, {0x1F8C2, 0x1F8CF},
|
||||
{0x1F8D9, 0x1F8FF}, {0x1F90C, 0x1F93A}, {0x1F93C, 0x1F945},
|
||||
{0x1F947, 0x1F9FF}, {0x1FA58, 0x1FA5F}, {0x1FA6E, 0x1FAFF},
|
||||
{0x1FC00, 0x1FFFD},
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@ linters:
|
||||
enable:
|
||||
- durationcheck
|
||||
- gocritic
|
||||
- gomodguard
|
||||
- gomodguard_v2
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
|
||||
+1
-4
@@ -8,11 +8,8 @@ all: checks
|
||||
checks: lint test examples functional-test
|
||||
|
||||
lint:
|
||||
@mkdir -p ${GOPATH}/bin
|
||||
@echo "Installing golangci-lint" && curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(GOPATH)/bin
|
||||
@echo "Running $@ check"
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint cache clean
|
||||
@GO111MODULE=on ${GOPATH}/bin/golangci-lint run --timeout=5m --config ./.golangci.yml
|
||||
go tool golangci-lint run
|
||||
|
||||
vet: lint
|
||||
|
||||
|
||||
+16
@@ -46,6 +46,22 @@ func (c *Client) GetObject(ctx context.Context, bucketName, objectName string, o
|
||||
}
|
||||
}
|
||||
|
||||
if opts.RDMABuffer != nil && c.rdmaEnabled {
|
||||
n, err := c.getObjectRDMA(ctx, bucketName, objectName, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Object{
|
||||
mutex: &sync.Mutex{},
|
||||
isClosed: true,
|
||||
objectInfo: ObjectInfo{
|
||||
Key: objectName,
|
||||
Size: n,
|
||||
},
|
||||
objectInfoSet: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
gctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
// Detect if snowball is server location we are talking to.
|
||||
|
||||
+7
@@ -23,6 +23,7 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
)
|
||||
@@ -48,6 +49,12 @@ type GetObjectOptions struct {
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html
|
||||
Checksum bool
|
||||
|
||||
// RDMABuffer, when non-nil and Options.EnableRDMA=true, downloads directly
|
||||
// into a contiguous buffer via libminiocpp.so. The returned *Object's
|
||||
// Read() returns EOF immediately; bytes-transferred is in Stat().Size.
|
||||
RDMABuffer unsafe.Pointer
|
||||
RDMABufferSize int
|
||||
|
||||
// To be not used by external applications
|
||||
Internal AdvancedGetOptions
|
||||
}
|
||||
|
||||
+10
@@ -28,6 +28,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/minio/minio-go/v7/pkg/encrypt"
|
||||
"github.com/minio/minio-go/v7/pkg/s3utils"
|
||||
@@ -111,6 +112,12 @@ type PutObjectOptions struct {
|
||||
ConcurrentStreamParts bool
|
||||
Internal AdvancedPutOptions
|
||||
|
||||
// RDMABuffer, when non-nil and Options.EnableRDMA=true, selects the RDMA
|
||||
// path via libminiocpp.so. Must reference RDMABufferSize contiguous bytes.
|
||||
// When set, the reader / size args to PutObject are ignored.
|
||||
RDMABuffer unsafe.Pointer
|
||||
RDMABufferSize int
|
||||
|
||||
customHeaders http.Header
|
||||
}
|
||||
|
||||
@@ -322,6 +329,9 @@ func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].Part
|
||||
func (c *Client) PutObject(ctx context.Context, bucketName, objectName string, reader io.Reader, size int64,
|
||||
opts PutObjectOptions,
|
||||
) (info UploadInfo, err error) {
|
||||
if opts.RDMABuffer != nil && c.rdmaEnabled {
|
||||
return c.putObjectRDMA(ctx, bucketName, objectName, opts)
|
||||
}
|
||||
if size < 0 && opts.DisableMultipart {
|
||||
return UploadInfo{}, errors.New("object size must be provided with disable multipart upload")
|
||||
}
|
||||
|
||||
+15
@@ -109,6 +109,15 @@ type Client struct {
|
||||
|
||||
trailingHeaderSupport bool
|
||||
maxRetries int
|
||||
|
||||
// RDMA dispatch state. rdmaEnabled mirrors Options.EnableRDMA;
|
||||
// the rest are only touched by rdma.go (built with -tags=rdma) but
|
||||
// have to live on the struct so the stub and the tagged build share
|
||||
// one shape.
|
||||
rdmaEnabled bool
|
||||
rdmaOnce sync.Once //nolint:unused
|
||||
rdmaHandle *rdmaClientHandle //nolint:unused
|
||||
rdmaInitErr error //nolint:unused
|
||||
}
|
||||
|
||||
// Options for New method
|
||||
@@ -156,6 +165,11 @@ type Options struct {
|
||||
// Number of times a request is retried. Defaults to 10 retries if this option is not configured.
|
||||
// Set to 1 to disable retries.
|
||||
MaxRetries int
|
||||
|
||||
// EnableRDMA causes PutObject / GetObject to dispatch to libminiocpp.so
|
||||
// when the caller supplies PutObjectOptions.RDMABuffer / GetObjectOptions.RDMABuffer.
|
||||
// No-op unless built with -tags=rdma.
|
||||
EnableRDMA bool
|
||||
}
|
||||
|
||||
// Global constants.
|
||||
@@ -311,6 +325,7 @@ func privateNew(endpoint string, opts *Options) (*Client, error) {
|
||||
}
|
||||
|
||||
clnt.trailingHeaderSupport = opts.TrailingHeaders && clnt.overrideSignerType.IsV4()
|
||||
clnt.rdmaEnabled = opts.EnableRDMA
|
||||
|
||||
// Sets bucket lookup style, whether server accepts DNS or Path lookup. Default is Auto - determined
|
||||
// by the SDK. When Auto is specified, DNS lookup is used for Amazon/Google cloud endpoints and Path for all other endpoints.
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-ini/ini"
|
||||
"gopkg.in/ini.v1"
|
||||
)
|
||||
|
||||
// A externalProcessCredentials stores the output of a credential_process
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
//go:build rdma
|
||||
|
||||
/*
|
||||
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
|
||||
* Copyright 2024-2026 MinIO, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
package minio
|
||||
|
||||
// #cgo CFLAGS: -DMINIO_CPP_RDMA
|
||||
// #cgo CXXFLAGS: --std=c++17 -DMINIO_CPP_RDMA
|
||||
// #cgo LDFLAGS: -lminiocpp
|
||||
// #include <stdlib.h>
|
||||
// #include <miniocpp/c_api.h>
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var ErrRDMANotConnected = errors.New("RDMA infrastructure not connected")
|
||||
|
||||
type rdmaClientHandle struct {
|
||||
cptr *C.miniocpp_client
|
||||
}
|
||||
|
||||
func newRDMAClient(c *Client) (*rdmaClientHandle, error) {
|
||||
creds, err := c.credsProvider.Get()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RDMA: credentials: %w", err)
|
||||
}
|
||||
|
||||
endpoint := C.CString(c.endpointURL.Host)
|
||||
defer C.free(unsafe.Pointer(endpoint))
|
||||
region := C.CString(c.region)
|
||||
defer C.free(unsafe.Pointer(region))
|
||||
accessKey := C.CString(creds.AccessKeyID)
|
||||
defer C.free(unsafe.Pointer(accessKey))
|
||||
secretKey := C.CString(creds.SecretAccessKey)
|
||||
defer C.free(unsafe.Pointer(secretKey))
|
||||
sessionToken := C.CString(creds.SessionToken)
|
||||
defer C.free(unsafe.Pointer(sessionToken))
|
||||
|
||||
var useHTTPS C.int
|
||||
if c.secure {
|
||||
useHTTPS = 1
|
||||
}
|
||||
|
||||
cptr := C.miniocpp_client_new(endpoint, region, accessKey, secretKey,
|
||||
sessionToken, useHTTPS)
|
||||
if cptr == nil {
|
||||
return nil, fmt.Errorf("RDMA: %s", lastRDMAError())
|
||||
}
|
||||
return &rdmaClientHandle{cptr: cptr}, nil
|
||||
}
|
||||
|
||||
func (c *Client) putObjectRDMA(_ context.Context, bucketName, objectName string,
|
||||
opts PutObjectOptions,
|
||||
) (UploadInfo, error) {
|
||||
h, err := c.rdma()
|
||||
if err != nil {
|
||||
return UploadInfo{}, err
|
||||
}
|
||||
|
||||
bucketC := C.CString(bucketName)
|
||||
defer C.free(unsafe.Pointer(bucketC))
|
||||
objectC := C.CString(objectName)
|
||||
defer C.free(unsafe.Pointer(objectC))
|
||||
|
||||
var etagBuf, checksumBuf [64]C.char
|
||||
n := C.miniocpp_put_object(h.cptr, bucketC, objectC,
|
||||
opts.RDMABuffer, C.size_t(opts.RDMABufferSize),
|
||||
nil, nil, &etagBuf[0], &checksumBuf[0])
|
||||
if n < 0 {
|
||||
return UploadInfo{}, fmt.Errorf("RDMA put: %s", lastRDMAError())
|
||||
}
|
||||
|
||||
return UploadInfo{
|
||||
Bucket: bucketName,
|
||||
Key: objectName,
|
||||
Size: int64(n),
|
||||
ETag: C.GoString(&etagBuf[0]),
|
||||
ChecksumCRC64NVME: C.GoString(&checksumBuf[0]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) getObjectRDMA(_ context.Context, bucketName, objectName string,
|
||||
opts GetObjectOptions,
|
||||
) (int64, error) {
|
||||
h, err := c.rdma()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
bucketC := C.CString(bucketName)
|
||||
defer C.free(unsafe.Pointer(bucketC))
|
||||
objectC := C.CString(objectName)
|
||||
defer C.free(unsafe.Pointer(objectC))
|
||||
|
||||
n := C.miniocpp_get_object(h.cptr, bucketC, objectC,
|
||||
opts.RDMABuffer, C.size_t(opts.RDMABufferSize), nil, nil)
|
||||
if n < 0 {
|
||||
return 0, fmt.Errorf("RDMA get: %s", lastRDMAError())
|
||||
}
|
||||
return int64(n), nil
|
||||
}
|
||||
|
||||
func (c *Client) rdma() (*rdmaClientHandle, error) {
|
||||
c.rdmaOnce.Do(func() {
|
||||
c.rdmaHandle, c.rdmaInitErr = newRDMAClient(c)
|
||||
})
|
||||
return c.rdmaHandle, c.rdmaInitErr
|
||||
}
|
||||
|
||||
func lastRDMAError() string {
|
||||
msg := C.miniocpp_last_error()
|
||||
if msg == nil {
|
||||
return "unknown error"
|
||||
}
|
||||
return C.GoString(msg)
|
||||
}
|
||||
|
||||
// AlignedBuffer allocates a page-aligned buffer of n bytes for use as
|
||||
// PutObjectOptions.RDMABuffer / GetObjectOptions.RDMABuffer. Release with
|
||||
// FreeAlignedBuffer. Returns nil on allocation failure.
|
||||
func AlignedBuffer(n int) unsafe.Pointer {
|
||||
return C.miniocpp_alloc_aligned(C.size_t(n))
|
||||
}
|
||||
|
||||
// FreeAlignedBuffer releases a buffer from AlignedBuffer.
|
||||
func FreeAlignedBuffer(p unsafe.Pointer) { C.miniocpp_free_aligned(p) }
|
||||
|
||||
// IsRDMAAvailable reports whether cuObj is connected to a cuObjServer.
|
||||
func IsRDMAAvailable() bool { return C.miniocpp_rdma_available() != 0 }
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
//go:build !rdma
|
||||
|
||||
/*
|
||||
* MinIO Go Library for Amazon S3 Compatible Cloud Storage
|
||||
* Copyright 2024-2026 MinIO, Inc.
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
package minio
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// ErrRDMANotCompiled is returned when RDMA dispatch is requested but the
|
||||
// binary was built without -tags=rdma.
|
||||
var ErrRDMANotCompiled = errors.New("RDMA support not compiled in (build with -tags=rdma)")
|
||||
|
||||
// rdmaClientHandle is the no-tag placeholder type so Client (in api.go)
|
||||
// has a stable shape regardless of build tags. The rdma.go variant
|
||||
// defines the real struct.
|
||||
type rdmaClientHandle struct{} //nolint:unused
|
||||
|
||||
func (c *Client) putObjectRDMA(_ context.Context, _, _ string, _ PutObjectOptions) (UploadInfo, error) {
|
||||
return UploadInfo{}, ErrRDMANotCompiled
|
||||
}
|
||||
|
||||
func (c *Client) getObjectRDMA(_ context.Context, _, _ string, _ GetObjectOptions) (int64, error) {
|
||||
return 0, ErrRDMANotCompiled
|
||||
}
|
||||
|
||||
// AlignedBuffer is unavailable without -tags=rdma; returns nil.
|
||||
func AlignedBuffer(_ int) unsafe.Pointer { return nil }
|
||||
|
||||
// FreeAlignedBuffer is a no-op without -tags=rdma.
|
||||
func FreeAlignedBuffer(_ unsafe.Pointer) {}
|
||||
|
||||
// IsRDMAAvailable always returns false without -tags=rdma.
|
||||
func IsRDMAAvailable() bool { return false }
|
||||
+2
-2
@@ -159,7 +159,7 @@ func NewUnary(m map[string]interface{}, unprotected []string, tp trace.TracerPro
|
||||
ctx = ctxpkg.ContextSetScopes(ctx, tokenScope)
|
||||
// TODO: MFA enforcement should be moved to the individual service level, so each service can
|
||||
// decide which endpoints require MFA and which are accessible without it.
|
||||
if conf.MFAEnabled {
|
||||
if conf.MFAEnabled && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
|
||||
if mfav := metadata.ValueFromIncomingContext(ctx, ctxpkg.MFAOutgoingHeader); !slices.Contains(mfav, "true") {
|
||||
log.Warn().Str("user_id", u.Id.OpaqueId).Strs("mfa_values", mfav).Msg("MFA is required")
|
||||
return mfaResponse(ctx, req, info)
|
||||
@@ -256,7 +256,7 @@ func NewStream(m map[string]interface{}, unprotected []string, tp trace.TracerPr
|
||||
ctx = ctxpkg.ContextSetScopes(ctx, tokenScope)
|
||||
// TODO: MFA enforcement should be moved to the individual service level, so each service can
|
||||
// decide which endpoints require MFA and which are accessible without it.
|
||||
if conf.MFAEnabled {
|
||||
if conf.MFAEnabled && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
|
||||
if mfav := metadata.ValueFromIncomingContext(ctx, ctxpkg.MFAOutgoingHeader); !slices.Contains(mfav, "true") {
|
||||
log.Warn().Str("user_id", u.Id.OpaqueId).Strs("mfa_values", mfav).Msg("MFA is required")
|
||||
return status.Errorf(codes.PermissionDenied, "MFA required to access vault storage")
|
||||
|
||||
Generated
Vendored
+37
-19
@@ -28,6 +28,7 @@ import (
|
||||
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
@@ -245,7 +246,7 @@ func FileDownloaded(r *provider.InitiateFileDownloadResponse, req *provider.Init
|
||||
}
|
||||
|
||||
// FileLocked converts the response to an events
|
||||
func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, owner *user.UserId, executant *user.User) events.FileLocked {
|
||||
func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, spaceOwner *user.UserId, executant *user.User) events.FileLocked {
|
||||
return events.FileLocked{
|
||||
Executant: executant.GetId(),
|
||||
Ref: req.Ref,
|
||||
@@ -255,7 +256,7 @@ func FileLocked(r *provider.SetLockResponse, req *provider.SetLockRequest, owner
|
||||
}
|
||||
|
||||
// FileUnlocked converts the response to an event
|
||||
func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, owner *user.UserId, executant *user.User) events.FileUnlocked {
|
||||
func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, spaceOwner *user.UserId, executant *user.User) events.FileUnlocked {
|
||||
return events.FileUnlocked{
|
||||
Executant: executant.GetId(),
|
||||
Ref: req.Ref,
|
||||
@@ -265,29 +266,42 @@ func FileUnlocked(r *provider.UnlockResponse, req *provider.UnlockRequest, owner
|
||||
}
|
||||
|
||||
// ItemTrashed converts the response to an event
|
||||
func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, spaceOwner *user.UserId, executant *user.User) events.ItemTrashed {
|
||||
opaqueID := utils.ReadPlainFromOpaque(r.Opaque, "opaque_id")
|
||||
func ItemTrashed(r *provider.DeleteResponse, req *provider.DeleteRequest, result *storage.DeleteResult, executant *user.User) events.ItemTrashed {
|
||||
var spaceOwner *user.UserId
|
||||
var id *provider.ResourceId
|
||||
if result != nil {
|
||||
spaceOwner = result.SpaceOwner
|
||||
id = result.ResourceId
|
||||
}
|
||||
reqID := req.GetRef().GetResourceId()
|
||||
if id == nil {
|
||||
if reqID != nil {
|
||||
id = &provider.ResourceId{
|
||||
StorageId: reqID.GetStorageId(),
|
||||
SpaceId: reqID.GetSpaceId(),
|
||||
OpaqueId: reqID.GetOpaqueId(),
|
||||
}
|
||||
}
|
||||
} else if id.GetStorageId() == "" {
|
||||
id.StorageId = reqID.GetStorageId()
|
||||
}
|
||||
return events.ItemTrashed{
|
||||
SpaceOwner: spaceOwner,
|
||||
Executant: executant.GetId(),
|
||||
Ref: req.Ref,
|
||||
ID: &provider.ResourceId{
|
||||
StorageId: req.Ref.GetResourceId().GetStorageId(),
|
||||
SpaceId: req.Ref.GetResourceId().GetSpaceId(),
|
||||
OpaqueId: opaqueID,
|
||||
},
|
||||
SpaceOwner: spaceOwner,
|
||||
Executant: executant.GetId(),
|
||||
Ref: req.Ref,
|
||||
ID: id,
|
||||
Timestamp: utils.TSNow(),
|
||||
ImpersonatingUser: extractImpersonator(executant),
|
||||
}
|
||||
}
|
||||
|
||||
// ItemMoved converts the response to an event
|
||||
func ItemMoved(r *provider.MoveResponse, req *provider.MoveRequest, spaceOwner *user.UserId, executant *user.User) events.ItemMoved {
|
||||
func ItemMoved(r *provider.MoveResponse, req *provider.MoveRequest, result *storage.MoveResult, executant *user.User) events.ItemMoved {
|
||||
return events.ItemMoved{
|
||||
SpaceOwner: spaceOwner,
|
||||
SpaceOwner: result.SpaceOwner,
|
||||
Executant: executant.GetId(),
|
||||
Ref: req.Destination,
|
||||
OldReference: req.Source,
|
||||
Ref: result.NewReference,
|
||||
OldReference: result.OldReference,
|
||||
Timestamp: utils.TSNow(),
|
||||
ImpersonatingUser: extractImpersonator(executant),
|
||||
}
|
||||
@@ -425,13 +439,17 @@ func SpaceDisabled(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteS
|
||||
}
|
||||
|
||||
// SpaceDeleted converts the response to an event
|
||||
func SpaceDeleted(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteStorageSpaceRequest, executant *user.User) events.SpaceDeleted {
|
||||
func SpaceDeleted(r *provider.DeleteStorageSpaceResponse, req *provider.DeleteStorageSpaceRequest, result *storage.DeleteStorageSpaceResult, executant *user.User) events.SpaceDeleted {
|
||||
var spaceName string
|
||||
var final map[string]provider.ResourcePermissions
|
||||
_ = utils.ReadJSONFromOpaque(r.GetOpaque(), "grants", &final)
|
||||
if result != nil {
|
||||
spaceName = result.SpaceName
|
||||
final = result.FinalMembers
|
||||
}
|
||||
return events.SpaceDeleted{
|
||||
Executant: executant.GetId(),
|
||||
ID: req.Id,
|
||||
SpaceName: utils.ReadPlainFromOpaque(r.GetOpaque(), "spacename"),
|
||||
SpaceName: spaceName,
|
||||
FinalMembers: final,
|
||||
Timestamp: time.Now(),
|
||||
}
|
||||
|
||||
Generated
Vendored
+25
-20
@@ -22,12 +22,12 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
ocmcore "github.com/cs3org/go-cs3apis/cs3/ocm/core/v1beta1"
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
@@ -35,7 +35,6 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -58,27 +57,33 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
|
||||
}
|
||||
|
||||
interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
|
||||
// Register a channel in the context to receive the space owner id from the handler(s) further down the stack
|
||||
var ownerID *user.UserId
|
||||
sendOwnerChan := make(chan *user.UserId)
|
||||
ctx = storagespace.ContextRegisterSendOwnerChan(ctx, sendOwnerChan)
|
||||
// Register slots so the storage driver can pass data back up through
|
||||
// the immutable context chain; values are read here after the handler returns.
|
||||
ctx = storagespace.ContextRegisterSpaceOwnerSlot(ctx)
|
||||
ctx = storagespace.ContextRegisterMoveResultSlot(ctx)
|
||||
// Register a slot for typed Delete results
|
||||
ctx = storagespace.ContextRegisterDeleteResultSlot(ctx)
|
||||
|
||||
// Register a slot for typed DeleteStorageSpace results
|
||||
ctx = storagespace.ContextRegisterDeleteStorageSpaceResultSlot(ctx)
|
||||
|
||||
res, err := handler(ctx, req)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Read the space owner id from the channel
|
||||
select {
|
||||
case ownerID = <-sendOwnerChan:
|
||||
default:
|
||||
}
|
||||
spaceOwnerID := storagespace.ContextGetSpaceOwner(ctx) // nil if not set by handler
|
||||
|
||||
executant, _ := revactx.ContextGetUser(ctx)
|
||||
|
||||
// The MoveResponse event is moved to the decomposedfs
|
||||
var ev interface{}
|
||||
switch v := res.(type) {
|
||||
case *provider.MoveResponse:
|
||||
if isSuccess(v) {
|
||||
if result := storagespace.ContextGetMoveResult(ctx); result != nil {
|
||||
ev = ItemMoved(v, req.(*provider.MoveRequest), result, executant)
|
||||
}
|
||||
}
|
||||
case *collaboration.CreateShareResponse:
|
||||
if isSuccess(v) {
|
||||
ev = ShareCreated(v, executant)
|
||||
@@ -137,7 +142,7 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
|
||||
}
|
||||
case *provider.CreateContainerResponse:
|
||||
if isSuccess(v) {
|
||||
ev = ContainerCreated(v, req.(*provider.CreateContainerRequest), ownerID, executant)
|
||||
ev = ContainerCreated(v, req.(*provider.CreateContainerRequest), spaceOwnerID, executant)
|
||||
}
|
||||
case *provider.InitiateFileDownloadResponse:
|
||||
if isSuccess(v) {
|
||||
@@ -145,7 +150,7 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
|
||||
}
|
||||
case *provider.DeleteResponse:
|
||||
if isSuccess(v) {
|
||||
ev = ItemTrashed(v, req.(*provider.DeleteRequest), ownerID, executant)
|
||||
ev = ItemTrashed(v, req.(*provider.DeleteRequest), storagespace.ContextGetDeleteResult(ctx), executant)
|
||||
}
|
||||
case *provider.PurgeRecycleResponse:
|
||||
if isSuccess(v) {
|
||||
@@ -153,11 +158,11 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
|
||||
}
|
||||
case *provider.RestoreRecycleItemResponse:
|
||||
if isSuccess(v) {
|
||||
ev = ItemRestored(v, req.(*provider.RestoreRecycleItemRequest), ownerID, executant)
|
||||
ev = ItemRestored(v, req.(*provider.RestoreRecycleItemRequest), spaceOwnerID, executant)
|
||||
}
|
||||
case *provider.RestoreFileVersionResponse:
|
||||
if isSuccess(v) {
|
||||
ev = FileVersionRestored(v, req.(*provider.RestoreFileVersionRequest), ownerID, executant)
|
||||
ev = FileVersionRestored(v, req.(*provider.RestoreFileVersionRequest), spaceOwnerID, executant)
|
||||
}
|
||||
case *provider.CreateStorageSpaceResponse:
|
||||
if isSuccess(v) && v.StorageSpace != nil { // TODO: Why are there CreateStorageSpaceResponses with nil StorageSpace?
|
||||
@@ -178,22 +183,22 @@ func NewUnary(m map[string]interface{}) (grpc.UnaryServerInterceptor, int, error
|
||||
if isSuccess(v) {
|
||||
r := req.(*provider.DeleteStorageSpaceRequest)
|
||||
if utils.ExistsInOpaque(r.Opaque, "purge") {
|
||||
ev = SpaceDeleted(v, r, executant)
|
||||
ev = SpaceDeleted(v, r, storagespace.ContextGetDeleteStorageSpaceResult(ctx), executant)
|
||||
} else {
|
||||
ev = SpaceDisabled(v, r, executant)
|
||||
}
|
||||
}
|
||||
case *provider.TouchFileResponse:
|
||||
if isSuccess(v) {
|
||||
ev = FileTouched(v, req.(*provider.TouchFileRequest), ownerID, executant)
|
||||
ev = FileTouched(v, req.(*provider.TouchFileRequest), spaceOwnerID, executant)
|
||||
}
|
||||
case *provider.SetLockResponse:
|
||||
if isSuccess(v) {
|
||||
ev = FileLocked(v, req.(*provider.SetLockRequest), ownerID, executant)
|
||||
ev = FileLocked(v, req.(*provider.SetLockRequest), spaceOwnerID, executant)
|
||||
}
|
||||
case *provider.UnlockResponse:
|
||||
if isSuccess(v) {
|
||||
ev = FileUnlocked(v, req.(*provider.UnlockRequest), ownerID, executant)
|
||||
ev = FileUnlocked(v, req.(*provider.UnlockRequest), spaceOwnerID, executant)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Generated
Vendored
+59
-73
@@ -239,7 +239,13 @@ func (s *Service) SetLock(ctx context.Context, req *provider.SetLockRequest) (*p
|
||||
Status: status.NewPermissionDenied(ctx, nil, "no permission to lock the share"),
|
||||
}, nil
|
||||
}
|
||||
err := s.Storage.SetLock(ctx, req.Ref, req.Lock)
|
||||
res, err := s.Storage.SetLock(ctx, req.Ref, req.Lock)
|
||||
if err != nil {
|
||||
return &provider.SetLockResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "set lock", err),
|
||||
}, nil
|
||||
}
|
||||
storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner)
|
||||
|
||||
return &provider.SetLockResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "set lock", err),
|
||||
@@ -279,7 +285,13 @@ func (s *Service) Unlock(ctx context.Context, req *provider.UnlockRequest) (*pro
|
||||
}, nil
|
||||
}
|
||||
|
||||
err := s.Storage.Unlock(ctx, req.Ref, req.Lock)
|
||||
res, err := s.Storage.Unlock(ctx, req.Ref, req.Lock)
|
||||
if err != nil {
|
||||
return &provider.UnlockResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "unlock", err),
|
||||
}, nil
|
||||
}
|
||||
storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner)
|
||||
|
||||
return &provider.UnlockResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "unlock", err),
|
||||
@@ -613,35 +625,8 @@ func (s *Service) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSt
|
||||
}
|
||||
|
||||
func (s *Service) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*provider.DeleteStorageSpaceResponse, error) {
|
||||
// we need to get the space before so we can return critical information
|
||||
// FIXME: why is this string parsing necessary?
|
||||
idraw, _ := storagespace.ParseID(req.Id.GetOpaqueId())
|
||||
idraw.OpaqueId = idraw.GetSpaceId()
|
||||
id := &provider.StorageSpaceId{OpaqueId: storagespace.FormatResourceID(&idraw)}
|
||||
|
||||
spaces, err := s.Storage.ListStorageSpaces(ctx, []*provider.ListStorageSpacesRequest_Filter{{Type: provider.ListStorageSpacesRequest_Filter_TYPE_ID, Term: &provider.ListStorageSpacesRequest_Filter_Id{Id: id}}}, true)
|
||||
result, err := s.Storage.DeleteStorageSpace(ctx, req)
|
||||
if err != nil {
|
||||
var st *rpc.Status
|
||||
switch err.(type) {
|
||||
case errtypes.IsNotFound:
|
||||
st = status.NewNotFound(ctx, "space not found")
|
||||
case errtypes.PermissionDenied:
|
||||
st = status.NewPermissionDenied(ctx, err, "permission denied")
|
||||
case errtypes.BadRequest:
|
||||
st = status.NewInvalid(ctx, err.Error())
|
||||
default:
|
||||
st = status.NewInternal(ctx, "error deleting space: "+req.Id.String())
|
||||
}
|
||||
return &provider.DeleteStorageSpaceResponse{
|
||||
Status: st,
|
||||
}, nil
|
||||
} else if len(spaces) != 1 {
|
||||
return &provider.DeleteStorageSpaceResponse{
|
||||
Status: status.NewNotFound(ctx, "space not found"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
if err := s.Storage.DeleteStorageSpace(ctx, req); err != nil {
|
||||
var st *rpc.Status
|
||||
switch err.(type) {
|
||||
case errtypes.IsNotFound:
|
||||
@@ -664,15 +649,13 @@ func (s *Service) DeleteStorageSpace(ctx context.Context, req *provider.DeleteSt
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TODO: update cs3api
|
||||
o := utils.AppendPlainToOpaque(nil, "spacename", spaces[0].GetName())
|
||||
o.Map["grants"] = spaces[0].GetOpaque().GetMap()["grants"]
|
||||
|
||||
res := &provider.DeleteStorageSpaceResponse{
|
||||
Opaque: o,
|
||||
Status: status.NewOK(ctx),
|
||||
if result != nil {
|
||||
storagespace.ContextSetDeleteStorageSpaceResult(ctx, result)
|
||||
}
|
||||
return res, nil
|
||||
|
||||
return &provider.DeleteStorageSpaceResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) CreateContainer(ctx context.Context, req *provider.CreateContainerRequest) (*provider.CreateContainerResponse, error) {
|
||||
@@ -683,7 +666,13 @@ func (s *Service) CreateContainer(ctx context.Context, req *provider.CreateConta
|
||||
}
|
||||
}
|
||||
|
||||
err := s.Storage.CreateDir(ctx, req.Ref)
|
||||
res, err := s.Storage.CreateDir(ctx, req.Ref)
|
||||
if err != nil {
|
||||
return &provider.CreateContainerResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "create container", err),
|
||||
}, nil
|
||||
}
|
||||
storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner)
|
||||
|
||||
return &provider.CreateContainerResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "create container", err),
|
||||
@@ -700,7 +689,13 @@ func (s *Service) TouchFile(ctx context.Context, req *provider.TouchFileRequest)
|
||||
mtime = utils.ReadPlainFromOpaque(req.Opaque, "X-OC-Mtime")
|
||||
}
|
||||
|
||||
err := s.Storage.TouchFile(ctx, req.Ref, utils.ExistsInOpaque(req.Opaque, "markprocessing"), mtime)
|
||||
res, err := s.Storage.TouchFile(ctx, req.Ref, utils.ExistsInOpaque(req.Opaque, "markprocessing"), mtime)
|
||||
if err != nil {
|
||||
return &provider.TouchFileResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "touch file", err),
|
||||
}, nil
|
||||
}
|
||||
storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner)
|
||||
|
||||
return &provider.TouchFileResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "touch file", err),
|
||||
@@ -725,44 +720,24 @@ func (s *Service) Delete(ctx context.Context, req *provider.DeleteRequest) (*pro
|
||||
}
|
||||
}
|
||||
|
||||
md, err := s.Storage.GetMD(ctx, req.Ref, []string{}, []string{"id", "status"})
|
||||
if err != nil {
|
||||
return &provider.DeleteResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "can't stat resource to delete", err),
|
||||
}, nil
|
||||
}
|
||||
result, err := s.Storage.Delete(ctx, req.Ref)
|
||||
|
||||
if utils.ReadPlainFromOpaque(md.GetOpaque(), "status") == "processing" {
|
||||
return &provider.DeleteResponse{
|
||||
Status: &rpc.Status{
|
||||
Code: rpc.Code_CODE_TOO_EARLY,
|
||||
Message: "file is processing",
|
||||
},
|
||||
Opaque: &typesv1beta1.Opaque{
|
||||
Map: map[string]*typesv1beta1.OpaqueEntry{
|
||||
"status": {Decoder: "plain", Value: []byte("processing")},
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
if err == nil && result != nil {
|
||||
storagespace.ContextSetDeleteResult(ctx, result)
|
||||
}
|
||||
|
||||
err = s.Storage.Delete(ctx, req.Ref)
|
||||
|
||||
return &provider.DeleteResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "delete", err),
|
||||
Opaque: &typesv1beta1.Opaque{
|
||||
Map: map[string]*typesv1beta1.OpaqueEntry{
|
||||
"opaque_id": {Decoder: "plain", Value: []byte(md.Id.OpaqueId)},
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Move(ctx context.Context, req *provider.MoveRequest) (*provider.MoveResponse, error) {
|
||||
ctx = ctxpkg.ContextSetLockID(ctx, req.LockId)
|
||||
|
||||
err := s.Storage.Move(ctx, req.Source, req.Destination)
|
||||
|
||||
result, err := s.Storage.Move(ctx, req.Source, req.Destination)
|
||||
if err == nil && result != nil {
|
||||
storagespace.ContextSetMoveResult(ctx, result)
|
||||
}
|
||||
return &provider.MoveResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "move", err),
|
||||
}, nil
|
||||
@@ -874,7 +849,13 @@ func (s *Service) ListFileVersions(ctx context.Context, req *provider.ListFileVe
|
||||
func (s *Service) RestoreFileVersion(ctx context.Context, req *provider.RestoreFileVersionRequest) (*provider.RestoreFileVersionResponse, error) {
|
||||
ctx = ctxpkg.ContextSetLockID(ctx, req.LockId)
|
||||
|
||||
err := s.Storage.RestoreRevision(ctx, req.Ref, req.Key)
|
||||
res, err := s.Storage.RestoreRevision(ctx, req.Ref, req.Key)
|
||||
if err != nil {
|
||||
return &provider.RestoreFileVersionResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "restore file version", err),
|
||||
}, nil
|
||||
}
|
||||
storagespace.ContextSetSpaceOwner(ctx, res.SpaceOwner)
|
||||
|
||||
return &provider.RestoreFileVersionResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "restore file version", err),
|
||||
@@ -973,12 +954,17 @@ func (s *Service) RestoreRecycleItem(ctx context.Context, req *provider.RestoreR
|
||||
|
||||
// TODO(labkode): CRITICAL: fill recycle info with storage provider.
|
||||
key, relativePath := splitKeyAndPath(req.GetKey())
|
||||
err := s.Storage.RestoreRecycleItem(ctx, req.Ref, key, relativePath, req.RestoreRef)
|
||||
|
||||
res := &provider.RestoreRecycleItemResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "restore recycle item", err),
|
||||
writeRes, err := s.Storage.RestoreRecycleItem(ctx, req.Ref, key, relativePath, req.RestoreRef)
|
||||
if err != nil {
|
||||
return &provider.RestoreRecycleItemResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "restore recycle item", err),
|
||||
}, nil
|
||||
}
|
||||
return res, nil
|
||||
storagespace.ContextSetSpaceOwner(ctx, writeRes.SpaceOwner)
|
||||
|
||||
return &provider.RestoreRecycleItemResponse{
|
||||
Status: status.NewStatusFromErrType(ctx, "restore recycle item", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) PurgeRecycle(ctx context.Context, req *provider.PurgeRecycleRequest) (*provider.PurgeRecycleResponse, error) {
|
||||
|
||||
Generated
Vendored
+2
@@ -24,6 +24,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocs/config"
|
||||
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocs/response"
|
||||
"github.com/owncloud/reva/v2/pkg/owncloud/ocs"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
// Handler renders the capability endpoint
|
||||
@@ -260,5 +261,6 @@ func (h *Handler) vaultCapabilities(c ocs.CapabilitiesData) ocs.CapabilitiesData
|
||||
caps := *c.Capabilities
|
||||
caps.FilesSharing = &sharing
|
||||
c.Capabilities = &caps
|
||||
c.Capabilities.Vault.VaultStorageProvider = utils.VaultStorageProviderID
|
||||
return c
|
||||
}
|
||||
+2
-2
@@ -203,9 +203,9 @@ func (w *wrapper) DownloadRevision(ctx context.Context, ref *provider.Reference,
|
||||
return w.FS.DownloadRevision(ctx, ref, revisionKey, openReaderfunc)
|
||||
}
|
||||
|
||||
func (w *wrapper) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
func (w *wrapper) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
if err := w.userIsProjectAdmin(ctx, ref); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return w.FS.RestoreRevision(ctx, ref, revisionKey)
|
||||
|
||||
+39
-24
@@ -213,38 +213,47 @@ func (d *driver) webdavClient(ctx context.Context, forUser *userpb.UserId, ref *
|
||||
return c, share, rel, nil
|
||||
}
|
||||
|
||||
func (d *driver) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (d *driver) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
client, _, rel, err := d.webdavClient(ctx, nil, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return client.MkdirAll(rel, 0)
|
||||
if err := client.MkdirAll(rel, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
func (d *driver) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (d *driver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
client, _, rel, err := d.webdavClient(ctx, nil, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return client.RemoveAll(rel)
|
||||
if err := client.RemoveAll(rel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (d *driver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
func (d *driver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
client, _, rel, err := d.webdavClient(ctx, nil, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return client.Write(rel, []byte{}, 0)
|
||||
if err := client.Write(rel, []byte{}, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.TouchFileResult{}, nil
|
||||
}
|
||||
|
||||
func (d *driver) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (d *driver) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
client, _, relOld, err := d.webdavClient(ctx, nil, oldRef)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
_, relNew := shareInfoFromReference(newRef)
|
||||
|
||||
return client.Rename(relOld, relNew, false)
|
||||
return nil, client.Rename(relOld, relNew, false)
|
||||
}
|
||||
|
||||
func getPathFromShareIDAndRelPath(shareID *ocmpb.ShareId, relPath string) string {
|
||||
@@ -422,16 +431,16 @@ func (d *driver) DownloadRevision(ctx context.Context, ref *provider.Reference,
|
||||
return nil, nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
|
||||
func (d *driver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error {
|
||||
return errtypes.NotSupported("operation not supported")
|
||||
func (d *driver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) {
|
||||
return nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
|
||||
func (d *driver) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) {
|
||||
return nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
|
||||
func (d *driver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
return errtypes.NotSupported("operation not supported")
|
||||
func (d *driver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
|
||||
func (d *driver) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -479,13 +488,16 @@ func (d *driver) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Refer
|
||||
}
|
||||
|
||||
// SetLock sets a lock on a file
|
||||
func (d *driver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (d *driver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
client, _, rel, err := d.webdavClient(ctx, nil, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client.Lock(rel, lock.GetLockId())
|
||||
if err := client.Lock(rel, lock.GetLockId()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.SetLockResult{}, nil
|
||||
}
|
||||
|
||||
func (d *driver) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) {
|
||||
@@ -512,13 +524,16 @@ func (d *driver) RefreshLock(ctx context.Context, ref *provider.Reference, lock
|
||||
}
|
||||
|
||||
// Unlock removes a lock from a file
|
||||
func (d *driver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (d *driver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
client, _, rel, err := d.webdavClient(ctx, nil, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client.Unlock(rel, lock.GetLockId())
|
||||
if err := client.Unlock(rel, lock.GetLockId()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.UnlockResult{}, nil
|
||||
}
|
||||
|
||||
func (d *driver) ListStorageSpaces(ctx context.Context, filters []*provider.ListStorageSpacesRequest_Filter, _ bool) ([]*provider.StorageSpace, error) {
|
||||
@@ -613,6 +628,6 @@ func (d *driver) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSto
|
||||
return nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
|
||||
func (d *driver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("operation not supported")
|
||||
func (d *driver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("operation not supported")
|
||||
}
|
||||
+2
-1
@@ -337,5 +337,6 @@ type Version struct {
|
||||
|
||||
// CapabilitiesVault holds vault capabilities
|
||||
type CapabilitiesVault struct {
|
||||
Enabled ocsBool `json:"enabled" xml:"enabled" mapstructure:"enabled"`
|
||||
Enabled ocsBool `json:"enabled" xml:"enabled" mapstructure:"enabled"`
|
||||
VaultStorageProvider string `json:"vault_storage_provider" xml:"vault_storage_provider" mapstructure:"vault_storage_provider"`
|
||||
}
|
||||
+8
@@ -523,6 +523,14 @@ func (m *manager) ListPublicShares(ctx context.Context, u *user.User, filters []
|
||||
continue
|
||||
}
|
||||
|
||||
if local.ResourceId == nil {
|
||||
log.Warn().
|
||||
Str("share_id", local.PublicShare.GetId().GetOpaqueId()).
|
||||
Str("share_token", local.Token).
|
||||
Msg("ListPublicShares: skipping share with nil resource_id")
|
||||
continue
|
||||
}
|
||||
|
||||
key := strings.Join([]string{local.ResourceId.StorageId, local.ResourceId.OpaqueId}, "!")
|
||||
if _, hit := cache[key]; !hit && !publicshare.IsCreatedByUser(&local.PublicShare, u) {
|
||||
sRes, err := client.Stat(ctx, &provider.StatRequest{Ref: &provider.Reference{ResourceId: local.ResourceId}})
|
||||
|
||||
+11
@@ -170,6 +170,15 @@ func NewTooManyRequests(ctx context.Context, msg string) *rpc.Status {
|
||||
}
|
||||
}
|
||||
|
||||
// NewTooEarly returns a Status with CODE_TOO_EARLY.
|
||||
func NewTooEarly(ctx context.Context, msg string) *rpc.Status {
|
||||
return &rpc.Status{
|
||||
Code: rpc.Code_CODE_TOO_EARLY,
|
||||
Message: msg,
|
||||
Trace: getTrace(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
// NewStatusFromErrType returns a status that corresponds to the given errtype
|
||||
func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Status {
|
||||
switch e := err.(type) {
|
||||
@@ -202,6 +211,8 @@ func NewStatusFromErrType(ctx context.Context, msg string, err error) *rpc.Statu
|
||||
return NewInvalid(ctx, msg+":"+err.Error())
|
||||
case errtypes.TooManyRequests:
|
||||
return NewTooManyRequests(ctx, msg+": "+err.Error())
|
||||
case errtypes.TooEarly:
|
||||
return NewTooEarly(ctx, msg+": "+err.Error())
|
||||
}
|
||||
|
||||
// map GRPC status codes coming from the auth middleware
|
||||
|
||||
Generated
Vendored
+3
@@ -503,6 +503,9 @@ func (c *Cache) syncWithLock(ctx context.Context, storageID, spaceID string) err
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
if err := c.Persist(ctx, storageID, spaceID); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to create empty provider cache file")
|
||||
}
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
|
||||
Generated
Vendored
+41
-2
@@ -22,6 +22,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -132,7 +133,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
for attempt := 0; attempt < 20; attempt++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
@@ -156,6 +162,13 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
timer := time.NewTimer(expBackoff(attempt))
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
@@ -219,7 +232,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
Str("spaceID", spaceID).Logger()
|
||||
|
||||
var err error
|
||||
for retries := 100; retries > 0; retries-- {
|
||||
for attempt := 0; attempt < 20; attempt++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
err = persistFunc()
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
@@ -243,6 +261,13 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
|
||||
log.Error().Err(err).Msg("persisting added received share failed")
|
||||
return err
|
||||
}
|
||||
timer := time.NewTimer(expBackoff(attempt))
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
}
|
||||
if err := c.syncWithLock(ctx, userID); err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
@@ -307,6 +332,9 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
if err := c.persist(ctx, userID); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to create empty received share cache file")
|
||||
}
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
@@ -379,6 +407,17 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// expBackoff returns full-jitter delay: rand(0, min(100ms, 2^attempt ms)).
|
||||
// attempt: 0 1 2 3 4 5 6 7+
|
||||
// max ms: 1 2 4 8 16 32 64 100
|
||||
func expBackoff(attempt int) time.Duration {
|
||||
base := time.Duration(1<<uint(attempt)) * time.Millisecond
|
||||
if base > 100*time.Millisecond {
|
||||
base = 100 * time.Millisecond
|
||||
}
|
||||
return time.Duration(rand.Int64N(int64(base) + 1))
|
||||
}
|
||||
|
||||
func userJSONPath(userID string) string {
|
||||
return filepath.Join("/users", userID, "received.json")
|
||||
}
|
||||
|
||||
Generated
Vendored
+3
@@ -284,6 +284,9 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
|
||||
span.AddEvent("updating local cache")
|
||||
case errtypes.NotFound:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
if err := c.Persist(ctx, userID); err != nil {
|
||||
log.Warn().Err(err).Msg("failed to create empty share cache file")
|
||||
}
|
||||
return nil
|
||||
case errtypes.NotModified:
|
||||
span.SetStatus(codes.Ok, "")
|
||||
|
||||
+35
-25
@@ -148,11 +148,11 @@ func (fs *cephfs) CreateHome(ctx context.Context) (err error) {
|
||||
return getRevaError(err)
|
||||
}
|
||||
|
||||
func (fs *cephfs) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *cephfs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
user := fs.makeUser(ctx)
|
||||
path, err := user.resolveRef(ref)
|
||||
if err != nil {
|
||||
return getRevaError(err)
|
||||
return nil, getRevaError(err)
|
||||
}
|
||||
|
||||
user.op(func(cv *cacheVal) {
|
||||
@@ -163,20 +163,23 @@ func (fs *cephfs) CreateDir(ctx context.Context, ref *provider.Reference) error
|
||||
//TODO(tmourati): Add entry id logic
|
||||
})
|
||||
|
||||
return getRevaError(err)
|
||||
if err := getRevaError(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *cephfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
return fmt.Errorf("unimplemented: TouchFile")
|
||||
func (fs *cephfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
return nil, fmt.Errorf("unimplemented: TouchFile")
|
||||
}
|
||||
|
||||
func (fs *cephfs) Delete(ctx context.Context, ref *provider.Reference) (err error) {
|
||||
func (fs *cephfs) Delete(ctx context.Context, ref *provider.Reference) (_ *storage.DeleteResult, err error) {
|
||||
var path string
|
||||
user := fs.makeUser(ctx)
|
||||
path, err = user.resolveRef(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.op(func(cv *cacheVal) {
|
||||
@@ -189,20 +192,24 @@ func (fs *cephfs) Delete(ctx context.Context, ref *provider.Reference) (err erro
|
||||
|
||||
//has already been deleted by direct mount
|
||||
if err != nil && err.Error() == errNotFound {
|
||||
return nil
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
return getRevaError(err)
|
||||
if err != nil {
|
||||
return nil, getRevaError(err)
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *cephfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (err error) {
|
||||
func (fs *cephfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
var oldPath, newPath string
|
||||
var err error
|
||||
user := fs.makeUser(ctx)
|
||||
if oldPath, err = user.resolveRef(oldRef); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
if newPath, err = user.resolveRef(newRef); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.op(func(cv *cacheVal) {
|
||||
@@ -215,10 +222,10 @@ func (fs *cephfs) Move(ctx context.Context, oldRef, newRef *provider.Reference)
|
||||
|
||||
// has already been moved by direct mount
|
||||
if err != nil && err.Error() == errNotFound {
|
||||
return nil
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
return getRevaError(err)
|
||||
return nil, getRevaError(err)
|
||||
}
|
||||
|
||||
func (fs *cephfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) (ri *provider.ResourceInfo, err error) {
|
||||
@@ -386,12 +393,12 @@ func (fs *cephfs) DownloadRevision(ctx context.Context, ref *provider.Reference,
|
||||
return ri, file, getRevaError(err)
|
||||
}
|
||||
|
||||
func (fs *cephfs) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (err error) {
|
||||
func (fs *cephfs) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (_ *storage.RestoreRevisionResult, err error) {
|
||||
//TODO(tmourati): Fix entry id logic
|
||||
var path string
|
||||
user := fs.makeUser(ctx)
|
||||
if path, err = user.resolveRef(ref); err != nil {
|
||||
return errors.Wrap(err, "cephfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "cephfs: error resolving ref")
|
||||
}
|
||||
|
||||
user.op(func(cv *cacheVal) {
|
||||
@@ -415,7 +422,10 @@ func (fs *cephfs) RestoreRevision(ctx context.Context, ref *provider.Reference,
|
||||
_, err = io.Copy(dst, src)
|
||||
})
|
||||
|
||||
return getRevaError(err)
|
||||
if err := getRevaError(err); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *cephfs) GetPathByID(ctx context.Context, id *provider.ResourceId) (str string, err error) {
|
||||
@@ -614,8 +624,8 @@ func (fs *cephfs) ListRecycle(ctx context.Context, ref *provider.Reference, key,
|
||||
panic("implement me")
|
||||
}
|
||||
|
||||
func (fs *cephfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
return errors.New("cephfs: restoreRecycleItem not supported")
|
||||
func (fs *cephfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return nil, errors.New("cephfs: restoreRecycleItem not supported")
|
||||
}
|
||||
|
||||
func (fs *cephfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -630,8 +640,8 @@ func (fs *cephfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSt
|
||||
return nil, errors.New("cephfs: updateStorageSpace not supported")
|
||||
}
|
||||
|
||||
func (fs *cephfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errors.New("cephfs: deleteStorageSpace not supported")
|
||||
func (fs *cephfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errors.New("cephfs: deleteStorageSpace not supported")
|
||||
}
|
||||
|
||||
// GetLock returns an existing lock on the given reference
|
||||
@@ -640,8 +650,8 @@ func (fs *cephfs) GetLock(ctx context.Context, ref *provider.Reference) (*provid
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *cephfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *cephfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -650,6 +660,6 @@ func (fs *cephfs) RefreshLock(ctx context.Context, ref *provider.Reference, lock
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *cephfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *cephfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
+18
-18
@@ -47,31 +47,31 @@ func (fs *hellofs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateS
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (fs *hellofs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("delete storage space")
|
||||
func (fs *hellofs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("delete storage space")
|
||||
}
|
||||
|
||||
// CreateDir creates a resource of type container
|
||||
func (fs *hellofs) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// TouchFile sets the mtime of a resource, creating an empty file if it does not exist
|
||||
// FIXME the markprocessing flag is an implementation detail of decomposedfs, remove it from the function
|
||||
// FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string
|
||||
func (fs *hellofs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// Delete deletes a resource.
|
||||
// If the storage driver supports a recycle bin it should moves it to the recycle bin
|
||||
func (fs *hellofs) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// Move changes the path of a resource
|
||||
func (fs *hellofs) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// Upload creates or updates a resource of type file with a new revision
|
||||
@@ -132,8 +132,8 @@ func (fs *hellofs) GetLock(ctx context.Context, ref *provider.Reference) (*provi
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *hellofs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -142,8 +142,8 @@ func (fs *hellofs) RefreshLock(ctx context.Context, ref *provider.Reference, loc
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *hellofs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// revisions
|
||||
@@ -159,8 +159,8 @@ func (fs *hellofs) DownloadRevision(ctx context.Context, ref *provider.Reference
|
||||
}
|
||||
|
||||
// RestoreRevision restores a revision
|
||||
func (fs *hellofs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// trash
|
||||
@@ -182,8 +182,8 @@ func (fs *hellofs) ListRecycle(ctx context.Context, ref *provider.Reference, key
|
||||
|
||||
// RestoreRecycleItem restores an item from the recyle bin
|
||||
// if restoreRef is nil the resource should be restored at the original path
|
||||
func (fs *hellofs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *hellofs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// CreateHome creates a users home
|
||||
|
||||
+37
-23
@@ -257,38 +257,44 @@ func (nc *StorageDriver) CreateHome(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// CreateDir as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (nc *StorageDriver) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
bodyStr, err := json.Marshal(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
log := appctx.GetLogger(ctx)
|
||||
log.Info().Msgf("CreateDir %s", bodyStr)
|
||||
|
||||
_, _, err = nc.do(ctx, Action{"CreateDir", string(bodyStr)})
|
||||
return err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
return fmt.Errorf("unimplemented: TouchFile")
|
||||
func (nc *StorageDriver) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
return nil, fmt.Errorf("unimplemented: TouchFile")
|
||||
}
|
||||
|
||||
// Delete as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (nc *StorageDriver) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
bodyStr, err := json.Marshal(ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
log := appctx.GetLogger(ctx)
|
||||
log.Info().Msgf("Delete %s", bodyStr)
|
||||
|
||||
_, _, err = nc.do(ctx, Action{"Delete", string(bodyStr)})
|
||||
return err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
// Move as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
type paramsObj struct {
|
||||
OldRef *provider.Reference `json:"oldRef"`
|
||||
NewRef *provider.Reference `json:"newRef"`
|
||||
@@ -302,7 +308,10 @@ func (nc *StorageDriver) Move(ctx context.Context, oldRef, newRef *provider.Refe
|
||||
log.Info().Msgf("Move %s", bodyStr)
|
||||
|
||||
_, _, err := nc.do(ctx, Action{"Move", string(bodyStr)})
|
||||
return err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
// GetMD as defined in the storage.FS interface
|
||||
@@ -505,7 +514,7 @@ func (nc *StorageDriver) DownloadRevision(ctx context.Context, ref *provider.Ref
|
||||
}
|
||||
|
||||
// RestoreRevision as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error {
|
||||
func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) {
|
||||
type paramsObj struct {
|
||||
Ref *provider.Reference `json:"ref"`
|
||||
Key string `json:"key"`
|
||||
@@ -519,7 +528,10 @@ func (nc *StorageDriver) RestoreRevision(ctx context.Context, ref *provider.Refe
|
||||
log.Info().Msgf("RestoreRevision %s", bodyStr)
|
||||
|
||||
_, _, err := nc.do(ctx, Action{"RestoreRevision", string(bodyStr)})
|
||||
return err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
// ListRecycle as defined in the storage.FS interface
|
||||
@@ -554,7 +566,7 @@ func (nc *StorageDriver) ListRecycle(ctx context.Context, ref *provider.Referenc
|
||||
}
|
||||
|
||||
// RestoreRecycleItem as defined in the storage.FS interface
|
||||
func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
type paramsObj struct {
|
||||
Key string `json:"key"`
|
||||
Path string `json:"path"`
|
||||
@@ -571,8 +583,10 @@ func (nc *StorageDriver) RestoreRecycleItem(ctx context.Context, ref *provider.R
|
||||
log.Info().Msgf("RestoreRecycleItem %s", bodyStr)
|
||||
|
||||
_, _, err := nc.do(ctx, Action{"RestoreRecycleItem", string(bodyStr)})
|
||||
|
||||
return err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{}, nil
|
||||
}
|
||||
|
||||
// PurgeRecycleItem as defined in the storage.FS interface
|
||||
@@ -848,8 +862,8 @@ func (nc *StorageDriver) GetLock(ctx context.Context, ref *provider.Reference) (
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (nc *StorageDriver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (nc *StorageDriver) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -858,8 +872,8 @@ func (nc *StorageDriver) RefreshLock(ctx context.Context, ref *provider.Referenc
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (nc *StorageDriver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (nc *StorageDriver) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// ListStorageSpaces as defined in the storage.FS interface
|
||||
@@ -914,16 +928,16 @@ func (nc *StorageDriver) UpdateStorageSpace(ctx context.Context, req *provider.U
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (nc *StorageDriver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
func (nc *StorageDriver) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
bodyStr, _ := json.Marshal(req)
|
||||
_, respBody, err := nc.do(ctx, Action{"DeleteStorageSpace", string(bodyStr)})
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
var respObj provider.DeleteStorageSpaceResponse
|
||||
err = json.Unmarshal(respBody, &respObj)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return nil
|
||||
return &storage.DeleteStorageSpaceResult{}, nil
|
||||
}
|
||||
+96
-86
@@ -754,38 +754,38 @@ func (fs *owncloudsqlfs) GetHome(ctx context.Context) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) {
|
||||
func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference) (_ *storage.CreateDirResult, err error) {
|
||||
|
||||
ip, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check permissions of parent dir
|
||||
if perm, err := fs.readPermissions(ctx, filepath.Dir(ip)); err == nil {
|
||||
if !perm.CreateContainer {
|
||||
return errtypes.PermissionDenied("")
|
||||
return nil, errtypes.PermissionDenied("")
|
||||
}
|
||||
} else {
|
||||
if isNotFound(err) {
|
||||
return errtypes.PreconditionFailed(ref.Path)
|
||||
return nil, errtypes.PreconditionFailed(ref.Path)
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
}
|
||||
|
||||
if err = os.Mkdir(ip, 0700); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.PreconditionFailed(ref.Path)
|
||||
return nil, errtypes.PreconditionFailed(ref.Path)
|
||||
}
|
||||
if os.IsExist(err) {
|
||||
return errtypes.AlreadyExists(ref.Path)
|
||||
return nil, errtypes.AlreadyExists(ref.Path)
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error creating dir "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
return nil, errors.Wrap(err, "owncloudsql: error creating dir "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
}
|
||||
|
||||
fi, err := os.Stat(ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
mtime := time.Now().Unix()
|
||||
|
||||
@@ -803,54 +803,55 @@ func (fs *owncloudsqlfs) CreateDir(ctx context.Context, ref *provider.Reference)
|
||||
}
|
||||
storageID, err := fs.getStorage(ctx, ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false)
|
||||
if err != nil {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, filepath.Dir(ip))
|
||||
if err := fs.propagate(ctx, filepath.Dir(ip)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
ip, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check permissions of parent dir
|
||||
parentPerms, err := fs.readPermissions(ctx, filepath.Dir(ip))
|
||||
if err == nil {
|
||||
if !parentPerms.InitiateFileUpload {
|
||||
return errtypes.PermissionDenied("")
|
||||
return nil, errtypes.PermissionDenied("")
|
||||
}
|
||||
} else {
|
||||
if isNotFound(err) {
|
||||
return errtypes.NotFound(ref.Path)
|
||||
return nil, errtypes.NotFound(ref.Path)
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
}
|
||||
|
||||
_, err = os.Create(ip)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.NotFound(ref.Path)
|
||||
return nil, errtypes.NotFound(ref.Path)
|
||||
}
|
||||
// FIXME we also need already exists error, webdav expects 405 MethodNotAllowed
|
||||
return errors.Wrap(err, "owncloudsql: error creating file "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
return nil, errors.Wrap(err, "owncloudsql: error creating file "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
}
|
||||
|
||||
if err = os.Chmod(ip, 0700); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error setting file permissions on "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
return nil, errors.Wrap(err, "owncloudsql: error setting file permissions on "+fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
}
|
||||
|
||||
fi, err := os.Stat(ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
storageMtime := time.Now().Unix()
|
||||
mt := storageMtime
|
||||
@@ -874,14 +875,17 @@ func (fs *owncloudsqlfs) TouchFile(ctx context.Context, ref *provider.Reference,
|
||||
}
|
||||
storageID, err := fs.getStorage(ctx, ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, filepath.Dir(ip))
|
||||
if err := fs.propagate(ctx, filepath.Dir(ip)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.TouchFileResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) CreateReference(ctx context.Context, sp string, targetURI *url.URL) error {
|
||||
@@ -1143,8 +1147,8 @@ func (fs *owncloudsqlfs) GetLock(ctx context.Context, ref *provider.Reference) (
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *owncloudsqlfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *owncloudsqlfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -1153,8 +1157,8 @@ func (fs *owncloudsqlfs) RefreshLock(ctx context.Context, ref *provider.Referenc
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// Delete is actually only a move to trash
|
||||
@@ -1166,40 +1170,40 @@ func (fs *owncloudsqlfs) Unlock(ctx context.Context, ref *provider.Reference, lo
|
||||
// versions were not.
|
||||
// We will live with that compromise since this storage driver will be
|
||||
// deprecated soon.
|
||||
func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (err error) {
|
||||
func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (_ *storage.DeleteResult, err error) {
|
||||
var ip string
|
||||
if ip, err = fs.resolve(ctx, ref); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
}
|
||||
|
||||
// check permissions
|
||||
if perm, err := fs.readPermissions(ctx, ip); err == nil {
|
||||
if !perm.Delete {
|
||||
return errtypes.PermissionDenied("")
|
||||
return nil, errtypes.PermissionDenied("")
|
||||
}
|
||||
} else {
|
||||
if isNotFound(err) {
|
||||
return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
}
|
||||
|
||||
_, err = os.Stat(ip)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.NotFound(fs.toStoragePath(ctx, ip))
|
||||
return nil, errtypes.NotFound(fs.toStoragePath(ctx, ip))
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error stating "+ip)
|
||||
return nil, errors.Wrap(err, "owncloudsql: error stating "+ip)
|
||||
}
|
||||
|
||||
// Delete file into the owner's trash, not the user's (in case of shares)
|
||||
rp, err := fs.getRecyclePathForUser(fs.getOwner(ip))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving recycle path")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving recycle path")
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(rp, 0700); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error creating trashbin dir "+rp)
|
||||
return nil, errors.Wrap(err, "owncloudsql: error creating trashbin dir "+rp)
|
||||
}
|
||||
|
||||
// ip is the path on disk ... we need only the path relative to root
|
||||
@@ -1207,9 +1211,9 @@ func (fs *owncloudsqlfs) Delete(ctx context.Context, ref *provider.Reference) (e
|
||||
|
||||
err = fs.trash(ctx, ip, rp, origin)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "owncloudsql: error deleting file %s", ip)
|
||||
return nil, errors.Wrapf(err, "owncloudsql: error deleting file %s", ip)
|
||||
}
|
||||
return nil
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) trash(ctx context.Context, ip string, rp string, origin string) error {
|
||||
@@ -1295,51 +1299,51 @@ func (fs *owncloudsqlfs) trashVersions(ctx context.Context, ip string, origin st
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (err error) {
|
||||
var oldIP string
|
||||
if oldIP, err = fs.resolve(ctx, oldRef); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
func (fs *owncloudsqlfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
oldIP, err := fs.resolve(ctx, oldRef)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
}
|
||||
|
||||
// check permissions
|
||||
if perm, err := fs.readPermissions(ctx, oldIP); err == nil {
|
||||
if !perm.Move { // TODO add dedicated permission?
|
||||
return errtypes.PermissionDenied("")
|
||||
return nil, errtypes.PermissionDenied("")
|
||||
}
|
||||
} else {
|
||||
if isNotFound(err) {
|
||||
return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(oldIP)))
|
||||
return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(oldIP)))
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
}
|
||||
|
||||
var newIP string
|
||||
if newIP, err = fs.resolve(ctx, newRef); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
newIP, err := fs.resolve(ctx, newRef)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
}
|
||||
|
||||
// TODO check target permissions ... if it exists
|
||||
storage, err := fs.getStorage(ctx, oldIP)
|
||||
stor, err := fs.getStorage(ctx, oldIP)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
err = fs.filecache.Move(ctx, storage, fs.toDatabasePath(oldIP), fs.toDatabasePath(newIP))
|
||||
err = fs.filecache.Move(ctx, stor, fs.toDatabasePath(oldIP), fs.toDatabasePath(newIP))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if err = os.Rename(oldIP, newIP); err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error moving "+oldIP+" to "+newIP)
|
||||
return nil, errors.Wrap(err, "owncloudsql: error moving "+oldIP+" to "+newIP)
|
||||
}
|
||||
|
||||
if err := fs.propagate(ctx, newIP); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if filepath.Dir(newIP) != filepath.Dir(oldIP) {
|
||||
if err := fs.propagate(ctx, filepath.Dir(oldIP)); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) (*provider.ResourceInfo, error) {
|
||||
@@ -1657,22 +1661,22 @@ func (fs *owncloudsqlfs) DownloadRevision(ctx context.Context, ref *provider.Ref
|
||||
return nil, nil, errtypes.NotSupported("download revision")
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
ip, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving reference")
|
||||
}
|
||||
|
||||
// check permissions
|
||||
if perm, err := fs.readPermissions(ctx, ip); err == nil {
|
||||
if !perm.RestoreFileVersion {
|
||||
return errtypes.PermissionDenied("")
|
||||
return nil, errtypes.PermissionDenied("")
|
||||
}
|
||||
} else {
|
||||
if isNotFound(err) {
|
||||
return errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
return nil, errtypes.NotFound(fs.toStoragePath(ctx, filepath.Dir(ip)))
|
||||
}
|
||||
return errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error reading permissions")
|
||||
}
|
||||
|
||||
vp := fs.getVersionsPath(ctx, ip)
|
||||
@@ -1681,34 +1685,34 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe
|
||||
// check revision exists
|
||||
rs, err := os.Stat(rp)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !rs.Mode().IsRegular() {
|
||||
return fmt.Errorf("%s is not a regular file", rp)
|
||||
return nil, fmt.Errorf("%s is not a regular file", rp)
|
||||
}
|
||||
|
||||
source, err := os.Open(rp)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer source.Close()
|
||||
|
||||
// destination should be available, otherwise we could not have navigated to its revisions
|
||||
if err := fs.archiveRevision(ctx, fs.getVersionsPath(ctx, ip), ip); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
destination, err := os.Create(ip)
|
||||
if err != nil {
|
||||
// TODO(jfd) bring back revision in case sth goes wrong?
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer destination.Close()
|
||||
|
||||
_, err = io.Copy(destination, source)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sha1h, md5h, adler32h, err := fs.HashFile(ip)
|
||||
@@ -1717,7 +1721,7 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe
|
||||
}
|
||||
fi, err := os.Stat(ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
mtime := time.Now().Unix()
|
||||
data := map[string]interface{}{
|
||||
@@ -1731,15 +1735,18 @@ func (fs *owncloudsqlfs) RestoreRevision(ctx context.Context, ref *provider.Refe
|
||||
}
|
||||
storageID, err := fs.getStorage(ctx, ip)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
_, err = fs.filecache.InsertOrUpdate(ctx, storageID, data, false)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO(jfd) bring back revision in case sth goes wrong?
|
||||
return fs.propagate(ctx, ip)
|
||||
if err := fs.propagate(ctx, ip); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -1902,18 +1909,18 @@ func (fs *owncloudsqlfs) ListRecycle(ctx context.Context, ref *provider.Referenc
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
base, ttime, err := splitTrashKey(key)
|
||||
if err != nil {
|
||||
log.Error().Str("path", key).Msg("invalid trash item key")
|
||||
return fmt.Errorf("invalid trash item suffix")
|
||||
return nil, fmt.Errorf("invalid trash item suffix")
|
||||
}
|
||||
|
||||
recyclePath, err := fs.getRecyclePath(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "owncloudsql: error resolving recycle path")
|
||||
return nil, errors.Wrap(err, "owncloudsql: error resolving recycle path")
|
||||
}
|
||||
src := filepath.Join(recyclePath, filepath.Clean(key))
|
||||
|
||||
@@ -1923,7 +1930,7 @@ func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.R
|
||||
if err != nil {
|
||||
log := appctx.GetLogger(ctx)
|
||||
log.Error().Err(err).Str("path", key).Msg("could not get trash item")
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
restoreRef.Path = filepath.Join(item.Path, item.Name)
|
||||
}
|
||||
@@ -1932,27 +1939,30 @@ func (fs *owncloudsqlfs) RestoreRecycleItem(ctx context.Context, ref *provider.R
|
||||
// move back to original location
|
||||
if err := os.Rename(src, tgt); err != nil {
|
||||
log.Error().Err(err).Str("key", key).Str("restorePath", restoreRef.Path).Str("src", src).Str("tgt", tgt).Msg("could not restore item")
|
||||
return errors.Wrap(err, "owncloudsql: could not restore item")
|
||||
return nil, errors.Wrap(err, "owncloudsql: could not restore item")
|
||||
}
|
||||
|
||||
storage, err := fs.getStorage(ctx, src)
|
||||
storageID, err := fs.getStorage(ctx, src)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
err = fs.filecache.Move(ctx, storage, fs.toDatabasePath(src), fs.toDatabasePath(tgt))
|
||||
err = fs.filecache.Move(ctx, storageID, fs.toDatabasePath(src), fs.toDatabasePath(tgt))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
err = fs.filecache.DeleteRecycleItem(ctx, ctxpkg.ContextMustGetUser(ctx).Username, base, ttime)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
err = fs.RestoreRecycleItemVersions(ctx, key, tgt)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, tgt)
|
||||
if err := fs.propagate(ctx, tgt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) RestoreRecycleItemVersions(ctx context.Context, key, target string) error {
|
||||
|
||||
+3
-2
@@ -29,6 +29,7 @@ import (
|
||||
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/owncloudsql/filecache"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
@@ -99,8 +100,8 @@ func (fs *owncloudsqlfs) UpdateStorageSpace(ctx context.Context, req *provider.U
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (fs *owncloudsqlfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("delete storage space")
|
||||
func (fs *owncloudsqlfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("delete storage space")
|
||||
}
|
||||
|
||||
// Note: currently unused but will be used later
|
||||
|
||||
+12
-11
@@ -226,10 +226,10 @@ func (tb *Trashbin) ListRecycle(ctx context.Context, ref *provider.Reference, ke
|
||||
}
|
||||
|
||||
// RestoreRecycleItem restores the specified item
|
||||
func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
n, err := tb.lu.NodeFromResource(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
trashRoot := trashRootForNode(n)
|
||||
@@ -237,33 +237,33 @@ func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Refere
|
||||
|
||||
restoreBaseNode, err := tb.lu.NodeFromID(ctx, restoreRef.GetResourceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
restorePath := filepath.Join(restoreBaseNode.InternalPath(), restoreRef.GetPath())
|
||||
|
||||
id, err := tb.lu.MetadataBackend().Get(ctx, trashPath, prefixes.IDAttr)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// update parent id in case it was restored to a different location
|
||||
parentID, err := tb.lu.MetadataBackend().Get(ctx, filepath.Dir(restorePath), prefixes.IDAttr)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if len(parentID) == 0 {
|
||||
return fmt.Errorf("trashbin: parent id not found for %s", restorePath)
|
||||
return nil, fmt.Errorf("trashbin: parent id not found for %s", restorePath)
|
||||
}
|
||||
|
||||
err = tb.lu.MetadataBackend().Set(ctx, trashPath, prefixes.ParentidAttr, parentID)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// restore the item
|
||||
err = os.Rename(trashPath, restorePath)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if err := tb.lu.CacheID(ctx, n.SpaceID, string(id), restorePath); err != nil {
|
||||
tb.log.Error().Err(err).Str("spaceID", n.SpaceID).Str("id", string(id)).Str("path", restorePath).Msg("trashbin: error caching id")
|
||||
@@ -271,10 +271,11 @@ func (tb *Trashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Refere
|
||||
|
||||
// cleanup trash info
|
||||
if relativePath == "." || relativePath == "/" {
|
||||
return os.Remove(filepath.Join(trashRoot, "info", key+".trashinfo"))
|
||||
} else {
|
||||
return nil
|
||||
if err := os.Remove(filepath.Join(trashRoot, "info", key+".trashinfo")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{SpaceOwner: n.SpaceOwnerOrManager(ctx)}, nil
|
||||
}
|
||||
|
||||
// PurgeRecycleItem purges the specified item, all its children and all their revisions
|
||||
|
||||
+35
-35
@@ -36,13 +36,13 @@ import (
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3manager"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/mime"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
@@ -288,8 +288,8 @@ func (fs *s3FS) GetLock(ctx context.Context, ref *provider.Reference) (*provider
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *s3FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *s3FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -298,8 +298,8 @@ func (fs *s3FS) RefreshLock(ctx context.Context, ref *provider.Reference, lock *
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *s3FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *s3FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
func (fs *s3FS) CreateReference(ctx context.Context, path string, targetURI *url.URL) error {
|
||||
@@ -315,12 +315,12 @@ func (fs *s3FS) CreateHome(ctx context.Context) error {
|
||||
return errtypes.NotSupported("s3fs: not supported")
|
||||
}
|
||||
|
||||
func (fs *s3FS) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *s3FS) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
fn, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fn = fs.addRoot(fn) + "/" // append / to indicate folder // TODO only if fn does not end in /
|
||||
@@ -337,28 +337,28 @@ func (fs *s3FS) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
log.Error().Err(err)
|
||||
if aerr, ok := err.(awserr.Error); ok {
|
||||
if aerr.Code() == s3.ErrCodeNoSuchBucket {
|
||||
return errtypes.NotFound(ref.Path)
|
||||
return nil, errtypes.NotFound(ref.Path)
|
||||
}
|
||||
}
|
||||
// FIXME we also need already exists error, webdav expects 405 MethodNotAllowed
|
||||
return errors.Wrap(err, "s3fs: error creating dir "+ref.Path)
|
||||
return nil, errors.Wrap(err, "s3fs: error creating dir "+ref.Path)
|
||||
}
|
||||
|
||||
log.Debug().Interface("result", result) // todo cache etag?
|
||||
return nil
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *s3FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
return fmt.Errorf("unimplemented: TouchFile")
|
||||
func (fs *s3FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
return nil, fmt.Errorf("unimplemented: TouchFile")
|
||||
}
|
||||
|
||||
func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
fn, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error resolving ref")
|
||||
return nil, errors.Wrap(err, "error resolving ref")
|
||||
}
|
||||
|
||||
// first we need to find out if fn is a dir or a file
|
||||
@@ -373,7 +373,7 @@ func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
switch aerr.Code() {
|
||||
case s3.ErrCodeNoSuchBucket:
|
||||
case s3.ErrCodeNoSuchKey:
|
||||
return errtypes.NotFound(fn)
|
||||
return nil, errtypes.NotFound(fn)
|
||||
}
|
||||
}
|
||||
// it might be a directory, so we can batch delete the prefix + /
|
||||
@@ -383,10 +383,10 @@ func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
})
|
||||
batcher := s3manager.NewBatchDeleteWithClient(fs.client)
|
||||
if err := batcher.Delete(aws.BackgroundContext(), iter); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
// ok, we are done
|
||||
return nil
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
// we found an object, let's get rid of it
|
||||
@@ -400,14 +400,14 @@ func (fs *s3FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
switch aerr.Code() {
|
||||
case s3.ErrCodeNoSuchBucket:
|
||||
case s3.ErrCodeNoSuchKey:
|
||||
return errtypes.NotFound(fn)
|
||||
return nil, errtypes.NotFound(fn)
|
||||
}
|
||||
}
|
||||
return errors.Wrap(err, "s3fs: error deleting "+fn)
|
||||
return nil, errors.Wrap(err, "s3fs: error deleting "+fn)
|
||||
}
|
||||
|
||||
log.Debug().Interface("result", result)
|
||||
return nil
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
// CreateStorageSpace creates a storage space
|
||||
@@ -449,17 +449,17 @@ func (fs *s3FS) moveObject(ctx context.Context, oldKey string, newKey string) er
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
fn, err := fs.resolve(ctx, oldRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error resolving ref")
|
||||
return nil, errors.Wrap(err, "error resolving ref")
|
||||
}
|
||||
|
||||
newName, err := fs.resolve(ctx, newRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "error resolving ref")
|
||||
return nil, errors.Wrap(err, "error resolving ref")
|
||||
}
|
||||
|
||||
// first we need to find out if fn is a dir or a file
|
||||
@@ -474,7 +474,7 @@ func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) er
|
||||
switch aerr.Code() {
|
||||
case s3.ErrCodeNoSuchBucket:
|
||||
case s3.ErrCodeNoSuchKey:
|
||||
return errtypes.NotFound(fn)
|
||||
return nil, errtypes.NotFound(fn)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,7 +488,7 @@ func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) er
|
||||
for isTruncated {
|
||||
output, err := fs.client.ListObjectsV2(input)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "s3FS: error listing "+fn)
|
||||
return nil, errors.Wrap(err, "s3FS: error listing "+fn)
|
||||
}
|
||||
|
||||
for _, o := range output.Contents {
|
||||
@@ -499,7 +499,7 @@ func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) er
|
||||
|
||||
err := fs.moveObject(ctx, *o.Key, strings.Replace(*o.Key, fn+"/", newName+"/", 1))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,15 +507,15 @@ func (fs *s3FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) er
|
||||
isTruncated = *output.IsTruncated
|
||||
}
|
||||
// ok, we are done
|
||||
return nil
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
// move single object
|
||||
err = fs.moveObject(ctx, fn, newName)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return nil
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *s3FS) GetMD(ctx context.Context, ref *provider.Reference, mdKeys []string, fieldMask []string) (*provider.ResourceInfo, error) {
|
||||
@@ -663,8 +663,8 @@ func (fs *s3FS) DownloadRevision(ctx context.Context, ref *provider.Reference, r
|
||||
return nil, nil, errtypes.NotSupported("download revision")
|
||||
}
|
||||
|
||||
func (fs *s3FS) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
return errtypes.NotSupported("restore revision")
|
||||
func (fs *s3FS) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
return nil, errtypes.NotSupported("restore revision")
|
||||
}
|
||||
|
||||
func (fs *s3FS) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -679,8 +679,8 @@ func (fs *s3FS) ListRecycle(ctx context.Context, ref *provider.Reference, key, r
|
||||
return nil, errtypes.NotSupported("list recycle")
|
||||
}
|
||||
|
||||
func (fs *s3FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
return errtypes.NotSupported("restore recycle")
|
||||
func (fs *s3FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return nil, errtypes.NotSupported("restore recycle")
|
||||
}
|
||||
|
||||
func (fs *s3FS) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) {
|
||||
@@ -693,6 +693,6 @@ func (fs *s3FS) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStor
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (fs *s3FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("delete storage space")
|
||||
func (fs *s3FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("delete storage space")
|
||||
}
|
||||
+74
-11
@@ -23,11 +23,51 @@ import (
|
||||
"io"
|
||||
"net/url"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
registry "github.com/cs3org/go-cs3apis/cs3/storage/registry/v1beta1"
|
||||
tusd "github.com/tus/tusd/v2/pkg/handler"
|
||||
)
|
||||
|
||||
type MoveResult struct {
|
||||
SpaceOwner *user.UserId
|
||||
OldReference *provider.Reference
|
||||
NewReference *provider.Reference
|
||||
}
|
||||
|
||||
type CreateDirResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
ResourceID *provider.ResourceId
|
||||
}
|
||||
|
||||
type TouchFileResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
ResourceID *provider.ResourceId
|
||||
}
|
||||
|
||||
type RestoreRevisionResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
}
|
||||
|
||||
type RestoreRecycleItemResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
}
|
||||
|
||||
type SetLockResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
}
|
||||
|
||||
type UnlockResult struct {
|
||||
SpaceOwner *userpb.UserId
|
||||
SpaceID string
|
||||
}
|
||||
|
||||
// FS is the interface to implement access to the storage.
|
||||
type FS interface {
|
||||
// Minimal set for a readonly storage driver
|
||||
@@ -59,16 +99,17 @@ type FS interface {
|
||||
// CreateReference creates a resource of type reference
|
||||
CreateReference(ctx context.Context, path string, targetURI *url.URL) error
|
||||
// CreateDir creates a resource of type container
|
||||
CreateDir(ctx context.Context, ref *provider.Reference) error
|
||||
CreateDir(ctx context.Context, ref *provider.Reference) (*CreateDirResult, error)
|
||||
// TouchFile sets the mtime of a resource, creating an empty file if it does not exist
|
||||
// FIXME the markprocessing flag is an implementation detail of decomposedfs, remove it from the function
|
||||
// FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string
|
||||
TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error
|
||||
TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*TouchFileResult, error)
|
||||
// Delete deletes a resource.
|
||||
// If the storage driver supports a recycle bin it should moves it to the recycle bin
|
||||
Delete(ctx context.Context, ref *provider.Reference) error
|
||||
// If the storage driver supports a recycle bin it should move it to the recycle bin
|
||||
// On success, returns a DeleteResult used by the wrapper to publish ItemTrashed.
|
||||
Delete(ctx context.Context, ref *provider.Reference) (*DeleteResult, error)
|
||||
// Move changes the path of a resource
|
||||
Move(ctx context.Context, oldRef, newRef *provider.Reference) error
|
||||
Move(ctx context.Context, oldRef, newRef *provider.Reference) (*MoveResult, error)
|
||||
// InitiateUpload returns a list of protocols with urls that can be used to append bytes to a new upload session
|
||||
InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error)
|
||||
// Upload creates or updates a resource of type file with a new revision
|
||||
@@ -81,7 +122,7 @@ type FS interface {
|
||||
// DownloadRevision downloads a revision
|
||||
DownloadRevision(ctx context.Context, ref *provider.Reference, key string, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error)
|
||||
// RestoreRevision restores a revision
|
||||
RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error
|
||||
RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*RestoreRevisionResult, error)
|
||||
|
||||
// Recyce bin
|
||||
|
||||
@@ -89,7 +130,7 @@ type FS interface {
|
||||
ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error)
|
||||
// RestoreRecycleItem restores an item from the recyle bin
|
||||
// if restoreRef is nil the resource should be restored at the original path
|
||||
RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error
|
||||
RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*RestoreRecycleItemResult, error)
|
||||
// PurgeRecycleItem removes a resource from the recycle bin
|
||||
PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error
|
||||
// EmptyRecycle removes all resource from the recycle bin
|
||||
@@ -121,11 +162,11 @@ type FS interface {
|
||||
// GetLock returns an existing lock on the given reference
|
||||
GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error)
|
||||
// SetLock puts a lock on the given reference
|
||||
SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error
|
||||
SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*SetLockResult, error)
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
RefreshLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock, existingLockID string) error
|
||||
// Unlock removes an existing lock from the given reference
|
||||
Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error
|
||||
Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*UnlockResult, error)
|
||||
|
||||
// Spaces
|
||||
|
||||
@@ -133,8 +174,10 @@ type FS interface {
|
||||
CreateStorageSpace(ctx context.Context, req *provider.CreateStorageSpaceRequest) (*provider.CreateStorageSpaceResponse, error)
|
||||
// UpdateStorageSpace updates a storage space
|
||||
UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorageSpaceRequest) (*provider.UpdateStorageSpaceResponse, error)
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error
|
||||
// DeleteStorageSpace deletes a storage space.
|
||||
// On a successful delete (purge), returns a DeleteStorageSpaceResult used by
|
||||
// the wrapper to publish SpaceDeleted. SpaceDisabled does not need this data.
|
||||
DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*DeleteStorageSpaceResult, error)
|
||||
|
||||
// CreateHome creates a users home
|
||||
// Deprecated: use CreateStorageSpace with type personal
|
||||
@@ -144,6 +187,26 @@ type FS interface {
|
||||
GetHome(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
// DeleteResult is returned by FS.Delete on success. It carries the data the
|
||||
// storageprovider wrapper needs to publish the ItemTrashed event.
|
||||
type DeleteResult struct {
|
||||
// SpaceOwner is the owner of the space the deleted resource belonged to.
|
||||
SpaceOwner *userpb.UserId
|
||||
// ResourceId is the stable identifier of the deleted resource, used as ItemTrashed.ID in the published event.
|
||||
ResourceId *provider.ResourceId
|
||||
}
|
||||
|
||||
// DeleteStorageSpaceResult is returned by FS.DeleteStorageSpace on a successful
|
||||
// purge. It carries the data the storageprovider wrapper needs to publish the
|
||||
// SpaceDeleted event. The SpaceDisabled flow does not consume it.
|
||||
type DeleteStorageSpaceResult struct {
|
||||
// SpaceName is the name of the space at the time of deletion.
|
||||
SpaceName string
|
||||
// FinalMembers is the grant map of the space at the time of deletion,
|
||||
// keyed by user/group opaque id.
|
||||
FinalMembers map[string]provider.ResourcePermissions
|
||||
}
|
||||
|
||||
// UnscopeFunc is a function that unscopes a user
|
||||
type UnscopeFunc func()
|
||||
|
||||
|
||||
Generated
Vendored
+110
-74
@@ -42,6 +42,7 @@ import (
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
@@ -744,13 +745,13 @@ func (fs *Decomposedfs) GetPathByID(ctx context.Context, id *provider.ResourceId
|
||||
}
|
||||
|
||||
// CreateDir creates the specified directory
|
||||
func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (err error) {
|
||||
func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference) (_ *storage.CreateDirResult, err error) {
|
||||
ctx, span := tracer.Start(ctx, "CreateDir")
|
||||
defer span.End()
|
||||
|
||||
name := path.Base(ref.Path)
|
||||
if name == "" || name == "." || name == "/" {
|
||||
return errtypes.BadRequest("Invalid path: " + ref.Path)
|
||||
return nil, errtypes.BadRequest("Invalid path: " + ref.Path)
|
||||
}
|
||||
|
||||
parentRef := &provider.Reference{
|
||||
@@ -762,52 +763,51 @@ func (fs *Decomposedfs) CreateDir(ctx context.Context, ref *provider.Reference)
|
||||
var n *node.Node
|
||||
if n, err = fs.lu.NodeFromResource(ctx, parentRef); err != nil {
|
||||
if e, ok := err.(errtypes.NotFound); ok {
|
||||
return errtypes.PreconditionFailed(e.Error())
|
||||
return nil, errtypes.PreconditionFailed(e.Error())
|
||||
}
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
// TODO check if user has access to root / space
|
||||
if !n.Exists {
|
||||
return errtypes.PreconditionFailed(parentRef.Path)
|
||||
return nil, errtypes.PreconditionFailed(parentRef.Path)
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, n)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.CreateContainer:
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
spaceOwner := n.SpaceOwnerOrManager(ctx)
|
||||
|
||||
// check lock
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// verify child does not exist, yet
|
||||
if n, err = n.Child(ctx, name); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
if n.Exists {
|
||||
return errtypes.AlreadyExists(ref.Path)
|
||||
return nil, errtypes.AlreadyExists(ref.Path)
|
||||
}
|
||||
|
||||
if err = fs.tp.CreateDir(ctx, n); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return
|
||||
return &storage.CreateDirResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID, ResourceID: &provider.ResourceId{OpaqueId: n.ID, SpaceId: n.SpaceID}}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
ctx, span := tracer.Start(ctx, "TouchFile")
|
||||
defer span.End()
|
||||
parentRef := &provider.Reference{
|
||||
@@ -818,37 +818,39 @@ func (fs *Decomposedfs) TouchFile(ctx context.Context, ref *provider.Reference,
|
||||
// verify parent exists
|
||||
parent, err := fs.lu.NodeFromResource(ctx, parentRef)
|
||||
if err != nil {
|
||||
return errtypes.InternalError(err.Error())
|
||||
return nil, errtypes.InternalError(err.Error())
|
||||
}
|
||||
if !parent.Exists {
|
||||
return errtypes.NotFound(parentRef.Path)
|
||||
return nil, errtypes.NotFound(parentRef.Path)
|
||||
}
|
||||
|
||||
n, err := fs.lu.NodeFromResource(ctx, ref)
|
||||
if err != nil {
|
||||
return errtypes.InternalError(err.Error())
|
||||
return nil, errtypes.InternalError(err.Error())
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, n)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.InitiateFileUpload:
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
spaceOwner := n.SpaceOwnerOrManager(ctx)
|
||||
|
||||
// check lock
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
return fs.tp.TouchFile(ctx, n, markprocessing, mtime)
|
||||
if err := fs.tp.TouchFile(ctx, n, markprocessing, mtime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.TouchFileResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID, ResourceID: &provider.ResourceId{OpaqueId: n.ID, SpaceId: n.SpaceID}}, nil
|
||||
}
|
||||
|
||||
// CreateReference creates a reference as a node folder with the target stored in extended attributes
|
||||
@@ -861,72 +863,86 @@ func (fs *Decomposedfs) CreateReference(ctx context.Context, p string, targetURI
|
||||
}
|
||||
|
||||
// Move moves a resource from one reference to another
|
||||
func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (err error) {
|
||||
func (fs *Decomposedfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
ctx, span := tracer.Start(ctx, "Move")
|
||||
defer span.End()
|
||||
var oldNode, newNode *node.Node
|
||||
var err error
|
||||
if oldNode, err = fs.lu.NodeFromResource(ctx, oldRef); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !oldNode.Exists {
|
||||
err = errtypes.NotFound(filepath.Join(oldNode.ParentID, oldNode.Name))
|
||||
return
|
||||
return nil, errtypes.NotFound(filepath.Join(oldNode.ParentID, oldNode.Name))
|
||||
}
|
||||
|
||||
orp, err := fs.p.AssemblePermissions(ctx, oldNode)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !orp.Move:
|
||||
f, _ := storagespace.FormatReference(oldRef)
|
||||
if orp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
if newNode, err = fs.lu.NodeFromResource(ctx, newRef); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
if newNode.Exists {
|
||||
err = errtypes.AlreadyExists(filepath.Join(newNode.ParentID, newNode.Name))
|
||||
return
|
||||
return nil, errtypes.AlreadyExists(filepath.Join(newNode.ParentID, newNode.Name))
|
||||
}
|
||||
|
||||
nrp, err := fs.p.AssemblePermissions(ctx, newNode)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case oldNode.IsDir(ctx) && !nrp.CreateContainer:
|
||||
f, _ := storagespace.FormatReference(newRef)
|
||||
if nrp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
case !oldNode.IsDir(ctx) && !nrp.InitiateFileUpload:
|
||||
f, _ := storagespace.FormatReference(newRef)
|
||||
if nrp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, newNode.SpaceOwnerOrManager(ctx))
|
||||
storagespace.ContextSetSpaceOwner(ctx, newNode.SpaceOwnerOrManager(ctx))
|
||||
|
||||
// check lock on source
|
||||
if err := oldNode.CheckLock(ctx); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := fs.tp.Move(ctx, oldNode, newNode); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fs.publishEvent(ctx, fs.moveEvent(ctx, oldRef, newRef, oldNode, newNode, orp, nrp))
|
||||
|
||||
return nil
|
||||
log := appctx.GetLogger(ctx)
|
||||
newResolved := newRef
|
||||
if nref, err := fs.refFromNode(ctx, newNode, newRef.GetResourceId().GetStorageId(), nrp); err != nil {
|
||||
log.Error().Err(err).Str("ref", newRef.String()).Msg("move: failed to resolve new reference")
|
||||
} else {
|
||||
newResolved = nref
|
||||
}
|
||||
oldResolved := oldRef
|
||||
if oref, err := fs.refFromNode(ctx, oldNode, oldRef.GetResourceId().GetStorageId(), orp); err != nil {
|
||||
log.Error().Err(err).Str("ref", oldRef.String()).Msg("move: failed to resolve old reference")
|
||||
} else {
|
||||
oldResolved = oref
|
||||
}
|
||||
return &storage.MoveResult{
|
||||
SpaceOwner: newNode.SpaceOwnerOrManager(ctx),
|
||||
OldReference: oldResolved,
|
||||
NewReference: newResolved,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetMD returns the metadata for the specified resource
|
||||
@@ -1068,37 +1084,47 @@ func (fs *Decomposedfs) ListFolder(ctx context.Context, ref *provider.Reference,
|
||||
}
|
||||
|
||||
// Delete deletes the specified resource
|
||||
func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (err error) {
|
||||
func (fs *Decomposedfs) Delete(ctx context.Context, ref *provider.Reference) (dr *storage.DeleteResult, err error) {
|
||||
ctx, span := tracer.Start(ctx, "Delete")
|
||||
defer span.End()
|
||||
var node *node.Node
|
||||
if node, err = fs.lu.NodeFromResource(ctx, ref); err != nil {
|
||||
return
|
||||
return nil, err
|
||||
}
|
||||
if !node.Exists {
|
||||
return errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
}
|
||||
|
||||
if node.IsProcessing(ctx) {
|
||||
return nil, errtypes.TooEarly("file is processing")
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, node)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.Delete:
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, node.SpaceOwnerOrManager(ctx))
|
||||
|
||||
if err := node.CheckLock(ctx); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.tp.Delete(ctx, node)
|
||||
if err := fs.tp.Delete(ctx, node); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{
|
||||
SpaceOwner: node.SpaceOwnerOrManager(ctx),
|
||||
ResourceId: &provider.ResourceId{
|
||||
SpaceId: node.SpaceID,
|
||||
OpaqueId: node.ID,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Download returns a reader to the specified resource
|
||||
@@ -1177,31 +1203,36 @@ func (fs *Decomposedfs) GetLock(ctx context.Context, ref *provider.Reference) (*
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (fs *Decomposedfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
ctx, span := tracer.Start(ctx, "SetLock")
|
||||
defer span.End()
|
||||
node, err := fs.lu.NodeFromResource(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Decomposedfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "Decomposedfs: error resolving ref")
|
||||
}
|
||||
|
||||
if !node.Exists {
|
||||
return errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, node)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.InitiateFileUpload:
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
return node.SetLock(ctx, lock)
|
||||
spaceOwner := node.SpaceOwnerOrManager(ctx)
|
||||
|
||||
if err := node.SetLock(ctx, lock); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.SetLockResult{SpaceOwner: spaceOwner, SpaceID: node.SpaceID}, nil
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -1237,41 +1268,46 @@ func (fs *Decomposedfs) RefreshLock(ctx context.Context, ref *provider.Reference
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (fs *Decomposedfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
ctx, span := tracer.Start(ctx, "Unlock")
|
||||
defer span.End()
|
||||
if lock.LockId == "" {
|
||||
return errtypes.BadRequest("missing lockid")
|
||||
return nil, errtypes.BadRequest("missing lockid")
|
||||
}
|
||||
|
||||
node, err := fs.lu.NodeFromResource(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Decomposedfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "Decomposedfs: error resolving ref")
|
||||
}
|
||||
|
||||
if !node.Exists {
|
||||
return errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
return nil, errtypes.NotFound(filepath.Join(node.ParentID, node.Name))
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, node)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.InitiateFileUpload: // TODO do we need a dedicated permission?
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
return node.Unlock(ctx, lock)
|
||||
spaceOwner := node.SpaceOwnerOrManager(ctx)
|
||||
|
||||
if err := node.Unlock(ctx, lock); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.UnlockResult{SpaceOwner: spaceOwner, SpaceID: node.SpaceID}, nil
|
||||
}
|
||||
|
||||
func (fs *Decomposedfs) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) {
|
||||
return fs.trashbin.ListRecycle(ctx, ref, key, relativePath)
|
||||
}
|
||||
func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (fs *Decomposedfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
return fs.trashbin.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef)
|
||||
}
|
||||
func (fs *Decomposedfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package decomposedfs
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
)
|
||||
|
||||
func (fs *Decomposedfs) publishEvent(ctx context.Context, evf func() (any, error)) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
if fs.stream == nil {
|
||||
log.Error().Msg("Failed to publish event, stream is undefined")
|
||||
return
|
||||
}
|
||||
ev, err := evf()
|
||||
if err != nil || ev == nil {
|
||||
log.Error().Err(err).Msg("Failed to crete the event")
|
||||
return
|
||||
}
|
||||
if err := events.Publish(ctx, fs.stream, ev); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to publish event")
|
||||
}
|
||||
}
|
||||
|
||||
func (fs *Decomposedfs) moveEvent(ctx context.Context, oldRef, newRef *provider.Reference, oldNode, newNode *node.Node, orp, nrp *provider.ResourcePermissions) func() (any, error) {
|
||||
return func() (any, error) {
|
||||
executant, _ := revactx.ContextGetUser(ctx)
|
||||
ev := events.ItemMoved{
|
||||
SpaceOwner: newNode.Owner(),
|
||||
Executant: executant.GetId(),
|
||||
Ref: newRef,
|
||||
OldReference: oldRef,
|
||||
Timestamp: utils.TSNow(),
|
||||
ImpersonatingUser: extractImpersonator(executant),
|
||||
}
|
||||
log := appctx.GetLogger(ctx)
|
||||
if nref, err := fs.refFromNode(ctx, newNode, newRef.GetResourceId().GetStorageId(), nrp); err == nil {
|
||||
ev.Ref = nref
|
||||
} else {
|
||||
log.Error().Err(err).Msg("Failed to get destination reference")
|
||||
}
|
||||
|
||||
if oref, err := fs.refFromNode(ctx, oldNode, oldRef.GetResourceId().GetStorageId(), orp); err == nil {
|
||||
ev.OldReference = oref
|
||||
} else {
|
||||
log.Error().Err(err).Msg("Failed to get source reference")
|
||||
}
|
||||
|
||||
return ev, nil
|
||||
}
|
||||
}
|
||||
|
||||
func extractImpersonator(u *user.User) *user.User {
|
||||
var impersonator user.User
|
||||
if err := utils.ReadJSONFromOpaque(u.Opaque, "impersonating-user", &impersonator); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &impersonator
|
||||
}
|
||||
+2
-2
@@ -64,7 +64,7 @@ func (fs *Decomposedfs) SetArbitraryMetadata(ctx context.Context, ref *provider.
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
|
||||
// check lock
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
@@ -159,7 +159,7 @@ func (fs *Decomposedfs) UnsetArbitraryMetadata(ctx context.Context, ref *provide
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
|
||||
// check lock
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
|
||||
+15
-15
@@ -37,7 +37,6 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/lookup"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
)
|
||||
|
||||
type DecomposedfsTrashbin struct {
|
||||
@@ -346,18 +345,18 @@ func (tb *DecomposedfsTrashbin) listTrashRoot(ctx context.Context, spaceID strin
|
||||
}
|
||||
|
||||
// RestoreRecycleItem restores the specified item
|
||||
func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
_, span := tracer.Start(ctx, "RestoreRecycleItem")
|
||||
defer span.End()
|
||||
if ref == nil {
|
||||
return errtypes.BadRequest("missing reference, needs a space id")
|
||||
return nil, errtypes.BadRequest("missing reference, needs a space id")
|
||||
}
|
||||
|
||||
var targetNode *node.Node
|
||||
if restoreRef != nil {
|
||||
tn, err := tb.fs.lu.NodeFromResource(ctx, restoreRef)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
targetNode = tn
|
||||
@@ -365,39 +364,40 @@ func (tb *DecomposedfsTrashbin) RestoreRecycleItem(ctx context.Context, ref *pro
|
||||
|
||||
rn, parent, restoreFunc, err := tb.fs.tp.RestoreRecycleItemFunc(ctx, ref.ResourceId.SpaceId, key, relativePath, targetNode)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check permissions of deleted node
|
||||
rp, err := tb.fs.p.AssembleTrashPermissions(ctx, rn)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.RestoreRecycleItem:
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(key)
|
||||
return nil, errtypes.PermissionDenied(key)
|
||||
}
|
||||
return errtypes.NotFound(key)
|
||||
return nil, errtypes.NotFound(key)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, rn.SpaceOwnerOrManager(ctx))
|
||||
spaceOwner := rn.SpaceOwnerOrManager(ctx)
|
||||
|
||||
// check we can write to the parent of the restore reference
|
||||
pp, err := tb.fs.p.AssemblePermissions(ctx, parent)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !pp.InitiateFileUpload:
|
||||
// share receiver cannot restore to a shared resource to which she does not have write permissions.
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(key)
|
||||
return nil, errtypes.PermissionDenied(key)
|
||||
}
|
||||
return errtypes.NotFound(key)
|
||||
return nil, errtypes.NotFound(key)
|
||||
}
|
||||
|
||||
// Run the restore func
|
||||
return restoreFunc()
|
||||
if err := restoreFunc(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{SpaceOwner: spaceOwner, SpaceID: rn.SpaceID}, nil
|
||||
}
|
||||
|
||||
// PurgeRecycleItem purges the specified item, all its children and all their revisions
|
||||
|
||||
+23
-20
@@ -32,6 +32,7 @@ import (
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
@@ -189,7 +190,7 @@ func (fs *Decomposedfs) DownloadRevision(ctx context.Context, ref *provider.Refe
|
||||
}
|
||||
|
||||
// RestoreRevision restores the specified revision of the resource
|
||||
func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (returnErr error) {
|
||||
func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (_ *storage.RestoreRevisionResult, returnErr error) {
|
||||
_, span := tracer.Start(ctx, "RestoreRevision")
|
||||
defer span.End()
|
||||
log := appctx.GetLogger(ctx)
|
||||
@@ -198,44 +199,43 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
kp := strings.SplitN(revisionKey, node.RevisionIDDelimiter, 2)
|
||||
if len(kp) != 2 {
|
||||
log.Error().Str("revisionKey", revisionKey).Msg("malformed revisionKey")
|
||||
return errtypes.NotFound(revisionKey)
|
||||
return nil, errtypes.NotFound(revisionKey)
|
||||
}
|
||||
|
||||
spaceID := ref.ResourceId.SpaceId
|
||||
// check if the node is available and has not been deleted
|
||||
n, err := node.ReadNode(ctx, fs.lu, spaceID, kp[0], false, nil, false)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if !n.Exists {
|
||||
err = errtypes.NotFound(filepath.Join(n.ParentID, n.Name))
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rp, err := fs.p.AssemblePermissions(ctx, n)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
return nil, err
|
||||
case !rp.RestoreFileVersion:
|
||||
f, _ := storagespace.FormatReference(ref)
|
||||
if rp.Stat {
|
||||
return errtypes.PermissionDenied(f)
|
||||
return nil, errtypes.PermissionDenied(f)
|
||||
}
|
||||
return errtypes.NotFound(f)
|
||||
return nil, errtypes.NotFound(f)
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
spaceOwner := n.SpaceOwnerOrManager(ctx)
|
||||
|
||||
// check lock
|
||||
if err := n.CheckLock(ctx); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// write lock node before copying metadata
|
||||
f, err := lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_RDWR|os.O_CREATE, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = f.Close()
|
||||
@@ -247,7 +247,7 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
mtime, err := n.GetMTime(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Interface("ref", ref).Str("originalnode", kp[0]).Str("revisionKey", revisionKey).Msg("cannot read mtime")
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// revisions are stored alongside the actual file, so a rename can be efficient and does not cross storage / partition boundaries
|
||||
@@ -255,7 +255,7 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
|
||||
// touch new revision
|
||||
if _, err := os.Create(newRevisionPath); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if returnErr != nil {
|
||||
@@ -277,12 +277,12 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
attributeName == prefixes.MTimeAttr // FIXME somewhere I mix up the revision time and the mtime, causing the restore to overwrite the other existing revisien
|
||||
}, f, true)
|
||||
if err != nil {
|
||||
return errtypes.InternalError("failed to copy blob xattrs to version node: " + err.Error())
|
||||
return nil, errtypes.InternalError("failed to copy blob xattrs to version node: " + err.Error())
|
||||
}
|
||||
|
||||
// remember mtime from node as new revision mtime
|
||||
if err = os.Chtimes(newRevisionPath, mtime, mtime); err != nil {
|
||||
return errtypes.InternalError("failed to change mtime of version node")
|
||||
return nil, errtypes.InternalError("failed to change mtime of version node")
|
||||
}
|
||||
|
||||
// update blob id in node
|
||||
@@ -296,7 +296,7 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
attributeName == prefixes.BlobsizeAttr
|
||||
}, false)
|
||||
if err != nil {
|
||||
return errtypes.InternalError("failed to copy blob xattrs to old revision to node: " + err.Error())
|
||||
return nil, errtypes.InternalError("failed to copy blob xattrs to old revision to node: " + err.Error())
|
||||
}
|
||||
// always set the node mtime to the current time
|
||||
err = fs.lu.MetadataBackend().SetMultiple(ctx, nodePath,
|
||||
@@ -305,12 +305,12 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
},
|
||||
false)
|
||||
if err != nil {
|
||||
return errtypes.InternalError("failed to set mtime attribute on node: " + err.Error())
|
||||
return nil, errtypes.InternalError("failed to set mtime attribute on node: " + err.Error())
|
||||
}
|
||||
|
||||
revisionSize, err := fs.lu.MetadataBackend().GetInt64(ctx, restoredRevisionPath, prefixes.BlobsizeAttr)
|
||||
if err != nil {
|
||||
return errtypes.InternalError("failed to read blob size xattr from old revision")
|
||||
return nil, errtypes.InternalError("failed to read blob size xattr from old revision")
|
||||
}
|
||||
|
||||
// drop old revision
|
||||
@@ -331,7 +331,10 @@ func (fs *Decomposedfs) RestoreRevision(ctx context.Context, ref *provider.Refer
|
||||
// revision 10, current 5 (restore a bigger blob) -> 10-5 = +5
|
||||
sizeDiff := revisionSize - n.Blobsize
|
||||
|
||||
return fs.tp.Propagate(ctx, n, sizeDiff)
|
||||
if err := fs.tp.Propagate(ctx, n, sizeDiff); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{SpaceOwner: spaceOwner, SpaceID: n.SpaceID}, nil
|
||||
}
|
||||
|
||||
// DeleteRevision deletes the specified revision of the resource
|
||||
@@ -385,7 +388,7 @@ func (fs *Decomposedfs) getRevisionNode(ctx context.Context, ref *provider.Refer
|
||||
}
|
||||
|
||||
// Set space owner in context
|
||||
storagespace.ContextSendSpaceOwnerID(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
storagespace.ContextSetSpaceOwner(ctx, n.SpaceOwnerOrManager(ctx))
|
||||
|
||||
return n, nil
|
||||
}
|
||||
+118
-15
@@ -43,6 +43,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
sdk "github.com/owncloud/reva/v2/pkg/sdk/common"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/lookup"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
|
||||
@@ -700,7 +701,7 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up
|
||||
},
|
||||
}
|
||||
// delete old image after new image was successfully set
|
||||
_ = fs.Delete(ctx, delRef)
|
||||
_, _ = fs.Delete(ctx, delRef)
|
||||
// silently ignore failed deletion
|
||||
}
|
||||
}
|
||||
@@ -724,7 +725,7 @@ func (fs *Decomposedfs) UpdateStorageSpace(ctx context.Context, req *provider.Up
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
opaque := req.Opaque
|
||||
var purge bool
|
||||
if opaque != nil {
|
||||
@@ -733,39 +734,49 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De
|
||||
|
||||
_, spaceID, _, err := storagespace.SplitID(req.Id.GetOpaqueId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
n, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, true, nil, false) // permission to read disabled space is checked later
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if !n.Exists {
|
||||
return nil, errtypes.NotFound(spaceID)
|
||||
}
|
||||
|
||||
st, err := n.SpaceRoot.XattrString(ctx, prefixes.SpaceTypeAttr)
|
||||
if err != nil {
|
||||
return errtypes.InternalError(fmt.Sprintf("space %s does not have a spacetype, possible corrupt decompsedfs", n.ID))
|
||||
return nil, errtypes.InternalError(fmt.Sprintf("space %s does not have a spacetype, possible corrupt decompsedfs", n.ID))
|
||||
}
|
||||
|
||||
if err := canDeleteSpace(ctx, spaceID, st, purge, n, fs.p); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if purge {
|
||||
if !n.IsDisabled(ctx) {
|
||||
return errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space"))
|
||||
return nil, errtypes.NewErrtypeFromStatus(status.NewInvalid(ctx, "can't purge enabled space"))
|
||||
}
|
||||
|
||||
// Capture data for SpaceDeleted before any destructive work.
|
||||
spaceName, _ := n.SpaceRoot.XattrString(ctx, prefixes.SpaceNameAttr)
|
||||
finalMembers, err := fs.readFinalMembers(ctx, n, spaceName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO invalidate ALL indexes in msgpack, not only by type
|
||||
spaceType, err := n.XattrString(ctx, prefixes.SpaceTypeAttr)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if err := fs.spaceTypeIndex.Remove(spaceType, spaceID); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// invalidate cache
|
||||
if err := fs.lu.MetadataBackend().Purge(ctx, n.InternalPath()); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
root := fs.getSpaceRoot(spaceID)
|
||||
@@ -809,24 +820,110 @@ func (fs *Decomposedfs) DeleteStorageSpace(ctx context.Context, req *provider.De
|
||||
// This is deletes all blobs of the space
|
||||
// NOTE: This isn't needed when no s3 is used, but we can't differentiate that here...
|
||||
if err := filepath.Walk(root, walkfn); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// remove space metadata
|
||||
if err := os.RemoveAll(root); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// try removing the space root node
|
||||
// Note that this will fail when there are other spaceids starting with the same two digits.
|
||||
_ = os.Remove(filepath.Dir(root))
|
||||
|
||||
return nil
|
||||
return &storage.DeleteStorageSpaceResult{
|
||||
SpaceName: spaceName,
|
||||
FinalMembers: finalMembers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mark as disabled by writing a dtime attribute
|
||||
dtime := time.Now()
|
||||
return n.SetDTime(ctx, &dtime)
|
||||
if err := n.SetDTime(ctx, &dtime); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteStorageSpaceResult{}, nil
|
||||
}
|
||||
|
||||
// readFinalMembers returns the space's active user/group grants
|
||||
// keyed by grantee opaque ID. Expired grants are pruned as a side
|
||||
// effect: the grant is deleted, the corresponding user/group space
|
||||
// index entry is removed, and a SpaceMembershipExpired event is
|
||||
// published, so expired grantees are absent from the result.
|
||||
func (fs *Decomposedfs) readFinalMembers(ctx context.Context, n *node.Node, spaceName string) (map[string]provider.ResourcePermissions, error) {
|
||||
sublog := appctx.GetLogger(ctx).With().Str("spaceid", n.SpaceID).Logger()
|
||||
|
||||
grants, err := n.ListGrants(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tmp := make(map[string]*provider.ResourcePermissions, len(grants))
|
||||
for _, g := range grants {
|
||||
var id string
|
||||
switch g.Grantee.Type {
|
||||
case provider.GranteeType_GRANTEE_TYPE_USER:
|
||||
id = g.Grantee.GetUserId().GetOpaqueId()
|
||||
case provider.GranteeType_GRANTEE_TYPE_GROUP:
|
||||
id = g.Grantee.GetGroupId().GetOpaqueId()
|
||||
default:
|
||||
continue
|
||||
}
|
||||
|
||||
if g.Expiration != nil && isGrantExpired(g) {
|
||||
errDeleteGrant := n.DeleteGrant(ctx, g, true)
|
||||
if errDeleteGrant != nil {
|
||||
sublog.Error().Err(errDeleteGrant).Str("grantee", id).
|
||||
Msg("failed to delete expired space grant")
|
||||
}
|
||||
if n.IsSpaceRoot(ctx) {
|
||||
switch g.Grantee.Type {
|
||||
case provider.GranteeType_GRANTEE_TYPE_USER:
|
||||
if errIndexRemove := fs.userSpaceIndex.Remove(g.Grantee.GetUserId().GetOpaqueId(), n.SpaceID); errIndexRemove != nil {
|
||||
sublog.Error().Err(errIndexRemove).Str("grantee", id).
|
||||
Msg("failed to delete expired user space index")
|
||||
}
|
||||
case provider.GranteeType_GRANTEE_TYPE_GROUP:
|
||||
if errIndexRemove := fs.groupSpaceIndex.Remove(g.Grantee.GetGroupId().GetOpaqueId(), n.SpaceID); errIndexRemove != nil {
|
||||
sublog.Error().Err(errIndexRemove).Str("grantee", id).
|
||||
Msg("failed to delete expired group space index")
|
||||
}
|
||||
}
|
||||
|
||||
if errDeleteGrant == nil {
|
||||
ev := events.SpaceMembershipExpired{
|
||||
SpaceOwner: n.SpaceOwnerOrManager(ctx),
|
||||
SpaceID: &provider.StorageSpaceId{OpaqueId: n.SpaceID},
|
||||
SpaceName: spaceName,
|
||||
ExpiredAt: time.Unix(int64(g.Expiration.Seconds), int64(g.Expiration.Nanos)),
|
||||
Timestamp: utils.TSNow(),
|
||||
}
|
||||
switch g.Grantee.Type {
|
||||
case provider.GranteeType_GRANTEE_TYPE_USER:
|
||||
ev.GranteeUserID = g.Grantee.GetUserId()
|
||||
case provider.GranteeType_GRANTEE_TYPE_GROUP:
|
||||
ev.GranteeGroupID = g.Grantee.GetGroupId()
|
||||
}
|
||||
if errPublish := events.Publish(ctx, fs.stream, ev); errPublish != nil {
|
||||
sublog.Error().Err(errPublish).Msg("error publishing SpaceMembershipExpired event")
|
||||
}
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
tmp[id] = g.Permissions
|
||||
}
|
||||
|
||||
b, err := json.Marshal(tmp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(map[string]provider.ResourcePermissions, len(tmp))
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// the value of `target` depends on the implementation:
|
||||
@@ -1172,7 +1269,8 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool,
|
||||
}
|
||||
|
||||
// space managers are allowed to disable and delete their project spaces
|
||||
if rp, err := p.AssemblePermissions(ctx, n); err == nil && permissions.IsManager(rp) {
|
||||
rp, err := p.AssemblePermissions(ctx, n)
|
||||
if err == nil && permissions.IsManager(rp) {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1186,5 +1284,10 @@ func canDeleteSpace(ctx context.Context, spaceID string, typ string, purge bool,
|
||||
return nil
|
||||
}
|
||||
|
||||
// active space, user has no grant at all: hide existence rather than reveal it
|
||||
if err == nil && !rp.GetStat() && !n.IsDisabled(ctx) {
|
||||
return errtypes.NotFound(spaceID)
|
||||
}
|
||||
|
||||
return errtypes.PermissionDenied(fmt.Sprintf("user is not allowed to delete space %s", n.ID))
|
||||
}
|
||||
Generated
Vendored
+1
-1
@@ -29,7 +29,7 @@ type Trashbin interface {
|
||||
Setup(storage.FS) error
|
||||
|
||||
ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error)
|
||||
RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error
|
||||
RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error)
|
||||
PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error
|
||||
EmptyRecycle(ctx context.Context, ref *provider.Reference) error
|
||||
}
|
||||
+87
-61
@@ -40,6 +40,7 @@ import (
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
types "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/jellydator/ttlcache/v2"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
@@ -57,7 +58,6 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/grants"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/templates"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/jellydator/ttlcache/v2"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -780,36 +780,36 @@ func (fs *eosfs) setLock(ctx context.Context, lock *provider.Lock, path string,
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) error {
|
||||
func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provider.Lock) (*storage.SetLockResult, error) {
|
||||
if l.Type == provider.LockType_LOCK_TYPE_SHARED {
|
||||
return errtypes.NotSupported("shared lock not yet implemented")
|
||||
return nil, errtypes.NotSupported("shared lock not yet implemented")
|
||||
}
|
||||
|
||||
path, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
path = fs.wrap(ctx, path)
|
||||
|
||||
user, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: no user in ctx")
|
||||
return nil, errors.Wrap(err, "eosfs: no user in ctx")
|
||||
}
|
||||
auth, err := fs.getUserAuth(ctx, user, path)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error getting uid and gid for user")
|
||||
return nil, errors.Wrap(err, "eosfs: error getting uid and gid for user")
|
||||
}
|
||||
|
||||
_, err = fs.getLock(ctx, auth, user, path, ref)
|
||||
if err != nil {
|
||||
// if the err is NotFound it is fine, otherwise we have to return
|
||||
if _, ok := err.(errtypes.NotFound); !ok {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
// the resource is already locked
|
||||
return errtypes.BadRequest("resource already locked")
|
||||
return nil, errtypes.BadRequest("resource already locked")
|
||||
}
|
||||
|
||||
// the cs3apis require to have the write permission on the resource
|
||||
@@ -818,10 +818,10 @@ func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provid
|
||||
// the request has it
|
||||
has, err := fs.userHasWriteAccess(ctx, user, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, fmt.Sprintf("eosfs: cannot check if user %s has write access on resource", user.Username))
|
||||
return nil, errors.Wrap(err, fmt.Sprintf("eosfs: cannot check if user %s has write access on resource", user.Username))
|
||||
}
|
||||
if !has {
|
||||
return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
}
|
||||
|
||||
// the user in the lock could differ from the user in the context
|
||||
@@ -829,14 +829,17 @@ func (fs *eosfs) SetLock(ctx context.Context, ref *provider.Reference, l *provid
|
||||
if l.User != nil && !utils.UserEqual(user.Id, l.User) {
|
||||
has, err := fs.userIDHasWriteAccess(ctx, l.User, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
|
||||
return nil, errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
|
||||
}
|
||||
if !has {
|
||||
return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
}
|
||||
}
|
||||
|
||||
return fs.setLock(ctx, l, path, true)
|
||||
if err := fs.setLock(ctx, l, path, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.SetLockResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) getUserFromID(ctx context.Context, userID *userpb.UserId) (*userpb.User, error) {
|
||||
@@ -952,9 +955,9 @@ func sameHolder(l1, l2 *provider.Lock) bool {
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
if lock.Type == provider.LockType_LOCK_TYPE_SHARED {
|
||||
return errtypes.NotSupported("shared lock not yet implemented")
|
||||
return nil, errtypes.NotSupported("shared lock not yet implemented")
|
||||
}
|
||||
|
||||
oldLock, err := fs.GetLock(ctx, ref)
|
||||
@@ -962,47 +965,50 @@ func (fs *eosfs) Unlock(ctx context.Context, ref *provider.Reference, lock *prov
|
||||
switch err.(type) {
|
||||
case errtypes.NotFound:
|
||||
// the lock does not exist
|
||||
return errtypes.BadRequest("file was not locked")
|
||||
return nil, errtypes.BadRequest("file was not locked")
|
||||
default:
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// check if the lock id of the lock corresponds to the stored lock
|
||||
if oldLock.LockId != lock.LockId {
|
||||
return errtypes.BadRequest("lock id does not match")
|
||||
return nil, errtypes.BadRequest("lock id does not match")
|
||||
}
|
||||
|
||||
if !sameHolder(oldLock, lock) {
|
||||
return errtypes.BadRequest("caller does not hold the lock")
|
||||
return nil, errtypes.BadRequest("caller does not hold the lock")
|
||||
}
|
||||
|
||||
user, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error getting user")
|
||||
return nil, errors.Wrap(err, "eosfs: error getting user")
|
||||
}
|
||||
|
||||
// the cs3apis require to have the write permission on the resource
|
||||
// to remove the lock
|
||||
has, err := fs.userHasWriteAccess(ctx, user, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
|
||||
return nil, errors.Wrap(err, "eosfs: cannot check if user has write access on resource")
|
||||
}
|
||||
if !has {
|
||||
return errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
return nil, errtypes.PermissionDenied(fmt.Sprintf("user %s has not write access on resource", user.Username))
|
||||
}
|
||||
|
||||
path, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
path = fs.wrap(ctx, path)
|
||||
|
||||
auth, err := fs.getRootAuth(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error getting uid and gid for user")
|
||||
return nil, errors.Wrap(err, "eosfs: error getting uid and gid for user")
|
||||
}
|
||||
return fs.removeLockAttrs(ctx, auth, path)
|
||||
if err := fs.removeLockAttrs(ctx, auth, path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.UnlockResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) AddGrant(ctx context.Context, ref *provider.Reference, g *provider.Grant) error {
|
||||
@@ -1642,44 +1648,49 @@ func (fs *eosfs) createUserDir(ctx context.Context, u *userpb.User, path string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *eosfs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
p, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
if fs.isShareFolder(ctx, p) {
|
||||
return errtypes.PermissionDenied("eosfs: cannot perform operation under the virtual share folder")
|
||||
return nil, errtypes.PermissionDenied("eosfs: cannot perform operation under the virtual share folder")
|
||||
}
|
||||
fn := fs.wrap(ctx, p)
|
||||
|
||||
u, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: no user in ctx")
|
||||
return nil, errors.Wrap(err, "eosfs: no user in ctx")
|
||||
}
|
||||
|
||||
// We need the auth corresponding to the parent directory
|
||||
// as the file might not exist at the moment
|
||||
auth, err := fs.getUserAuth(ctx, u, path.Dir(fn))
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Info().Msgf("eosfs: createdir: path=%s", fn)
|
||||
return fs.c.CreateDir(ctx, auth, fn)
|
||||
if err := fs.c.CreateDir(ctx, auth, fn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *eosfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error {
|
||||
func (fs *eosfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
fn, auth, err := fs.resolveRefAndGetAuth(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
log.Info().Msgf("eosfs: touch file: path=%s", fn)
|
||||
|
||||
return fs.c.Touch(ctx, auth, fn)
|
||||
if err := fs.c.Touch(ctx, auth, fn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.TouchFileResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) CreateReference(ctx context.Context, p string, targetURI *url.URL) error {
|
||||
@@ -1730,28 +1741,34 @@ func (fs *eosfs) CreateReference(ctx context.Context, p string, targetURI *url.U
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *eosfs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
p, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
|
||||
if fs.isShareFolder(ctx, p) {
|
||||
return fs.deleteShadow(ctx, p)
|
||||
if err = fs.deleteShadow(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
fn := fs.wrap(ctx, p)
|
||||
|
||||
u, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: no user in ctx")
|
||||
return nil, errors.Wrap(err, "eosfs: no user in ctx")
|
||||
}
|
||||
auth, err := fs.getUserAuth(ctx, u, fn)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.c.Remove(ctx, auth, fn, false)
|
||||
if err := fs.c.Remove(ctx, auth, fn, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) deleteShadow(ctx context.Context, p string) error {
|
||||
@@ -1776,19 +1793,19 @@ func (fs *eosfs) deleteShadow(ctx context.Context, p string) error {
|
||||
return errors.New("eosfs: shadow delete of share folder that is neither root nor child. path=" + p)
|
||||
}
|
||||
|
||||
func (fs *eosfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (fs *eosfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
oldPath, err := fs.resolve(ctx, oldRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
|
||||
newPath, err := fs.resolve(ctx, newRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: error resolving reference")
|
||||
return nil, errors.Wrap(err, "eosfs: error resolving reference")
|
||||
}
|
||||
|
||||
if fs.isShareFolder(ctx, oldPath) || fs.isShareFolder(ctx, newPath) {
|
||||
return fs.moveShadow(ctx, oldPath, newPath)
|
||||
return nil, fs.moveShadow(ctx, oldPath, newPath)
|
||||
}
|
||||
|
||||
oldFn := fs.wrap(ctx, oldPath)
|
||||
@@ -1796,14 +1813,17 @@ func (fs *eosfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) e
|
||||
|
||||
u, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: no user in ctx")
|
||||
return nil, errors.Wrap(err, "eosfs: no user in ctx")
|
||||
}
|
||||
auth, err := fs.getUserAuth(ctx, u, oldFn)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return fs.c.Rename(ctx, auth, oldFn, newFn)
|
||||
if err := fs.c.Rename(ctx, auth, oldFn, newFn); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) moveShadow(ctx context.Context, oldPath, newPath string) error {
|
||||
@@ -1935,7 +1955,7 @@ func (fs *eosfs) DownloadRevision(ctx context.Context, ref *provider.Reference,
|
||||
return md, reader, err
|
||||
}
|
||||
|
||||
func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
var auth eosclient.Authorization
|
||||
var fn string
|
||||
var err error
|
||||
@@ -1946,26 +1966,29 @@ func (fs *eosfs) RestoreRevision(ctx context.Context, ref *provider.Reference, r
|
||||
// if we have access to it.
|
||||
md, err := fs.GetMD(ctx, ref, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
fn = fs.wrap(ctx, md.Path)
|
||||
|
||||
if md.PermissionSet.RestoreFileVersion {
|
||||
auth, err = fs.getUIDGateway(ctx, md.Owner)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
return errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore revisions")
|
||||
return nil, errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore revisions")
|
||||
}
|
||||
} else {
|
||||
fn, auth, err = fs.resolveRefForbidShareFolder(ctx, ref)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return fs.c.RollbackToVersion(ctx, auth, fn, revisionKey)
|
||||
if err := fs.c.RollbackToVersion(ctx, auth, fn, revisionKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -2036,7 +2059,7 @@ func (fs *eosfs) ListRecycle(ctx context.Context, ref *provider.Reference, key,
|
||||
return recycleEntries, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
var auth eosclient.Authorization
|
||||
|
||||
if !fs.conf.EnableHome && fs.conf.AllowPathRecycleOperations && ref.Path != "/" {
|
||||
@@ -2045,29 +2068,32 @@ func (fs *eosfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference
|
||||
// if we have access to it.
|
||||
md, err := fs.GetMD(ctx, &provider.Reference{Path: ref.Path}, nil, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if md.PermissionSet.RestoreRecycleItem {
|
||||
auth, err = fs.getUIDGateway(ctx, md.Owner)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
return errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore recycled items")
|
||||
return nil, errtypes.PermissionDenied("eosfs: user doesn't have permissions to restore recycled items")
|
||||
}
|
||||
} else {
|
||||
// We just act on the logged-in user's recycle bin
|
||||
u, err := getUser(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "eosfs: no user in ctx")
|
||||
return nil, errors.Wrap(err, "eosfs: no user in ctx")
|
||||
}
|
||||
auth, err = fs.getUserAuth(ctx, u, "")
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return fs.c.RestoreDeletedEntry(ctx, auth, key)
|
||||
if err := fs.c.RestoreDeletedEntry(ctx, auth, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *eosfs) convertToRecycleItem(ctx context.Context, eosDeletedItem *eosclient.DeletedEntry) (*provider.RecycleItem, error) {
|
||||
|
||||
+3
-2
@@ -34,6 +34,7 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/eosclient"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/templates"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/pkg/errors"
|
||||
@@ -360,6 +361,6 @@ func (fs *eosfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateSto
|
||||
return nil, errtypes.NotSupported("update storage space")
|
||||
}
|
||||
|
||||
func (fs *eosfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("delete storage spaces")
|
||||
func (fs *eosfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("delete storage spaces")
|
||||
}
|
||||
+62
-50
@@ -720,8 +720,8 @@ func (fs *localfs) GetLock(ctx context.Context, ref *provider.Reference) (*provi
|
||||
}
|
||||
|
||||
// SetLock puts a lock on the given reference
|
||||
func (fs *localfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *localfs) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
// RefreshLock refreshes an existing lock on the given reference
|
||||
@@ -730,8 +730,8 @@ func (fs *localfs) RefreshLock(ctx context.Context, ref *provider.Reference, loc
|
||||
}
|
||||
|
||||
// Unlock removes an existing lock from the given reference
|
||||
func (fs *localfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
return errtypes.NotSupported("unimplemented")
|
||||
func (fs *localfs) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
return nil, errtypes.NotSupported("unimplemented")
|
||||
}
|
||||
|
||||
func (fs *localfs) GetHome(ctx context.Context) (string, error) {
|
||||
@@ -779,45 +779,48 @@ func (fs *localfs) createHomeInternal(ctx context.Context, fn string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *localfs) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
|
||||
fn, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if fs.isShareFolder(ctx, fn) {
|
||||
return errtypes.PermissionDenied("localfs: cannot create folder under the share folder")
|
||||
return nil, errtypes.PermissionDenied("localfs: cannot create folder under the share folder")
|
||||
}
|
||||
|
||||
fn = fs.wrap(ctx, fn)
|
||||
if _, err := os.Stat(fn); err == nil {
|
||||
return errtypes.AlreadyExists(fn)
|
||||
return nil, errtypes.AlreadyExists(fn)
|
||||
}
|
||||
err = os.Mkdir(fn, 0700)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.PreconditionFailed(fn)
|
||||
return nil, errtypes.PreconditionFailed(fn)
|
||||
}
|
||||
return errors.Wrap(err, "localfs: error creating dir "+fn)
|
||||
return nil, errors.Wrap(err, "localfs: error creating dir "+fn)
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, path.Dir(fn))
|
||||
if err := fs.propagate(ctx, path.Dir(fn)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.CreateDirResult{}, nil
|
||||
}
|
||||
|
||||
// TouchFile as defined in the storage.FS interface
|
||||
func (fs *localfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) error {
|
||||
return fmt.Errorf("unimplemented: TouchFile")
|
||||
func (fs *localfs) TouchFile(ctx context.Context, ref *provider.Reference, _ bool, _ string) (*storage.TouchFileResult, error) {
|
||||
return nil, fmt.Errorf("unimplemented: TouchFile")
|
||||
}
|
||||
|
||||
func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
fn, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "localfs: error resolving ref")
|
||||
}
|
||||
|
||||
if fs.isShareFolderRoot(ctx, fn) {
|
||||
return errtypes.PermissionDenied("localfs: cannot delete the virtual share folder")
|
||||
return nil, errtypes.PermissionDenied("localfs: cannot delete the virtual share folder")
|
||||
}
|
||||
|
||||
var fp string
|
||||
@@ -830,58 +833,61 @@ func (fs *localfs) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
_, err = os.Stat(fp)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.NotFound(fn)
|
||||
return nil, errtypes.NotFound(fn)
|
||||
}
|
||||
return errors.Wrap(err, "localfs: error stating "+fp)
|
||||
return nil, errors.Wrap(err, "localfs: error stating "+fp)
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("%s.d%d", path.Base(fn), time.Now().UnixNano()/int64(time.Millisecond))
|
||||
if err := os.Rename(fp, fs.wrapRecycleBin(ctx, key)); err != nil {
|
||||
return errors.Wrap(err, "localfs: could not delete item")
|
||||
return nil, errors.Wrap(err, "localfs: could not delete item")
|
||||
}
|
||||
|
||||
err = fs.addToRecycledDB(ctx, key, fn)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error adding entry to DB")
|
||||
return nil, errors.Wrap(err, "localfs: error adding entry to DB")
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, path.Dir(fp))
|
||||
if err := fs.propagate(ctx, path.Dir(fp)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (fs *localfs) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
oldName, err := fs.resolve(ctx, oldRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "localfs: error resolving ref")
|
||||
}
|
||||
|
||||
newName, err := fs.resolve(ctx, newRef)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "localfs: error resolving ref")
|
||||
}
|
||||
|
||||
if fs.isShareFolder(ctx, oldName) || fs.isShareFolder(ctx, newName) {
|
||||
return fs.moveReferences(ctx, oldName, newName)
|
||||
return nil, fs.moveReferences(ctx, oldName, newName)
|
||||
}
|
||||
|
||||
oldName = fs.wrap(ctx, oldName)
|
||||
newName = fs.wrap(ctx, newName)
|
||||
|
||||
if err := os.Rename(oldName, newName); err != nil {
|
||||
return errors.Wrap(err, "localfs: error moving "+oldName+" to "+newName)
|
||||
return nil, errors.Wrap(err, "localfs: error moving "+oldName+" to "+newName)
|
||||
}
|
||||
|
||||
if err := fs.copyMD(oldName, newName); err != nil {
|
||||
return errors.Wrap(err, "localfs: error copying metadata")
|
||||
return nil, errors.Wrap(err, "localfs: error copying metadata")
|
||||
}
|
||||
|
||||
if err := fs.propagate(ctx, newName); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if err := fs.propagate(ctx, path.Dir(oldName)); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil
|
||||
return &storage.MoveResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) moveReferences(ctx context.Context, oldName, newName string) error {
|
||||
@@ -1172,14 +1178,14 @@ func (fs *localfs) DownloadRevision(ctx context.Context, ref *provider.Reference
|
||||
return ri, r, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) error {
|
||||
func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference, revisionKey string) (*storage.RestoreRevisionResult, error) {
|
||||
np, err := fs.resolve(ctx, ref)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error resolving ref")
|
||||
return nil, errors.Wrap(err, "localfs: error resolving ref")
|
||||
}
|
||||
|
||||
if fs.isShareFolder(ctx, np) {
|
||||
return errtypes.PermissionDenied("localfs: cannot restore revisions under the virtual share folder")
|
||||
return nil, errtypes.PermissionDenied("localfs: cannot restore revisions under the virtual share folder")
|
||||
}
|
||||
|
||||
versionsDir := fs.wrapVersions(ctx, np)
|
||||
@@ -1190,24 +1196,27 @@ func (fs *localfs) RestoreRevision(ctx context.Context, ref *provider.Reference,
|
||||
vs, err := os.Stat(vp)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.NotFound(revisionKey)
|
||||
return nil, errtypes.NotFound(revisionKey)
|
||||
}
|
||||
return errors.Wrap(err, "localfs: error stating "+vp)
|
||||
return nil, errors.Wrap(err, "localfs: error stating "+vp)
|
||||
}
|
||||
|
||||
if !vs.Mode().IsRegular() {
|
||||
return fmt.Errorf("%s is not a regular file", vp)
|
||||
return nil, fmt.Errorf("%s is not a regular file", vp)
|
||||
}
|
||||
|
||||
if err := fs.archiveRevision(ctx, np); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.Rename(vp, np); err != nil {
|
||||
return errors.Wrap(err, "localfs: error renaming from "+vp+" to "+np)
|
||||
return nil, errors.Wrap(err, "localfs: error renaming from "+vp+" to "+np)
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, np)
|
||||
if err := fs.propagate(ctx, np); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRevisionResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -1279,16 +1288,16 @@ func (fs *localfs) ListRecycle(ctx context.Context, ref *provider.Reference, key
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
|
||||
suffix := path.Ext(key)
|
||||
if len(suffix) == 0 || !strings.HasPrefix(suffix, ".d") {
|
||||
return errors.New("localfs: invalid trash item suffix")
|
||||
return nil, errors.New("localfs: invalid trash item suffix")
|
||||
}
|
||||
|
||||
filePath, err := fs.getRecycledEntry(ctx, key)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: invalid key")
|
||||
return nil, errors.Wrap(err, "localfs: invalid key")
|
||||
}
|
||||
|
||||
var localRestorePath string
|
||||
@@ -1302,27 +1311,30 @@ func (fs *localfs) RestoreRecycleItem(ctx context.Context, ref *provider.Referen
|
||||
}
|
||||
|
||||
if _, err = os.Stat(localRestorePath); err == nil {
|
||||
return errors.New("localfs: can't restore - file already exists at original path")
|
||||
return nil, errors.New("localfs: can't restore - file already exists at original path")
|
||||
}
|
||||
|
||||
rp := fs.wrapRecycleBin(ctx, key)
|
||||
if _, err = os.Stat(rp); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errtypes.NotFound(key)
|
||||
return nil, errtypes.NotFound(key)
|
||||
}
|
||||
return errors.Wrap(err, "localfs: error stating "+rp)
|
||||
return nil, errors.Wrap(err, "localfs: error stating "+rp)
|
||||
}
|
||||
|
||||
if err := os.Rename(rp, localRestorePath); err != nil {
|
||||
return errors.Wrap(err, "ocfs: could not restore item")
|
||||
return nil, errors.Wrap(err, "ocfs: could not restore item")
|
||||
}
|
||||
|
||||
err = fs.removeFromRecycledDB(ctx, key)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "localfs: error adding entry to DB")
|
||||
return nil, errors.Wrap(err, "localfs: error adding entry to DB")
|
||||
}
|
||||
|
||||
return fs.propagate(ctx, localRestorePath)
|
||||
if err := fs.propagate(ctx, localRestorePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &storage.RestoreRecycleItemResult{}, nil
|
||||
}
|
||||
|
||||
func (fs *localfs) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) {
|
||||
@@ -1335,8 +1347,8 @@ func (fs *localfs) UpdateStorageSpace(ctx context.Context, req *provider.UpdateS
|
||||
}
|
||||
|
||||
// DeleteStorageSpace deletes a storage space
|
||||
func (fs *localfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
return errtypes.NotSupported("delete storage space")
|
||||
func (fs *localfs) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
return nil, errtypes.NotSupported("delete storage space")
|
||||
}
|
||||
|
||||
func (fs *localfs) propagate(ctx context.Context, leafPath string) error {
|
||||
|
||||
+27
-3
@@ -30,7 +30,9 @@ import (
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
renameio "github.com/google/renameio/v2"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/storage/utils/filelocks"
|
||||
)
|
||||
|
||||
// Disk represents a disk metadata storage
|
||||
@@ -93,6 +95,14 @@ func (disk *Disk) SimpleUpload(ctx context.Context, uploadpath string, content [
|
||||
// Upload stores a file on disk
|
||||
func (disk *Disk) Upload(_ context.Context, req UploadRequest) (*UploadResponse, error) {
|
||||
p := disk.targetPath(req.Path)
|
||||
|
||||
// Serialize check+write across processes to eliminate the TOCTOU race.
|
||||
lock, err := filelocks.AcquireWriteLock(p)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("acquiring write lock: %w", err)
|
||||
}
|
||||
defer filelocks.ReleaseLock(lock)
|
||||
|
||||
if req.IfMatchEtag != "" {
|
||||
info, err := os.Stat(p)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
@@ -117,12 +127,20 @@ func (disk *Disk) Upload(_ context.Context, req UploadRequest) (*UploadResponse,
|
||||
}
|
||||
}
|
||||
}
|
||||
err := os.WriteFile(p, req.Content, 0644)
|
||||
if err != nil {
|
||||
for _, v := range req.IfNoneMatch {
|
||||
if v == "*" {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return nil, errtypes.AlreadyExists(p)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err := renameio.WriteFile(p, req.Content, 0644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info, err := os.Stat(disk.targetPath(req.Path))
|
||||
info, err := os.Stat(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -160,6 +178,12 @@ func (disk *Disk) Download(_ context.Context, req DownloadRequest) (*DownloadRes
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, tag := range req.IfNoneMatch {
|
||||
if tag == res.Etag {
|
||||
return nil, errtypes.NotModified(req.Path)
|
||||
}
|
||||
}
|
||||
|
||||
res.Content, err = io.ReadAll(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
+45
-45
@@ -145,7 +145,7 @@ func (f *FS) CreateHome(ctx context.Context) error {
|
||||
return res0
|
||||
}
|
||||
|
||||
func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) (*storage.CreateDirResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -154,25 +154,25 @@ func (f *FS) CreateDir(ctx context.Context, ref *provider.Reference) error {
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("CreateDir", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.CreateDir(ctx, ref)
|
||||
result, err := f.next.CreateDir(ctx, ref)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) error {
|
||||
func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*storage.TouchFileResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -181,25 +181,25 @@ func (f *FS) TouchFile(ctx context.Context, ref *provider.Reference, markprocess
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("TouchFile", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.TouchFile(ctx, ref, markprocessing, mtime)
|
||||
result, err := f.next.TouchFile(ctx, ref, markprocessing, mtime)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
func (f *FS) Delete(ctx context.Context, ref *provider.Reference) (*storage.DeleteResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -208,25 +208,25 @@ func (f *FS) Delete(ctx context.Context, ref *provider.Reference) error {
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("Delete", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.Delete(ctx, ref)
|
||||
res0, err := f.next.Delete(ctx, ref)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return res0, err
|
||||
}
|
||||
|
||||
func (f *FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) error {
|
||||
func (f *FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) (*storage.MoveResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -235,22 +235,22 @@ func (f *FS) Move(ctx context.Context, oldRef, newRef *provider.Reference) error
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("Move", ctx, oldRef.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.Move(ctx, oldRef, newRef)
|
||||
res0, res1 := f.next.Move(ctx, oldRef, newRef)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return res0, res1
|
||||
}
|
||||
|
||||
func (f *FS) GetMD(ctx context.Context, ref *provider.Reference, mdKeys, fieldMask []string) (*provider.ResourceInfo, error) {
|
||||
@@ -442,7 +442,7 @@ func (f *FS) DownloadRevision(ctx context.Context, ref *provider.Reference, key
|
||||
return res0, res1, res2
|
||||
}
|
||||
|
||||
func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) error {
|
||||
func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key string) (*storage.RestoreRevisionResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -451,22 +451,22 @@ func (f *FS) RestoreRevision(ctx context.Context, ref *provider.Reference, key s
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("RestoreRevision", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.RestoreRevision(ctx, ref, key)
|
||||
result, err := f.next.RestoreRevision(ctx, ref, key)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) ListRecycle(ctx context.Context, ref *provider.Reference, key, relativePath string) ([]*provider.RecycleItem, error) {
|
||||
@@ -496,7 +496,7 @@ func (f *FS) ListRecycle(ctx context.Context, ref *provider.Reference, key, rela
|
||||
return res0, res1
|
||||
}
|
||||
|
||||
func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) error {
|
||||
func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string, restoreRef *provider.Reference) (*storage.RestoreRecycleItemResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -505,22 +505,22 @@ func (f *FS) RestoreRecycleItem(ctx context.Context, ref *provider.Reference, ke
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("RestoreRecycleItem", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef)
|
||||
result, err := f.next.RestoreRecycleItem(ctx, ref, key, relativePath, restoreRef)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) PurgeRecycleItem(ctx context.Context, ref *provider.Reference, key, relativePath string) error {
|
||||
@@ -870,7 +870,7 @@ func (f *FS) UnsetArbitraryMetadata(ctx context.Context, ref *provider.Reference
|
||||
return res0
|
||||
}
|
||||
|
||||
func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.SetLockResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -879,22 +879,22 @@ func (f *FS) SetLock(ctx context.Context, ref *provider.Reference, lock *provide
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("SetLock", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.SetLock(ctx, ref, lock)
|
||||
result, err := f.next.SetLock(ctx, ref, lock)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) GetLock(ctx context.Context, ref *provider.Reference) (*provider.Lock, error) {
|
||||
@@ -951,7 +951,7 @@ func (f *FS) RefreshLock(ctx context.Context, ref *provider.Reference, lock *pro
|
||||
return res0
|
||||
}
|
||||
|
||||
func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) error {
|
||||
func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider.Lock) (*storage.UnlockResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -960,22 +960,22 @@ func (f *FS) Unlock(ctx context.Context, ref *provider.Reference, lock *provider
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("Unlock", ctx, ref.GetResourceId().GetSpaceId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.Unlock(ctx, ref, lock)
|
||||
result, err := f.next.Unlock(ctx, ref, lock)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (f *FS) ListStorageSpaces(ctx context.Context, filter []*provider.ListStorageSpacesRequest_Filter, unrestricted bool) ([]*provider.StorageSpace, error) {
|
||||
@@ -1062,7 +1062,7 @@ func (f *FS) UpdateStorageSpace(ctx context.Context, req *provider.UpdateStorage
|
||||
return res0, res1
|
||||
}
|
||||
|
||||
func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) error {
|
||||
func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorageSpaceRequest) (*storage.DeleteStorageSpaceResult, error) {
|
||||
var (
|
||||
err error
|
||||
unhook UnHook
|
||||
@@ -1071,20 +1071,20 @@ func (f *FS) DeleteStorageSpace(ctx context.Context, req *provider.DeleteStorage
|
||||
for _, hook := range f.hooks {
|
||||
ctx, unhook, err = hook("DeleteStorageSpace", ctx, req.GetId().GetOpaqueId())
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
if unhook != nil {
|
||||
unhooks = append(unhooks, unhook)
|
||||
}
|
||||
}
|
||||
|
||||
res0 := f.next.DeleteStorageSpace(ctx, req)
|
||||
res0, err := f.next.DeleteStorageSpace(ctx, req)
|
||||
|
||||
for _, unhook := range unhooks {
|
||||
if err := unhook(); err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return res0
|
||||
return res0, err
|
||||
}
|
||||
+137
-12
@@ -22,26 +22,151 @@ import (
|
||||
"context"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/storage"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const (
|
||||
sendOwnerChanKey key = iota
|
||||
spaceOwnerSlotKey key = iota
|
||||
moveResultSlotKey
|
||||
deleteResultSlotKey
|
||||
deleteStorageSpaceResultSlotKey
|
||||
)
|
||||
|
||||
// ContextSendSpaceOwnerID stores the space owner in the context.
|
||||
func ContextSendSpaceOwnerID(ctx context.Context, id *userpb.UserId) {
|
||||
ch, ok := ctx.Value(sendOwnerChanKey).(chan<- *userpb.UserId)
|
||||
if ok {
|
||||
go func() {
|
||||
ch <- id
|
||||
close(ch)
|
||||
}()
|
||||
// --- space owner ---
|
||||
|
||||
type spaceOwnerSlot struct {
|
||||
ownerID *userpb.UserId
|
||||
}
|
||||
|
||||
// ContextRegisterSpaceOwnerSlot installs an empty slot in ctx so that the
|
||||
// storage driver can write the space owner via ContextSetSpaceOwner and the
|
||||
// events middleware can read it via ContextGetSpaceOwner after the handler
|
||||
// returns. Subsequent registrations are no-ops; the first registration wins.
|
||||
func ContextRegisterSpaceOwnerSlot(ctx context.Context) context.Context {
|
||||
if ctx.Value(spaceOwnerSlotKey) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, spaceOwnerSlotKey, &spaceOwnerSlot{})
|
||||
}
|
||||
|
||||
// ContextSetSpaceOwner writes id into the slot. Subsequent writes overwrite
|
||||
// the previous value. Does nothing if no slot was registered.
|
||||
func ContextSetSpaceOwner(ctx context.Context, id *userpb.UserId) {
|
||||
if slot, ok := ctx.Value(spaceOwnerSlotKey).(*spaceOwnerSlot); ok {
|
||||
slot.ownerID = id
|
||||
}
|
||||
}
|
||||
|
||||
// ContextRegisterSendOwnerChan registers a channel to send the current space owner
|
||||
func ContextRegisterSendOwnerChan(ctx context.Context, ch chan<- *userpb.UserId) context.Context {
|
||||
return context.WithValue(ctx, sendOwnerChanKey, ch)
|
||||
// ContextGetSpaceOwner returns the space owner written by the storage driver,
|
||||
// or nil if none was set.
|
||||
func ContextGetSpaceOwner(ctx context.Context) *userpb.UserId {
|
||||
if slot, ok := ctx.Value(spaceOwnerSlotKey).(*spaceOwnerSlot); ok {
|
||||
return slot.ownerID
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- move result ---
|
||||
|
||||
type moveResultSlot struct {
|
||||
result *storage.MoveResult
|
||||
}
|
||||
|
||||
// ContextRegisterMoveResultSlot installs an empty slot in ctx so that the
|
||||
// storage driver can write move metadata via ContextSetMoveResult and the
|
||||
// events middleware can read it via ContextGetMoveResult after the handler
|
||||
// returns. Subsequent registrations are no-ops; the first registration wins.
|
||||
func ContextRegisterMoveResultSlot(ctx context.Context) context.Context {
|
||||
if ctx.Value(moveResultSlotKey) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, moveResultSlotKey, &moveResultSlot{})
|
||||
}
|
||||
|
||||
// ContextSetMoveResult writes r into the slot. Subsequent writes overwrite
|
||||
// the previous value. Does nothing if no slot was registered.
|
||||
func ContextSetMoveResult(ctx context.Context, r *storage.MoveResult) {
|
||||
if slot, ok := ctx.Value(moveResultSlotKey).(*moveResultSlot); ok {
|
||||
slot.result = r
|
||||
}
|
||||
}
|
||||
|
||||
// ContextGetMoveResult returns the move result written by the storage driver,
|
||||
// or nil if none was set.
|
||||
func ContextGetMoveResult(ctx context.Context) *storage.MoveResult {
|
||||
if slot, ok := ctx.Value(moveResultSlotKey).(*moveResultSlot); ok {
|
||||
return slot.result
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- delete result ---
|
||||
|
||||
type deleteResultSlot struct {
|
||||
result *storage.DeleteResult
|
||||
}
|
||||
|
||||
// ContextRegisterDeleteResultSlot installs an empty slot in ctx so that the
|
||||
// storage driver can write delete metadata via ContextSetDeleteResult and the
|
||||
// events middleware can read it via ContextGetDeleteResult after the handler
|
||||
// returns. Subsequent registrations are no-ops; the first registration wins.
|
||||
func ContextRegisterDeleteResultSlot(ctx context.Context) context.Context {
|
||||
if ctx.Value(deleteResultSlotKey) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, deleteResultSlotKey, &deleteResultSlot{})
|
||||
}
|
||||
|
||||
// ContextSetDeleteResult writes r into the slot. Subsequent writes overwrite
|
||||
// the previous value. Does nothing if no slot was registered.
|
||||
func ContextSetDeleteResult(ctx context.Context, r *storage.DeleteResult) {
|
||||
if slot, ok := ctx.Value(deleteResultSlotKey).(*deleteResultSlot); ok {
|
||||
slot.result = r
|
||||
}
|
||||
}
|
||||
|
||||
// ContextGetDeleteResult returns the delete result written by the storage
|
||||
// driver, or nil if none was set.
|
||||
func ContextGetDeleteResult(ctx context.Context) *storage.DeleteResult {
|
||||
if slot, ok := ctx.Value(deleteResultSlotKey).(*deleteResultSlot); ok {
|
||||
return slot.result
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- delete storage space result ---
|
||||
|
||||
type deleteStorageSpaceResultSlot struct {
|
||||
result *storage.DeleteStorageSpaceResult
|
||||
}
|
||||
|
||||
// ContextRegisterDeleteStorageSpaceResultSlot installs an empty slot in ctx so
|
||||
// that the storage driver can write delete-space metadata via
|
||||
// ContextSetDeleteStorageSpaceResult and the events middleware can read it via
|
||||
// ContextGetDeleteStorageSpaceResult after the handler returns. Subsequent
|
||||
// registrations are no-ops; the first registration wins.
|
||||
func ContextRegisterDeleteStorageSpaceResultSlot(ctx context.Context) context.Context {
|
||||
if ctx.Value(deleteStorageSpaceResultSlotKey) != nil {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, deleteStorageSpaceResultSlotKey, &deleteStorageSpaceResultSlot{})
|
||||
}
|
||||
|
||||
// ContextSetDeleteStorageSpaceResult writes r into the slot. Subsequent writes
|
||||
// overwrite the previous value. Does nothing if no slot was registered.
|
||||
func ContextSetDeleteStorageSpaceResult(ctx context.Context, r *storage.DeleteStorageSpaceResult) {
|
||||
if slot, ok := ctx.Value(deleteStorageSpaceResultSlotKey).(*deleteStorageSpaceResultSlot); ok {
|
||||
slot.result = r
|
||||
}
|
||||
}
|
||||
|
||||
// ContextGetDeleteStorageSpaceResult returns the delete-space result written by
|
||||
// the storage driver, or nil if none was set.
|
||||
func ContextGetDeleteStorageSpaceResult(ctx context.Context) *storage.DeleteStorageSpaceResult {
|
||||
if slot, ok := ctx.Value(deleteStorageSpaceResultSlotKey).(*deleteStorageSpaceResultSlot); ok {
|
||||
return slot.result
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
-11
@@ -47,7 +47,6 @@ type config struct {
|
||||
TracerProvider trace.TracerProvider
|
||||
MeterProvider metric.MeterProvider
|
||||
SpanKind trace.SpanKind
|
||||
SpanStartOptions []trace.SpanStartOption
|
||||
SpanAttributes []attribute.KeyValue
|
||||
MetricAttributes []attribute.KeyValue
|
||||
MetricAttributesFn func(ctx context.Context) []attribute.KeyValue
|
||||
@@ -204,16 +203,6 @@ func WithMessageEvents(events ...Event) Option {
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanOptions configures an additional set of
|
||||
// trace.SpanOptions, which are applied to each new span.
|
||||
//
|
||||
// Deprecated: It is only used by the deprecated interceptor, and is unused by [NewClientHandler] and [NewServerHandler].
|
||||
func WithSpanOptions(opts ...trace.SpanStartOption) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.SpanStartOptions = append(c.SpanStartOptions, opts...)
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanKind returns an Option to set the span kind for spans created by
|
||||
// the handler.
|
||||
//
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
|
||||
grpc_codes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go
Generated
Vendored
+1
-1
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
oldsemconv "go.opentelemetry.io/otel/semconv/v1.37.0" //nolint:depguard // Use of v1.37.0 is required for backward compatibility stability opt-in.
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
|
||||
)
|
||||
|
||||
// ParseFullMethod returns a span name following the OpenTelemetry semantic
|
||||
|
||||
Generated
Vendored
+31
-19
@@ -13,8 +13,8 @@ import (
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
oldrpcconv "go.opentelemetry.io/otel/semconv/v1.37.0/rpcconv" //nolint:depguard // Use of v1.37.0 is required for backward compatibility stability opt-in.
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0/rpcconv"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.41.0/rpcconv"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
grpc_codes "google.golang.org/grpc/codes"
|
||||
@@ -367,27 +367,39 @@ func (*config) handleRPC(
|
||||
span.End()
|
||||
}
|
||||
|
||||
var metricAttrs []attribute.KeyValue
|
||||
if gctx != nil {
|
||||
// Don't use gctx.metricAttrSet here, because it requires passing
|
||||
// multiple RecordOptions, which would call metric.mergeSets and
|
||||
// allocate a new set for each Record call.
|
||||
metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+1)
|
||||
metricAttrs = append(metricAttrs, gctx.metricAttrs...)
|
||||
}
|
||||
metricAttrs = append(metricAttrs, rpcStatusAttr)
|
||||
// Allocate vararg slice once.
|
||||
recordOpts := []metric.RecordOption{metric.WithAttributeSet(attribute.NewSet(metricAttrs...))}
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
// Measure right before calling Record() to capture as much elapsed time as possible.
|
||||
elapsedTime := float64(rs.EndTime.Sub(rs.BeginTime)) / float64(time.Second)
|
||||
var durationEnabled bool
|
||||
var oldDurationEnabled bool
|
||||
|
||||
if duration != nil {
|
||||
duration.Record(ctx, elapsedTime, recordOpts...)
|
||||
durationEnabled = duration.Enabled(ctx)
|
||||
}
|
||||
if oldDuration != nil {
|
||||
oldDuration.Record(ctx, elapsedTime*1000.0, recordOpts...)
|
||||
oldDurationEnabled = oldDuration.Enabled(ctx)
|
||||
}
|
||||
|
||||
if durationEnabled || oldDurationEnabled {
|
||||
var metricAttrs []attribute.KeyValue
|
||||
if gctx != nil {
|
||||
// Don't use gctx.metricAttrSet here, because it requires passing
|
||||
// multiple RecordOptions, which would call metric.mergeSets and
|
||||
// allocate a new set for each Record call.
|
||||
metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+1)
|
||||
metricAttrs = append(metricAttrs, gctx.metricAttrs...)
|
||||
}
|
||||
metricAttrs = append(metricAttrs, rpcStatusAttr)
|
||||
// Allocate vararg slice once.
|
||||
recordOpts := []metric.RecordOption{metric.WithAttributeSet(attribute.NewSet(metricAttrs...))}
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
// Measure right before calling Record() to capture as much elapsed time as possible.
|
||||
elapsedTime := float64(rs.EndTime.Sub(rs.BeginTime)) / float64(time.Second)
|
||||
|
||||
if durationEnabled {
|
||||
duration.Record(ctx, elapsedTime, recordOpts...)
|
||||
}
|
||||
if oldDurationEnabled {
|
||||
oldDuration.Record(ctx, elapsedTime*1000.0, recordOpts...)
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -4,4 +4,4 @@
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
// Version is the current release version of the gRPC instrumentation.
|
||||
const Version = "0.68.0"
|
||||
const Version = "0.69.0"
|
||||
+11
-7
@@ -96,9 +96,9 @@ linters:
|
||||
- "!**/exporters/zipkin/**"
|
||||
deny:
|
||||
- pkg: go.opentelemetry.io/otel/semconv
|
||||
desc: "Use go.opentelemetry.io/otel/semconv/v1.40.0 instead. If a newer semconv version has been released, update the depguard rule."
|
||||
desc: "Use go.opentelemetry.io/otel/semconv/v1.41.0 instead. If a newer semconv version has been released, update the depguard rule."
|
||||
allow:
|
||||
- go.opentelemetry.io/otel/semconv/v1.40.0
|
||||
- go.opentelemetry.io/otel/semconv/v1.41.0
|
||||
gocritic:
|
||||
disabled-checks:
|
||||
- appendAssign
|
||||
@@ -134,13 +134,16 @@ linters:
|
||||
strconcat: true
|
||||
revive:
|
||||
confidence: 0.01
|
||||
enable-all-rules: false
|
||||
enable-default-rules: true
|
||||
max-open-files: 2048
|
||||
rules:
|
||||
- name: blank-imports
|
||||
- name: bool-literal-in-expr
|
||||
- name: constant-logical-expr
|
||||
- name: context-as-argument
|
||||
arguments:
|
||||
- allowTypesBefore: '*testing.T'
|
||||
- allow-types-before: '*testing.T'
|
||||
disabled: true
|
||||
- name: context-keys-type
|
||||
- name: deep-exit
|
||||
@@ -152,7 +155,7 @@ linters:
|
||||
- name: duplicated-imports
|
||||
- name: early-return
|
||||
arguments:
|
||||
- preserveScope
|
||||
- preserve-scope
|
||||
- name: empty-block
|
||||
- name: empty-lines
|
||||
- name: error-naming
|
||||
@@ -161,7 +164,7 @@ linters:
|
||||
- name: errorf
|
||||
- name: exported
|
||||
arguments:
|
||||
- sayRepetitiveInsteadOfStutters
|
||||
- say-repetitive-instead-of-stutters
|
||||
- name: flag-parameter
|
||||
- name: identical-branches
|
||||
- name: if-return
|
||||
@@ -169,11 +172,12 @@ linters:
|
||||
- name: increment-decrement
|
||||
- name: indent-error-flow
|
||||
arguments:
|
||||
- preserveScope
|
||||
- preserve-scope
|
||||
- name: package-comments
|
||||
- name: range
|
||||
- name: range-val-in-closure
|
||||
- name: range-val-address
|
||||
- name: receiver-naming
|
||||
- name: redefines-builtin-id
|
||||
- name: string-format
|
||||
arguments:
|
||||
@@ -183,7 +187,7 @@ linters:
|
||||
- name: struct-tag
|
||||
- name: superfluous-else
|
||||
arguments:
|
||||
- preserveScope
|
||||
- preserve-scope
|
||||
- name: time-equal
|
||||
- name: unconditional-recursion
|
||||
- name: unexported-return
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
# Agent Guide for opentelemetry-go
|
||||
|
||||
This file contains active, task-oriented instructions for autonomous and semi-autonomous coding agents working in this repository.
|
||||
|
||||
Before starting any task, read `.github/copilot-instructions.md`, `CONTRIBUTING.md`, and this file.
|
||||
Treat `.github/copilot-instructions.md` as global passive guidance for every task, including docs-only and review-only work.
|
||||
|
||||
## Core expectations
|
||||
|
||||
- Preserve OpenTelemetry specification compliance, API stability, and idiomatic Go.
|
||||
- Prefer minimal, surgical changes over broad refactors or speculative cleanup.
|
||||
- Read the package you are editing and match its existing naming, option types, error handling, comments, tests, and concurrency patterns.
|
||||
- Keep public APIs backward compatible unless the task explicitly requires a breaking change.
|
||||
- Keep telemetry resilient and loosely coupled. Do not introduce behavior that can unexpectedly interfere with host applications.
|
||||
- Inspect boundaries carefully: input validation, resource limits, cancellation, shutdown, error propagation, concurrency, and memory growth.
|
||||
- Prefer fail-safe behavior and explicit invariants over implicit assumptions.
|
||||
- Keep dependencies minimal and justified.
|
||||
- Preserve host-application safety: telemetry should not panic, block indefinitely, or amplify attacker-controlled input.
|
||||
- Be conservative on hot paths. Avoid unnecessary allocations, reflection, interface churn, blocking, global state, and high-cardinality telemetry.
|
||||
- Write comments only for intent, invariants, and non-obvious constraints. Do not add comments that restate the code.
|
||||
|
||||
## Default workflow
|
||||
|
||||
For new features and behavior changes, use this order unless the task explicitly says otherwise:
|
||||
|
||||
1. Read the relevant package, its tests, and any package docs or `README.md`.
|
||||
2. Add or update a failing unit test that captures the required behavior or regression.
|
||||
3. Implement the smallest change that makes the test pass.
|
||||
4. Refactor only after the behavior is locked in, and only if the refactor keeps the diff focused.
|
||||
5. If the changed code is on a hot path or performance-sensitive, inspect existing benchmarks and run them. Add a benchmark if coverage is missing.
|
||||
6. Update documentation artifacts as needed while the context is fresh. Follow the documentation and changelog conventions below for the specific updates required.
|
||||
7. Run `make precommit` each time before considering the work complete.
|
||||
|
||||
For docs-only, test-only, or review-only tasks, still start with the required repository guidance above, then skip the workflow steps that do not apply while keeping the same discipline around scope, verification, and repository conventions.
|
||||
|
||||
## Verification
|
||||
|
||||
- Use `make` as the canonical repository verification command. The default target is `precommit`.
|
||||
- `make precommit` is the expected final verification step for linting, generation, README checks, module checks, and tests.
|
||||
- During iteration, targeted commands are fine for fast feedback, but do not stop there if the task changes code.
|
||||
- If you touch performance-sensitive code, run focused benchmarks and compare the results using `benchstat` in addition to `make`.
|
||||
|
||||
## Documentation and changelog
|
||||
|
||||
- Non-internal, non-test packages should have Go doc comments, usually in `doc.go`.
|
||||
- Non-internal, non-test, non-documentation packages should also have a `README.md` with at least a title and a `pkg.go.dev` badge.
|
||||
- Prefer examples over long code snippets in GoDoc when practical.
|
||||
- Keep docs aligned with actual behavior. Do not leave stale comments, stale examples, or stale package documentation behind.
|
||||
- For user-visible changes, update `CHANGELOG.md` under the appropriate `Added`, `Changed`, `Deprecated`, `Fixed`, or `Removed` section within `## [Unreleased]`.
|
||||
|
||||
## Repository habits
|
||||
|
||||
- Prefer focused diffs. Avoid drive-by cleanup.
|
||||
- Follow existing option patterns and exported API conventions instead of inventing new abstractions.
|
||||
- Generated files are checked in. If your change affects generation, keep generated output up to date.
|
||||
- Prefer fast local search tools such as `rg` when exploring the repository.
|
||||
- When changing behavior, make the invariants explicit in tests.
|
||||
|
||||
## Personas
|
||||
|
||||
### Feature Agent
|
||||
|
||||
Use this persona for new behavior, new API surface, or spec-driven feature work.
|
||||
|
||||
- Start with a failing unit test.
|
||||
- Confirm the expected behavior against the spec, existing package behavior, and public API compatibility.
|
||||
- Implement the smallest viable change.
|
||||
- Update GoDoc, examples, `README.md`, and `CHANGELOG.md` when the change is user-visible.
|
||||
- If the feature touches a hot path, check benchmarks and add one if the coverage is missing.
|
||||
|
||||
### Refactoring Agent
|
||||
|
||||
Use this persona when improving structure without intentionally changing behavior.
|
||||
|
||||
- Treat behavior preservation as the default contract.
|
||||
- Add or tighten tests before moving code if current behavior is not already pinned down.
|
||||
- Avoid broad rewrites, clever abstractions, or package-wide cleanup unless explicitly requested.
|
||||
- If a refactor touches a hot path, benchmark before and after.
|
||||
- Keep API shape, semantics, concurrency guarantees, and failure modes unchanged unless the task says otherwise.
|
||||
|
||||
### Test Agent
|
||||
|
||||
Use this persona when adding missing coverage, reproducing bugs, or hardening regressions.
|
||||
|
||||
- Reproduce the bug or missing behavior with the smallest failing test you can.
|
||||
- Prefer testing public behavior and externally visible invariants.
|
||||
- Add targeted regression tests before changing production code.
|
||||
- Only change production code when it is required to make the tested behavior correct or testable.
|
||||
- Keep tests deterministic, readable, and aligned with package patterns.
|
||||
|
||||
### Performance Agent
|
||||
|
||||
Use this persona for hot-path work, allocation reduction, or throughput and latency improvements.
|
||||
|
||||
- Benchmark first to establish a baseline.
|
||||
- Prefer changes that reduce allocations, copying, interface churn, and unnecessary synchronization.
|
||||
- Do not trade away correctness, spec compliance, or API stability for micro-optimizations.
|
||||
- Add or update benchmarks when performance-sensitive coverage is missing.
|
||||
- If you materially change a hot path, capture before-and-after results, preferably with `benchstat`.
|
||||
|
||||
### Review Agent
|
||||
|
||||
Use this persona when asked to review code, patches, or pull requests.
|
||||
|
||||
- Lead with findings, not summaries.
|
||||
- Order findings by severity and include precise file and line references when available.
|
||||
- Focus on correctness, spec compliance, API compatibility, concurrency safety, resilience, performance regressions, missing tests, missing benchmarks, documentation gaps, and changelog gaps.
|
||||
- Call out when a diff is broader than necessary.
|
||||
- If you find no issues, say that explicitly and note any residual risks or verification gaps.
|
||||
+96
-1
@@ -11,6 +11,100 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
|
||||
<!-- Released section -->
|
||||
<!-- Don't change this section unless doing release -->
|
||||
|
||||
## [1.44.0/0.66.0/0.20.0/0.0.17] 2026-05-27
|
||||
|
||||
### Added
|
||||
|
||||
- Add `ByteSlice` and `ByteSliceValue` functions for new `BYTESLICE` attribute type in `go.opentelemetry.io/otel/attribute`. (#7948)
|
||||
- Apply attribute value limit to the `KindBytes` attribute type in `go.opentelemetry.io/otel/sdk/log`. (#7990)
|
||||
- Apply attribute value limit to the `BYTESLICE` attribute type in `go.opentelemetry.io/otel/sdk/trace`. (#7990)
|
||||
- Support `BYTESLICE` attributes in `go.opentelemetry.io/otel/trace`. (#8153)
|
||||
- Support `BYTESLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlptrace`. (#8153)
|
||||
- Support `BYTESLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlplog`. (#8153)
|
||||
- Support `BYTESLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric`. (#8153)
|
||||
- Support `BYTESLICE` attributes in `go.opentelemetry.io/otel/exporters/zipkin`. (#8153)
|
||||
- Add `String` method for `Value` type in `go.opentelemetry.io/otel/attribute`. (#8142)
|
||||
- Add `Slice` and `SliceValue` functions for new `SLICE` attribute type in `go.opentelemetry.io/otel/attribute`. (#8166)
|
||||
- Support `SLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlptrace`. (#8216)
|
||||
- Support `SLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlplog`. (#8216)
|
||||
- Support `SLICE` attributes in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric`. (#8216)
|
||||
- Support `SLICE` attributes in `go.opentelemetry.io/otel/exporters/zipkin`. (#8216)
|
||||
- Apply `AttributeValueLengthLimit` to `attribute.SLICE` type attribute values in `go.opentelemetry.io/otel/sdk/trace`, recursively truncating contained string values. (#8217)
|
||||
- Add `Error` field on `Record` type in `go.opentelemetry.io/otel/log/logtest`. (#8148)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#8157)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`. (#8157)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`. (#8157)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`. (#8157)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`. (#8157)
|
||||
- Add `WithMaxRequestSize` option in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8157)
|
||||
- Add `Settable` to `go.opentelemetry.io/otel/metric/x` to allow reusing attribute options. (#8178)
|
||||
- Add experimental support for splitting metric data across multiple batches in `go.opentelemetry.io/otel/sdk/metric`.
|
||||
Set `OTEL_GO_X_METRIC_EXPORT_BATCH_SIZE=<max_size>` to enable for all periodic readers.
|
||||
See `go.opentelemetry.io/otel/sdk/metric/internal/x` for feature documentation. (#8071)
|
||||
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`.
|
||||
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
|
||||
See `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc/internal/x` for feature documentation. (#8192)
|
||||
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`.
|
||||
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
|
||||
See `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp/internal/x` for feature documentation. (#8194)
|
||||
- Add experimental self-observability metrics in `go.opentelemetry.io/otel/exporters/stdout/stdoutlog`.
|
||||
Enable with `OTEL_GO_X_SELF_OBSERVABILITY=true` environment variable.
|
||||
See `go.opentelemetry.io/otel/stdout/stdoutlog/internal/x` for feature documentation. (#8263)
|
||||
- Add `WithDefaultAttributes` to `go.opentelemetry.io/otel/metric/x` to support setting default attributes on instruments. (#8135)
|
||||
- Add `go.opentelemetry.io/otel/semconv/v1.41.0` package.
|
||||
The package contains semantic conventions from the `v1.41.0` version of the OpenTelemetry Semantic Conventions.
|
||||
See the [migration documentation](./semconv/v1.41.0/MIGRATION.md) for information on how to upgrade from `go.opentelemetry.io/otel/semconv/v1.40.0`. (#8324)
|
||||
- Add Observable variants of instruments to `go.opentelemetry.io/otel/semconv/v1.41.0` package. (#8350)
|
||||
- Generate explicit histogram bucket boundaries from weaver configuration for HTTP and RPC duration instruments in `go.opentelemetry.io/otel/semconv/v1.41.0`. (#8002)
|
||||
|
||||
### Changed
|
||||
|
||||
- ⚠️ **Breaking Change:** `go.opentelemetry.io/otel/sdk/metric` now applies a default cardinality limit of 2000 to comply with the Metrics SDK specification recommendation.
|
||||
New attribute sets are dropped when the cardinality limit is reached. The measurement of these sets are aggregated into a special attribute set containing `attribute.Bool("otel.metric.overflow", true)`.
|
||||
This can break users who relied on the previous unlimited default.
|
||||
Set `WithCardinalityLimit(0)` or the deprecated `OTEL_GO_X_CARDINALITY_LIMIT=0` environment variable to preserve unlimited cardinality.
|
||||
Note that support for `OTEL_GO_X_CARDINALITY_LIMIT` may be removed in a future release. (#8247)
|
||||
- `ErrorType` in `go.opentelemetry.io/otel/semconv` now unwraps errors created with `fmt.Errorf` when deriving the `error.type` attribute. (#8133)
|
||||
- `go.opentelemetry.io/otel/sdk/log` now unwraps error chains created with `fmt.Errorf` when deriving the `error.type` attribute from errors on log records. (#8133)
|
||||
- `Set.MarshalLog` method in `go.opentelemetry.io/otel/attribute` now uses `Value.String` formatting following the [OpenTelemetry AnyValue representation for non-OTLP protocols](https://opentelemetry.io/docs/specs/otel/common/#anyvalue). (#8169)
|
||||
- Optimize `go.opentelemetry.io/otel/sdk/metric` to return a drop reservoir and short-circuit `Offer` calls to the exemplar reservoir when `exemplar.AlwaysOffFilter` is configured. (#8211) (#8267)
|
||||
- Optimize `go.opentelemetry.io/otel/sdk/metric` to return a drop reservoir for asynchronous instruments when `exemplar.TraceBasedFilter` is configured. (#8286)
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Deprecate `Value.Emit` method in `go.opentelemetry.io/otel/attribute`.
|
||||
Use `Value.String` instead. (#8176)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Limit OTLP request size to 64 MiB by default in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`.
|
||||
The limit applies before compression, oversized requests are treated as non-retryable errors, and the limit can be configured with the new `WithMaxRequestSize` option. (#8157, #8365)
|
||||
- Fix gzipped request body replay on redirect in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`. (#8135)
|
||||
- Fix gzipped request body replay on redirect in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8152)
|
||||
- `go.opentelemetry.io/otel/exporters/prometheus` now uses `Value.String` formatting for label values following the [OpenTelemetry AnyValue representation for non-OTLP protocols](https://opentelemetry.io/docs/specs/otel/common/#anyvalue). (#8170)
|
||||
- Propagate errors from the exporter when calling `Shutdown` on `BatchSpanProcessor` in `go.opentelemetry.io/otel/sdk/trace`. (#8197)
|
||||
- Fix stale status code reporting on self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp` and `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8226)
|
||||
- Fix a concurrent `Collect` data race and potential panic in `go.opentelemetry.io/otel/exporters/prometheus` when `WithResourceAsConstantLabels` option is used. (#8227)
|
||||
- Fix race condition in `FixedSizeReservoir` in `go.opentelemetry.io/otel/sdk/metric/exemplar` by reverting #7447. (#8249)
|
||||
- Fix `FixedSizeReservoir` in `go.opentelemetry.io/otel/sdk/metric/exemplar` to safely handle zero size.
|
||||
A capacity check in the constructor initializes the reservoir safely and skips initialization for zero-cap; early returns in `Offer()` and `Collect()` ensure no-op behavior. (#8295)
|
||||
- Fix counting of spans and logs in self-observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`, `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`, `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`, and `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#8254)
|
||||
- Drop conflicting scope attributes named `name`, `version`, or `schema_url` from metric labels in `go.opentelemetry.io/otel/exporters/prometheus`, preserving the dedicated `otel_scope_name`, `otel_scope_version`, and `otel_scope_schema_url` labels. (#8264)
|
||||
- Close schema files opened by `ParseFile` in `go.opentelemetry.io/otel/schema/v1.0` and `go.opentelemetry.io/otel/schema/v1.1`. ([GHSA-995v-fvrw-c78m](https://github.com/open-telemetry/opentelemetry-go/security/advisories/GHSA-995v-fvrw-c78m))
|
||||
- Enforce the 8192-byte baggage size limit during extraction/parsing, changing behavior when the limit is exceeded in `go.opentelemetry.io/otel/baggage` and `go.opentelemetry.io/otel/propagation`. (#8222)
|
||||
- Fix `go.opentelemetry.io/otel/semconv/v1.41.0` to include `Attr*` helper methods for required attributes on observable instruments. (#8361)
|
||||
- Limit baggage extraction error reporting in `go.opentelemetry.io/otel/propagation` to prevent malformed or oversized baggage headers from flooding logs. ([GHSA-5wrp-cwcj-q835](https://github.com/open-telemetry/opentelemetry-go/security/advisories/GHSA-5wrp-cwcj-q835))
|
||||
|
||||
## [1.43.0/0.65.0/0.19.0] 2026-04-02
|
||||
|
||||
### Added
|
||||
@@ -3619,7 +3713,8 @@ It contains api and sdk for trace and meter.
|
||||
- CircleCI build CI manifest files.
|
||||
- CODEOWNERS file to track owners of this project.
|
||||
|
||||
[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.43.0...HEAD
|
||||
[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.44.0...HEAD
|
||||
[1.44.0/0.66.0/0.20.0/0.0.17]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.44.0
|
||||
[1.43.0/0.65.0/0.19.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.43.0
|
||||
[1.42.0/0.64.0/0.18.0/0.0.16]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.42.0
|
||||
[1.41.0/0.63.0/0.17.0/0.0.15]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.41.0
|
||||
|
||||
+89
-12
@@ -11,6 +11,12 @@ for a summary description of past meetings. To request edit access,
|
||||
join the meeting or get in touch on
|
||||
[Slack](https://cloud-native.slack.com/archives/C01NPAXACKT).
|
||||
|
||||
The meeting is open for all to join. We invite everyone to join our
|
||||
meeting, regardless of your experience level. Whether you're a
|
||||
seasoned OpenTelemetry developer, just starting your journey, or
|
||||
simply curious about the work we do, you're more than welcome to
|
||||
participate!
|
||||
|
||||
## Development
|
||||
|
||||
You can view and edit the source code by cloning this repository:
|
||||
@@ -746,8 +752,8 @@ Encapsulate setup in constructor functions, ensuring clear ownership and scope:
|
||||
import (
|
||||
"errors"
|
||||
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.41.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.41.0/otelconv"
|
||||
)
|
||||
|
||||
type SDKComponent struct {
|
||||
@@ -808,11 +814,11 @@ func (c *Component) initObservability() {
|
||||
|
||||
#### Performance
|
||||
|
||||
When observability is disabled there should be little to no overhead.
|
||||
When observability is disabled or the instrument is not `Enabled`, there should be little to no overhead.
|
||||
|
||||
```go
|
||||
func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
|
||||
if e.inst != nil {
|
||||
if e.inst != nil && e.inst.Enabled(ctx) {
|
||||
attrs := expensiveOperation()
|
||||
e.inst.recordSpanInflight(ctx, int64(len(spans)), attrs...)
|
||||
}
|
||||
@@ -829,7 +835,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan)
|
||||
}
|
||||
|
||||
func (i *instrumentation) recordSpanInflight(ctx context.Context, count int64, attrs ...attribute.KeyValue) {
|
||||
if i == nil || i.inflight == nil {
|
||||
if i == nil || i.inflight == nil || !i.inflight.Enabled(ctx) {
|
||||
return
|
||||
}
|
||||
i.inflight.Add(ctx, count, metric.WithAttributes(attrs...))
|
||||
@@ -865,8 +871,12 @@ var (
|
||||
)
|
||||
|
||||
func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...attribute.KeyValue) {
|
||||
if !i.counter.Enabled(ctx) {
|
||||
return
|
||||
}
|
||||
attrs := attrPool.Get().(*[]attribute.KeyValue)
|
||||
defer func() {
|
||||
clear(*attrs) // Clear references to strings/etc to let GC collect them.
|
||||
*attrs = (*attrs)[:0] // Reset.
|
||||
attrPool.Put(attrs)
|
||||
}()
|
||||
@@ -877,6 +887,7 @@ func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...
|
||||
|
||||
addOpt := addOptPool.Get().(*[]metric.AddOption)
|
||||
defer func() {
|
||||
clear(*addOpt)
|
||||
*addOpt = (*addOpt)[:0]
|
||||
addOptPool.Put(addOpt)
|
||||
}()
|
||||
@@ -1007,16 +1018,20 @@ Ensure observability measurements receive the correct context, especially for tr
|
||||
```go
|
||||
func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
|
||||
// Use the provided context for observability measurements
|
||||
e.inst.recordSpanExportStarted(ctx, len(spans))
|
||||
if e.inst.Enabled(ctx) {
|
||||
e.inst.recordSpanExportStarted(ctx, len(spans))
|
||||
}
|
||||
|
||||
err := e.doExport(ctx, spans)
|
||||
|
||||
if err != nil {
|
||||
e.inst.recordSpanExportFailed(ctx, len(spans), err)
|
||||
} else {
|
||||
e.inst.recordSpanExportSucceeded(ctx, len(spans))
|
||||
if e.inst.Enabled(ctx) {
|
||||
if err != nil {
|
||||
e.inst.recordSpanExportFailed(ctx, len(spans), err)
|
||||
} else {
|
||||
e.inst.recordSpanExportSucceeded(ctx, len(spans))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return err
|
||||
}
|
||||
```
|
||||
@@ -1039,7 +1054,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan)
|
||||
|
||||
All observability metrics should follow the [OpenTelemetry Semantic Conventions for SDK metrics](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/otel/sdk-metrics.md).
|
||||
|
||||
Use the metric semantic conventions convenience package [otelconv](./semconv/v1.40.0/otelconv/metric.go).
|
||||
Use the metric semantic conventions convenience package [otelconv](./semconv/v1.41.0/otelconv/metric.go).
|
||||
|
||||
##### Component Identification
|
||||
|
||||
@@ -1109,6 +1124,68 @@ func TestObservability(t *testing.T) {
|
||||
Test order should not affect results.
|
||||
Ensure that any global state (e.g. component ID counters) is reset between tests.
|
||||
|
||||
### Experimental Features
|
||||
|
||||
To support the development of new features in the specification, we use the following patterns to implement in-development features without adding new public artifacts in stable modules.
|
||||
|
||||
#### Experimental behavior with no API artifacts
|
||||
|
||||
Features that change behavior without changing the API (e.g., exemplar collection, auto-generation of identifiers) are implemented behind a feature gate.
|
||||
The implementation resides in an `/internal/x` package and is activated through environment variables with the `OTEL_GO_X_` prefix (e.g., `OTEL_GO_X_OBSERVABILITY`).
|
||||
The feature must be documented in a `README.md` file in the `/internal/x` package.
|
||||
|
||||
#### Experimental methods on SDK-only interfaces
|
||||
|
||||
Features that require new methods on SDK interfaces are defined as a new interface in an experimental module (e.g., `go.opentelemetry.io/otel/sdk/x`).
|
||||
The SDK uses type assertions (without importing the unstable package) to check if passing types implement these experimental interfaces.
|
||||
The SDK must not depend on the experimental module.
|
||||
|
||||
#### Experimental structs, functions, or interfaces
|
||||
|
||||
Features that don't need any changes to the existing stable package are implemented in an experimental module (e.g., `go.opentelemetry.io/otel/sdk/x`).
|
||||
|
||||
#### Experimental signals and components
|
||||
|
||||
New telemetry signals (e.g., Logs before stabilization) and components (e.g. bridges) are hosted in new, unstable modules (e.g., `go.opentelemetry.io/otel/log` before 1.0.0).
|
||||
The package should have the final name it will use once stabilized (i.e. not `/x`), and is released at a v0.x.y version to indicate it is not stable.
|
||||
Most new components are hosted in [opentelemetry-go-contrib](https://github.com/open-telemetry/opentelemetry-go-contrib).
|
||||
|
||||
#### Experimental options for API or SDK functions
|
||||
|
||||
Experimental Options functions are implemented in an experimental module (e.g., `go.opentelemetry.io/otel/sdk/x`).
|
||||
The return type of the Option function must embed the option's type (e.g. `metric.InstrumentOption`), and have an `Experimental()` method to prevent the API from panicking when the option is used.
|
||||
The SDK uses type assertions (without importing the unstable package) to check if passing types implement these experimental interfaces.
|
||||
The SDK must not depend on the experimental module.
|
||||
|
||||
For example:
|
||||
|
||||
```go
|
||||
type myOption struct {
|
||||
// Embed the stable option type.
|
||||
metric.InstrumentOption
|
||||
value string
|
||||
}
|
||||
|
||||
// Experimental prevents the API from panicking when the option is used.
|
||||
func (o myOption) Experimental() {}
|
||||
|
||||
// The SDK can use type assertions to use this function.
|
||||
func (o myOption) Value() string { return o.value }
|
||||
|
||||
func WithMyOption(value string) metric.InstrumentOption {
|
||||
return myOption{value: value}
|
||||
}
|
||||
```
|
||||
|
||||
#### Not Supported
|
||||
|
||||
The following kinds of experimental features are **not currently supported** on stable interfaces:
|
||||
|
||||
- Experimental methods on API interfaces
|
||||
- Experimental fields for API or SDK exported structs
|
||||
|
||||
In some cases forks or long-lived branches may be used for prototyping these features.
|
||||
|
||||
## Approvers and Maintainers
|
||||
|
||||
### Maintainers
|
||||
|
||||
+9
-1
@@ -191,8 +191,16 @@ benchmark: $(OTEL_GO_MOD_DIRS:%=benchmark/%)
|
||||
benchmark/%:
|
||||
cd $* && $(GO) test -run='^$$' -bench=. $(ARGS) ./...
|
||||
|
||||
# sdk/metric is split into two shards to work around CodSpeed limitations.
|
||||
# See https://github.com/CodSpeedHQ/codspeed-go/issues/56
|
||||
BENCHMARK_SHARDS := $(filter-out ./sdk/metric,$(OTEL_GO_MOD_DIRS)) ./sdk/metric/root ./sdk/metric/internal
|
||||
benchmark/./sdk/metric/root:
|
||||
cd ./sdk/metric && $(GO) test -run='^$$' -bench=. $(ARGS) . ./exemplar/...
|
||||
benchmark/./sdk/metric/internal:
|
||||
cd ./sdk/metric && $(GO) test -run='^$$' -bench=. $(ARGS) ./internal/...
|
||||
|
||||
print-sharded-benchmarks:
|
||||
@echo $(OTEL_GO_MOD_DIRS) | jq -cR 'split(" ")'
|
||||
@echo $(BENCHMARK_SHARDS) | jq -cR 'split(" ")'
|
||||
|
||||
.PHONY: golangci-lint golangci-lint-fix
|
||||
golangci-lint-fix: ARGS=--fix
|
||||
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user