autoupdate support for onecloud

This commit is contained in:
Zhang Dongliang
2018-09-28 11:24:51 +08:00
parent 5f6033fcae
commit 1bf9478693
128 changed files with 3267 additions and 725 deletions

279
Gopkg.lock generated
View File

@@ -2,12 +2,49 @@
[[projects]]
digest = "1:4b94878e125f31ec67c892ecfe38c13211da40653281588598218f807ae72bf7"
digest = "1:a151d8abdc2ab0a97060ac2e7c71472dff76255d76d5e65d29dcf21cf0ae0664"
name = "github.com/360EntSecGroup-Skylar/excelize"
packages = ["."]
pruneopts = "UT"
revision = "eb62256d165607c6877ce88efbba10c119137b3d"
version = "v1.3.0"
revision = "3e004d900b103379c2d62657a3070de4a2e8585a"
version = "v1.4.0"
[[projects]]
digest = "1:402c5ecf012012f4a6ff2bcc6ee903f5280e8c27f4abaebb2319716065397304"
name = "github.com/Azure/azure-sdk-for-go"
packages = [
"services/compute/mgmt/2018-04-01/compute",
"services/compute/mgmt/2018-06-01/compute",
"services/consumption/mgmt/2018-03-31/consumption",
"services/network/mgmt/2018-06-01/network",
"services/preview/subscription/mgmt/2018-03-01-preview/subscription",
"services/resources/mgmt/2018-05-01/resources",
"services/storage/mgmt/2017-10-01/storage",
"services/storage/mgmt/2018-02-01/storage",
"storage",
"version",
]
pruneopts = "UT"
revision = "4e8cbbfb1aeab140cd0fa97fd16b64ee18c3ca6a"
version = "v19.1.0"
[[projects]]
digest = "1:b8a61bb5402d1b01ada88ccb213da33a5d29683cba5ce93813aa67d5826afe56"
name = "github.com/Azure/go-autorest"
packages = [
"autorest",
"autorest/adal",
"autorest/azure",
"autorest/azure/auth",
"autorest/date",
"autorest/to",
"autorest/validation",
"logger",
"version",
]
pruneopts = "UT"
revision = "9bc4033dd347c7f416fca46b2f42a043dc1fbdf6"
version = "v10.15.5"
[[projects]]
digest = "1:f7a3877d7116adfcdcd641f9f6ad18fc2126bd5c080d8854cc3b395a01e0b7f3"
@@ -22,15 +59,37 @@
version = "v0.6.1"
[[projects]]
digest = "1:66b8ed452b31eb9075bc53295952487c333a9cb555de57ed61f5664c058d9050"
branch = "master"
digest = "1:13cce9b5c224cb93ecbfce7495a7d8ac291a3a1cb17827fbeb593f5905902164"
name = "github.com/Microsoft/azure-vhd-utils"
packages = [
"vhdcore",
"vhdcore/bat",
"vhdcore/block",
"vhdcore/block/bitmap",
"vhdcore/common",
"vhdcore/diskstream",
"vhdcore/footer",
"vhdcore/header",
"vhdcore/header/parentlocator",
"vhdcore/reader",
"vhdcore/validator",
"vhdcore/vhdfile",
"vhdcore/writer",
]
pruneopts = "UT"
revision = "2dd43d88c85c06c55828c86159d4583db9d41fbb"
[[projects]]
digest = "1:6981402aef27693f4b2ec619117abd263fde29f8c1dfac46eef0f35038d37513"
name = "github.com/Shopify/sarama"
packages = ["."]
pruneopts = "UT"
revision = "35324cf48e33d8260e1c7c18854465a904ade249"
version = "v1.17.0"
revision = "ec843464b50d4c8b56403ec9d589cf41ea30e722"
version = "v1.19.0"
[[projects]]
digest = "1:37a8ee6652ff3c42043fa26c0930858d1a72f26928ae26e5261fe81c5f0c2e8d"
digest = "1:5e9ea5618cb3451ce312505a48a563e95ce26c9ef498cd0a8833255e5e7f5c61"
name = "github.com/aliyun/alibaba-cloud-sdk-go"
packages = [
"sdk",
@@ -44,16 +103,16 @@
"sdk/utils",
]
pruneopts = "UT"
revision = "f53c66e9cf53d68bcf063643c09cc667efa0e613"
version = "1.23.3"
revision = "e61479d8220e534e78523e75ff42f92e8d5ac6e1"
version = "1.31.0"
[[projects]]
digest = "1:fff66556e25e676b296f9f2c78853831911e6ae41d84303a9be7a534bd1c0901"
digest = "1:5a2d4da3f703696f4bec1ba1d363f50461b72934b1817c07ab0963496ed1c90d"
name = "github.com/aliyun/aliyun-oss-go-sdk"
packages = ["oss"]
pruneopts = "UT"
revision = "36bf7aa2f916f274137aedd05d1d36f6a3c0f4a6"
version = "1.9.0"
revision = "ddc87ec2145f324f91257266e657cd7fa0ff1c8c"
version = "1.9.1"
[[projects]]
digest = "1:8f5416c7f59da8600725ae1ff00a99af1da8b04c211ae6f3c8f8bcab0164f650"
@@ -95,7 +154,7 @@
version = "v0.2.2"
[[projects]]
digest = "1:40098afbdd06a76dee4b6bcb85a22fed81ac9d2ebaf775c91e558c80f57aaff1"
digest = "1:7205ab9c5433db402268526647efc47daa3236f9a85a1faba705fda12fdafd29"
name = "github.com/coredns/coredns"
packages = [
"core/dnsserver",
@@ -148,16 +207,32 @@
"request",
]
pruneopts = "UT"
revision = "2e322f6e8a54f18c6aef9c25a7c432c291a3d9f7"
version = "v1.2.0"
revision = "eb51e8bac90fac86d34c9e1cb89b04ea0936b034"
version = "v1.2.2"
[[projects]]
digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39"
digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec"
name = "github.com/davecgh/go-spew"
packages = ["spew"]
pruneopts = "UT"
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
version = "v1.1.0"
revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73"
version = "v1.1.1"
[[projects]]
digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55"
name = "github.com/dgrijalva/jwt-go"
packages = ["."]
pruneopts = "UT"
revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e"
version = "v3.2.0"
[[projects]]
branch = "master"
digest = "1:e608bc2d867c3ded40ccea5417715393a50704ac24004afa87431a0e1976e50d"
name = "github.com/dimchansky/utfbom"
packages = ["."]
pruneopts = "UT"
revision = "5448fe645cb1964ba70ac8f9f2ffe975e61a536c"
[[projects]]
branch = "master"
@@ -177,11 +252,11 @@
[[projects]]
branch = "master"
digest = "1:0448d1c1a596941c608762912fe7c865f88d9ffa45afb8af1edcf1401762bf7e"
digest = "1:79f16588b5576b1b3cd90e48d2374cc9a1a8776862d28d8fd0f23b0e15534967"
name = "github.com/eapache/go-xerial-snappy"
packages = ["."]
pruneopts = "UT"
revision = "040cc1a32f578808623071247fdbd5cc43f37f5f"
revision = "776d5712da21bc4762676d614db1d8a64f4238b0"
[[projects]]
digest = "1:444b82bfe35c83bbcaf84e310fb81a1f9ece03edfed586483c869e2c046aef69"
@@ -197,7 +272,7 @@
name = "github.com/farsightsec/golang-framestream"
packages = ["."]
pruneopts = "UT"
revision = "c06a5734334d9629b3db143d74b47eb94ea68612"
revision = "d0f7ed81b7afcc56d3c1a66a0fd26a1b609675f3"
[[projects]]
digest = "1:865079840386857c809b72ce300be7580cb50d3d3129ce11bf9aa6ca2bc1934a"
@@ -232,15 +307,16 @@
revision = "22d885f9ecc78bf4ee5d72b937e4bbcdc58e8cae"
[[projects]]
digest = "1:ab00ecdc9607692ffd5fb1ac21a9ba2d6cc95bae011f327022c0b1c323d218e2"
digest = "1:ff09f03ca12c4d23c28c596eb0738745e36c1cac111f62f64819210f40607cd2"
name = "github.com/gin-gonic/gin"
packages = [
"binding",
"json",
"render",
]
pruneopts = "UT"
revision = "d459835d2b077e44f7c9b453505ee29881d5d12d"
version = "v1.2"
revision = "b869fe1415e4b9eb52f247441830d502aece2d4d"
version = "v1.3.0"
[[projects]]
digest = "1:31a18dae27a29aa074515e43a443abfd2ba6deb6d69309d8d7ce789c45f34659"
@@ -303,7 +379,7 @@
revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998"
[[projects]]
digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260"
digest = "1:4c0989ca0bcd10799064318923b9bc2db6b4d6338dd75f3f2d86c3511aaaf5cf"
name = "github.com/golang/protobuf"
packages = [
"proto",
@@ -313,8 +389,8 @@
"ptypes/timestamp",
]
pruneopts = "UT"
revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265"
version = "v1.1.0"
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
version = "v1.2.0"
[[projects]]
branch = "master"
@@ -326,11 +402,11 @@
[[projects]]
branch = "master"
digest = "1:9887333bbef17574b1db5f9893ea137ac44107235d624408a3ac9e0b98fbb2cb"
digest = "1:0bfbe13936953a98ae3cfe8ed6670d396ad81edf069a806d2f6515d7bb6950df"
name = "github.com/google/btree"
packages = ["."]
pruneopts = "UT"
revision = "e89373fe6b4a7413d7acd6da1725b83ef713e6e4"
revision = "4030bb1f1f0c35b30ca7009e9ebd06849dd45306"
[[projects]]
branch = "master"
@@ -341,12 +417,12 @@
revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1"
[[projects]]
digest = "1:8f8811f9be822914c3a25c6a071e93beb4c805d7b026cbf298bc577bc1cc945b"
digest = "1:3a26588bc48b96825977c1b3df964f8fd842cd6860cc26370588d3563433cf11"
name = "github.com/google/uuid"
packages = ["."]
pruneopts = "UT"
revision = "064e2069ce9c359c118179501254f67d7d37ba24"
version = "0.2"
revision = "d460ce9f8df2e77fb1ba55ca87fafed96c607494"
version = "v1.0.0"
[[projects]]
digest = "1:65c4414eeb350c47b8de71110150d0ea8a281835b1f386eacaa3ad7325929c21"
@@ -377,11 +453,11 @@
[[projects]]
branch = "master"
digest = "1:62db7727ec8e026e51e1b46696e0fdf6a956a701032eca4d63e311816820717c"
digest = "1:8ec54d9488698e9db22139250bde10e35aab02c20236e4d1c1457604c2c4fe18"
name = "github.com/googollee/go-socket.io"
packages = ["."]
pruneopts = "UT"
revision = "f12da5711bc66c18a0724987fff7f4f3db35c70f"
revision = "25e1f67559cf5d0e41efbc3e0157bb952596ffc3"
[[projects]]
digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1"
@@ -482,12 +558,20 @@
version = "0.2.2"
[[projects]]
digest = "1:eaefc85d32c03e5f0c2b88ea2f79fce3d993e2c78316d21319575dd4ea9153ca"
digest = "1:3e551bbb3a7c0ab2a2bf4660e7fcad16db089fdcfbb44b0199e62838038623ea"
name = "github.com/json-iterator/go"
packages = ["."]
pruneopts = "UT"
revision = "ab8a2e0c74be9d3be70b3184d9acc634935ded82"
version = "1.1.4"
revision = "1624edc4454b8682399def8740d46db5e4362ba4"
version = "v1.1.5"
[[projects]]
branch = "master"
digest = "1:f44d34fda864bed6d6c71514cd40b2ee097e6e67f745d5d014113e1faa5af8b7"
name = "github.com/konsorten/go-windows-terminal-sequences"
packages = ["."]
pruneopts = "UT"
revision = "b729f2633dfe35f4d1d8a32385f6685610ce1cb5"
[[projects]]
branch = "master"
@@ -499,11 +583,19 @@
[[projects]]
branch = "master"
digest = "1:094e04c4742b596bce4455eb535d4e4365016b44016db76f8593211406d77299"
digest = "1:29d28429a93b076908a36420a7ecb2bf429d24c15a4b5e2c220ea00fc84b71af"
name = "github.com/kr/pty"
packages = ["."]
pruneopts = "UT"
revision = "fa756f09eeb418bf1cc6268c66ceaad9bb98f598"
revision = "db8e3cd836b82e82e0a9c8edc6896967dd31374f"
[[projects]]
digest = "1:4e878df5f4e9fd625bf9c9aac77ef7cbfa4a74c01265505527c23470c0e40300"
name = "github.com/marstr/guid"
packages = ["."]
pruneopts = "UT"
revision = "8bd9a64bf37eb297b492a4101fb28e80ac0b290f"
version = "v1.1.0"
[[projects]]
digest = "1:c658e84ad3916da105a761660dcaeb01e63416c8ec7bc62256a9b411a05fcd67"
@@ -514,12 +606,12 @@
version = "v0.0.9"
[[projects]]
digest = "1:d4d17353dbd05cb52a2a52b7fe1771883b682806f68db442b436294926bbfafb"
digest = "1:0981502f9816113c9c8c4ac301583841855c8cf4da8c72f696b3ebedf6d0e4e5"
name = "github.com/mattn/go-isatty"
packages = ["."]
pruneopts = "UT"
revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
version = "v0.0.3"
revision = "6ca4dbf54d38eea1a992b3c722a76a5d1c4cb25c"
version = "v0.0.4"
[[projects]]
branch = "master"
@@ -531,11 +623,11 @@
[[projects]]
branch = "master"
digest = "1:d775613e6db40f54d34cc8b319ee5c2df56752f9f5e55e2f6004d11684bdc8fd"
digest = "1:325f68c3bd3044dcf51d46e802136cd239817e1fb130b5f3466a4cec4dd427d3"
name = "github.com/mattn/go-tty"
packages = ["."]
pruneopts = "UT"
revision = "931426f7535ac39720c8909d70ece5a41a2502a6"
revision = "13ff1204f104d52c3f7645ec027ecbcf9026429e"
[[projects]]
digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc"
@@ -567,12 +659,12 @@
version = "v0.10.11"
[[projects]]
digest = "1:463e4140189f8194f9121ca1c7fe3b8e9e9a2ab3d949b43c835c21034927dc62"
digest = "1:b39aee4261f1ae13fdd21a0db189e0bba0f96c0f2eba77ab278428e2d3b00052"
name = "github.com/miekg/dns"
packages = ["."]
pruneopts = "UT"
revision = "5a2b9fab83ff0f8bfc99684bd5f43a37abe560f1"
version = "v1.0.8"
revision = "f4db2ca6edc3af0ee51bf332099cc480bcf3ef9d"
version = "v1.0.10"
[[projects]]
digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563"
@@ -590,6 +682,14 @@
revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd"
version = "1.0.1"
[[projects]]
branch = "master"
digest = "1:84bd7f8a2e0bcd53ddc33c3b47c34c1fe340c8632cbe928f7f8ae10ec6ecdd62"
name = "github.com/mohae/deepcopy"
packages = ["."]
pruneopts = "UT"
revision = "c48cc78d482608239f6c4c92a4abd87eb8761c90"
[[projects]]
branch = "master"
digest = "1:7aefb397a53fc437c90f0fdb3e1419c751c5a3a165ced52325d5d797edf1aca6"
@@ -650,15 +750,15 @@
version = "v2.0.1"
[[projects]]
digest = "1:29803f52611cbcc1dfe55b456e9fdac362af7248b3d29d7ea1bec0a12e71dff4"
digest = "1:4f0885b3f0dba96128a09a6f4b4231c42688fbd05f323224c6aa5adc9f4e87bf"
name = "github.com/pierrec/lz4"
packages = [
".",
"internal/xxh32",
]
pruneopts = "UT"
revision = "1958fd8fff7f115e79725b1288e0b878b3e06b00"
version = "v2.0.3"
revision = "bb6bfd13c6a262f1943c0446eb25b7f54c1fb9a2"
version = "v2.0.6"
[[projects]]
branch = "master"
@@ -666,7 +766,7 @@
name = "github.com/pkg/term"
packages = ["termios"]
pruneopts = "UT"
revision = "cda20d4ac917ad418d86e151eff439648b06185b"
revision = "bffc007b7fd5a70e20e28f5b7649bb84671ef436"
[[projects]]
digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
@@ -697,7 +797,7 @@
[[projects]]
branch = "master"
digest = "1:e469cd65badf7694aeb44874518606d93c1d59e7735d3754ad442782437d3cc3"
digest = "1:63b68062b8968092eb86bedc4e68894bd096ea6b24920faca8b9dcf451f54bb5"
name = "github.com/prometheus/common"
packages = [
"expfmt",
@@ -705,11 +805,11 @@
"model",
]
pruneopts = "UT"
revision = "7600349dcfe1abd18d72d3a1770870d9800a7801"
revision = "c7de2306084e37d54b8be01f3541a8464345e9a5"
[[projects]]
branch = "master"
digest = "1:8c49953a1414305f2ff5465147ee576dd705487c35b15918fcd4efdc0cb7a290"
digest = "1:ef1dd9945e58ee9b635273d28c0ef3fa3742a7dedc038ebe207fd63e6ce000ef"
name = "github.com/prometheus/procfs"
packages = [
".",
@@ -718,7 +818,7 @@
"xfs",
]
pruneopts = "UT"
revision = "05ee40e3a273f7245e8777337fc7b46e533a9a92"
revision = "418d78d0b9a7b7de3a6bbc8a23def624cc977bb2"
[[projects]]
branch = "master"
@@ -745,20 +845,28 @@
revision = "49a4782e9908fe098c907022a1bd7519c79803d6"
[[projects]]
digest = "1:d867dfa6751c8d7a435821ad3b736310c2ed68945d05b50fb9d23aee0540c8cc"
digest = "1:81e02c4edb639c80559c0650f9401d3e2dcc3256d1fa215382bb7c83c1db9126"
name = "github.com/shopspring/decimal"
packages = ["."]
pruneopts = "UT"
revision = "cd690d0c9e2447b1ef2a129a6b7b49077da89b8e"
version = "1.1.0"
[[projects]]
digest = "1:dc2d85c13ac22c22a1f3170a41a8e1b897fa05134aaf533f16df44f66a25b4a1"
name = "github.com/sirupsen/logrus"
packages = ["."]
pruneopts = "UT"
revision = "3e01752db0189b9157070a0e1668a620f9a85da2"
version = "v1.0.6"
revision = "a67f783a3814b8729bd2dac5780b5f78f8dbd64d"
version = "v1.1.0"
[[projects]]
digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7"
digest = "1:dab83a1bbc7ad3d7a6ba1a1cc1760f25ac38cdf7d96a5cdd55cd915a4f5ceaf9"
name = "github.com/spf13/pflag"
packages = ["."]
pruneopts = "UT"
revision = "583c0c0531f06d5278b7d917446061adc344b5cd"
version = "v1.0.1"
revision = "9a97c102cda95a86cec2345a6f09f55a939babf5"
version = "v1.0.2"
[[projects]]
digest = "1:18752d0b95816a1b777505a97f71c7467a8445b8ffb55631a7bf779f6ba4fa83"
@@ -785,7 +893,7 @@
[[projects]]
branch = "master"
digest = "1:91771429c8de08d4d9b32663ad78bfa8ee1e0a146e921d9937c117665fd0377f"
digest = "1:35f0192bdf8cdd76e1851c53e293c92c058c20870ccb0af1a292f5e64075fe40"
name = "github.com/vmware/govmomi"
packages = [
".",
@@ -805,11 +913,11 @@
"vim25/xml",
]
pruneopts = "UT"
revision = "bbd99532a768d2fe369079ceda730e30726ae1a6"
revision = "c8ddb4b2bcda00a066d84c889dbb40d1aa9f2519"
[[projects]]
branch = "master"
digest = "1:014ee502e4880ffba2a0103cefa6af78cf8767ce08bc29376e6b86cdcaa2ec06"
digest = "1:71c5989353531072eeb9547066e05bdeaaf9ef0512673bca3b4b824092d70de3"
name = "golang.org/x/crypto"
packages = [
"curve25519",
@@ -817,16 +925,18 @@
"ed25519/internal/edwards25519",
"internal/chacha20",
"internal/subtle",
"pkcs12",
"pkcs12/internal/rc2",
"poly1305",
"ssh",
"ssh/terminal",
]
pruneopts = "UT"
revision = "c126467f60eb25f8f27e5a981f32a87e3965053f"
revision = "5295e8364332db77d75fce11f1d19c053919a9c9"
[[projects]]
branch = "master"
digest = "1:c945d925a3dae287abe075a89c6b09e1015da39d350eb512bb5d01ebcd7783e7"
digest = "1:4ab551743538ce88c540073958b2fb653ca077c5d4c3d1991d86016dd38e22f6"
name = "golang.org/x/net"
packages = [
"bpf",
@@ -843,18 +953,18 @@
"trace",
]
pruneopts = "UT"
revision = "f4c29de78a2a91c00474a2e689954305c350adf9"
revision = "4dfa2610cdf3b287375bbba5b8f2a14d3b01d8de"
[[projects]]
branch = "master"
digest = "1:be95d758fc4d9216e5d41ff5b98b46938fba85ca5bc2ddc45a1b03e2bb10fe7c"
digest = "1:2c607ffa8a0a34a9acba4aba7b33d981b5a2150bfcec41b1f2ef1d791bcf6c14"
name = "golang.org/x/sys"
packages = [
"unix",
"windows",
]
pruneopts = "UT"
revision = "e072cadbbdc8dd3d3ffa82b8b4b9304c261d9311"
revision = "dad3d9fb7b6e83d0f9ac8f54670f6334c3a287b4"
[[projects]]
digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18"
@@ -892,19 +1002,19 @@
name = "google.golang.org/appengine"
packages = ["cloudsql"]
pruneopts = "UT"
revision = "b1f26356af11148e710935ed1ac8a7f5702c7612"
version = "v1.1.0"
revision = "ae0ab99deb4dc413a2b4bd6c8bdd0eb67f1e4d06"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c"
digest = "1:56b0bca90b7e5d1facf5fbdacba23e4e0ce069d25381b8e2f70ef1e7ebfb9c1a"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = "UT"
revision = "daca94659cb50e9f37c1b834680f2e46358f10b0"
revision = "0e822944c569bf5c9afd034adaa56208bd2906ac"
[[projects]]
digest = "1:3dd7996ce6bf52dec6a2f69fa43e7c4cefea1d4dfa3c8ab7a5f8a9f7434e239d"
digest = "1:ab8e92d746fb5c4c18846b0879842ac8e53b3d352449423d0924a11f1020ae1b"
name = "google.golang.org/grpc"
packages = [
".",
@@ -935,8 +1045,8 @@
"tap",
]
pruneopts = "UT"
revision = "32fb0ac620c32ba40a4626ddf94d90d12cce3455"
version = "v1.14.0"
revision = "8dea3dc473e90c8179e519d91302d0597c0ca1d1"
version = "v1.15.0"
[[projects]]
digest = "1:2655728699af00d823b0a68bd7169fd241a30c04252f456b34421908701b9c3f"
@@ -1189,6 +1299,23 @@
analyzer-version = 1
input-imports = [
"github.com/360EntSecGroup-Skylar/excelize",
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute",
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute",
"github.com/Azure/azure-sdk-for-go/services/consumption/mgmt/2018-03-31/consumption",
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network",
"github.com/Azure/azure-sdk-for-go/services/preview/subscription/mgmt/2018-03-01-preview/subscription",
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources",
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage",
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2018-02-01/storage",
"github.com/Azure/azure-sdk-for-go/storage",
"github.com/Azure/go-autorest/autorest",
"github.com/Azure/go-autorest/autorest/azure",
"github.com/Azure/go-autorest/autorest/azure/auth",
"github.com/Microsoft/azure-vhd-utils/vhdcore/block/bitmap",
"github.com/Microsoft/azure-vhd-utils/vhdcore/common",
"github.com/Microsoft/azure-vhd-utils/vhdcore/diskstream",
"github.com/Microsoft/azure-vhd-utils/vhdcore/footer",
"github.com/Microsoft/azure-vhd-utils/vhdcore/validator",
"github.com/aliyun/alibaba-cloud-sdk-go/sdk",
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors",
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests",

View File

@@ -0,0 +1,47 @@
package shell
import (
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/modules"
"yunion.io/x/onecloud/pkg/mcclient/options"
)
func init() {
type SUpdateListOptions struct {
options.BaseListOptions
Region string `help:"cloud region ID or Name"`
}
R(&SUpdateListOptions{}, "update-list", "List updates", func(s *mcclient.ClientSession, args *SUpdateListOptions) error {
// TODO filer by region
result, err := modules.Updates.List(s, nil)
if err != nil {
return err
}
printList(result, modules.Updates.GetColumns(s))
return nil
})
type SUpdatePerformOptions struct {
Cmp bool `help:"update all the compute nodes automatically"`
}
R(&SUpdatePerformOptions{}, "update-perform", "Update the Controler", func(s *mcclient.ClientSession, args *SUpdatePerformOptions) error {
params := jsonutils.NewDict()
if args.Cmp {
params.Add(jsonutils.JSONTrue, "cmp")
}
result, err := modules.Updates.List(s, nil)
if err != nil {
return err
}
modules.Updates.DoUpdate(s, params)
printList(result, modules.Updates.GetColumns(s))
return nil
})
}

View File

@@ -122,4 +122,12 @@ func NewYunionConfManager(keyword, keywordPlural string, columns, adminColumns [
adminColumns: adminColumns,
serviceType: "yunionconf"},
Keyword: keyword, KeywordPlural: keywordPlural}
}
}
func NewAutoUpdateManager(keyword, keywordPlural string, columns, adminColumns []string) ResourceManager {
return ResourceManager{
BaseManager: BaseManager{columns: columns,
adminColumns: adminColumns,
serviceType: "autoupdate"},
Keyword: keyword, KeywordPlural: keywordPlural}
}

View File

@@ -0,0 +1,31 @@
package modules
import (
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/mcclient"
)
type SUpdateManager struct {
ResourceManager
}
var (
Updates SUpdateManager
)
func (this *SUpdateManager) DoUpdate(s *mcclient.ClientSession, params jsonutils.JSONObject) (jsonutils.JSONObject, error) {
ret := jsonutils.NewDict()
this.PerformAction(s, "", "", params)
return ret, nil
}
func init() {
Updates = SUpdateManager{NewAutoUpdateManager("update", "updates",
// user view
[]string{"localVersion", "remoteVersion", "status", "updateAvailable"},
[]string{}, // admin view
)}
register(&Updates)
}

View File

@@ -6,6 +6,17 @@ install:
go:
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
os:
- linux
- osx
env:
matrix:
- GOARCH=amd64
- GOARCH=386
script:
- go vet ./...

View File

@@ -25,7 +25,6 @@ Security reports are greatly appreciated and we will publicly thank you for it.
We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Reporting other issues
A great way to contribute to the project is to send a detailed report when you
@@ -44,7 +43,7 @@ When reporting issues, always include the output of `go env`.
Also include the steps required to reproduce the problem if possible and
applicable. This information will help us review and fix your issue faster.
When sending lengthy log-files, consider posting them as a gist (https://gist.github.com).
When sending lengthy log-files, consider posting them as a gist [https://gist.github.com](https://gist.github.com).
Don't forget to remove sensitive data from your logfiles before posting (you can
replace those parts with "REDACTED").
@@ -77,9 +76,9 @@ However, there might be a way to implement that feature *on top of* excelize.
Fork the repository and make changes on your fork in a feature branch:
- If it's a bug fix branch, name it XXXX-something where XXXX is the number of
* If it's a bug fix branch, name it XXXX-something where XXXX is the number of
the issue.
- If it's a feature branch, create an enhancement issue to announce
* If it's a feature branch, create an enhancement issue to announce
your intentions, and name it XXXX-something where XXXX is the number of the
issue.
@@ -194,7 +193,7 @@ signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```
```text
Developer Certificate of Origin
Version 1.1
@@ -242,14 +241,14 @@ Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
### How can I become a maintainer?
### How can I become a maintainer
First, all maintainers have 3 things
- They share responsibility in the project's success.
- They have made a long-term, recurring time investment to improve the project.
- They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
* They share responsibility in the project's success.
* They have made a long-term, recurring time investment to improve the project.
* They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
Maintainers are often under-appreciated, because their work is harder to appreciate.
It's easy to appreciate a really cool and technically advanced feature. It's harder

View File

@@ -11,7 +11,7 @@
## Introduction
Excelize is a library written in pure Golang and providing a set of functions that allow you to write to and read from XLSX files. Support reads and writes XLSX file generated by Microsoft Excel™ 2007 and later. Support save file without losing original charts of XLSX. This library needs Go version 1.8 or later. The full API docs can be seen using go's built-in documentation tool, or online at [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) and [Chinese translation](https://xuri.me/excelize/zh_cn).
Excelize is a library written in pure Go and providing a set of functions that allow you to write to and read from XLSX files. Support reads and writes XLSX file generated by Microsoft Excel™ 2007 and later. Support save file without losing original charts of XLSX. This library needs Go version 1.8 or later. The full API docs can be seen using go's built-in documentation tool, or online at [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) and [docs reference](https://xuri.me/excelize/).
## Basic Usage

View File

@@ -11,7 +11,7 @@
## 简介
Excelize 是 Go 语言编写的用于操作 Office Excel 文档类库,基于 ECMA-376 Office OpenXML 标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的 XLSX 文档。相比较其他的开源类库Excelize 支持写入原本带有图片(表)、透视表和切片器等复杂样式的文档,还支持向 Excel 文档中插入图片与图表,并且在保存后不会丢失文档原有样式,可以应用于各类报表系统中。使用本类库要求使用的 Go 语言为 1.8 或更高版本,完整的 API 使用文档请访问 [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) 或查看 [中文翻译](https://xuri.me/excelize/zh_cn)。
Excelize 是 Go 语言编写的用于操作 Office Excel 文档类库,基于 ECMA-376 Office OpenXML 标准。可以使用它来读取、写入由 Microsoft Excel™ 2007 及以上版本创建的 XLSX 文档。相比较其他的开源类库Excelize 支持写入原本带有图片(表)、透视表和切片器等复杂样式的文档,还支持向 Excel 文档中插入图片与图表,并且在保存后不会丢失文档原有样式,可以应用于各类报表系统中。使用本类库要求使用的 Go 语言为 1.8 或更高版本,完整的 API 使用文档请访问 [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) 或查看 [参考文档](https://xuri.me/excelize/)。
## 快速上手

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -9,7 +18,18 @@ import (
"time"
)
// mergeCellsParser provides function to check merged cells in worksheet by
const (
// STCellFormulaTypeArray defined the formula is an array formula.
STCellFormulaTypeArray = "array"
// STCellFormulaTypeDataTable defined the formula is a data table formula.
STCellFormulaTypeDataTable = "dataTable"
// STCellFormulaTypeNormal defined the formula is a regular cell formula.
STCellFormulaTypeNormal = "normal"
// STCellFormulaTypeShared defined the formula is part of a shared formula.
STCellFormulaTypeShared = "shared"
)
// mergeCellsParser provides a function to check merged cells in worksheet by
// given axis.
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
axis = strings.ToUpper(axis)
@@ -23,8 +43,8 @@ func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) string {
return axis
}
// SetCellValue provides function to set value of a cell. The following shows
// the supported data types:
// SetCellValue provides a function to set value of a cell. The following
// shows the supported data types:
//
// int
// int8
@@ -72,7 +92,7 @@ func (f *File) SetCellValue(sheet, axis string, value interface{}) {
}
}
// setCellIntValue provides function to set int value of a cell.
// setCellIntValue provides a function to set int value of a cell.
func (f *File) setCellIntValue(sheet, axis string, value interface{}) {
switch value.(type) {
case int:
@@ -100,7 +120,7 @@ func (f *File) setCellIntValue(sheet, axis string, value interface{}) {
}
}
// SetCellBool provides function to set bool type value of a cell by given
// SetCellBool provides a function to set bool type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellBool(sheet, axis string, value bool) {
xlsx := f.workSheetReader(sheet)
@@ -128,10 +148,10 @@ func (f *File) SetCellBool(sheet, axis string, value bool) {
}
}
// GetCellValue provides function to get formatted value from cell by given
// worksheet name and axis in XLSX file. If it is possible to apply a format to
// the cell value, it will do so, if not then an error will be returned, along
// with the raw value of the cell.
// GetCellValue provides a function to get formatted value from cell by given
// worksheet name and axis in XLSX file. If it is possible to apply a format
// to the cell value, it will do so, if not then an error will be returned,
// along with the raw value of the cell.
func (f *File) GetCellValue(sheet, axis string) string {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
@@ -163,9 +183,9 @@ func (f *File) GetCellValue(sheet, axis string) string {
return ""
}
// formattedValue provides function to returns a value after formatted. If it is
// possible to apply a format to the cell value, it will do so, if not then an
// error will be returned, along with the raw value of the cell.
// formattedValue provides a function to returns a value after formatted. If
// it is possible to apply a format to the cell value, it will do so, if not
// then an error will be returned, along with the raw value of the cell.
func (f *File) formattedValue(s int, v string) string {
if s == 0 {
return v
@@ -178,7 +198,7 @@ func (f *File) formattedValue(s int, v string) string {
return v
}
// GetCellStyle provides function to get cell style index by given worksheet
// GetCellStyle provides a function to get cell style index by given worksheet
// name and cell coordinates.
func (f *File) GetCellStyle(sheet, axis string) int {
xlsx := f.workSheetReader(sheet)
@@ -200,8 +220,8 @@ func (f *File) GetCellStyle(sheet, axis string) int {
return f.prepareCellStyle(xlsx, cell, xlsx.SheetData.Row[xAxis].C[yAxis].S)
}
// GetCellFormula provides function to get formula from cell by given worksheet
// name and axis in XLSX file.
// GetCellFormula provides a function to get formula from cell by given
// worksheet name and axis in XLSX file.
func (f *File) GetCellFormula(sheet, axis string) string {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
@@ -224,6 +244,9 @@ func (f *File) GetCellFormula(sheet, axis string) string {
if xlsx.SheetData.Row[k].R == row {
for i := range xlsx.SheetData.Row[k].C {
if axis == xlsx.SheetData.Row[k].C[i].R {
if xlsx.SheetData.Row[k].C[i].F.T == STCellFormulaTypeShared {
return getSharedForumula(xlsx, xlsx.SheetData.Row[k].C[i].F.Si)
}
if xlsx.SheetData.Row[k].C[i].F != nil {
return xlsx.SheetData.Row[k].C[i].F.Content
}
@@ -234,7 +257,35 @@ func (f *File) GetCellFormula(sheet, axis string) string {
return ""
}
// SetCellFormula provides function to set cell formula by given string and
// getSharedForumula find a cell contains the same formula as another cell,
// the "shared" value can be used for the t attribute and the si attribute can
// be used to refer to the cell containing the formula. Two formulas are
// considered to be the same when their respective representations in
// R1C1-reference notation, are the same.
//
// Note that this function not validate ref tag to check the cell if or not in
// allow area, and always return origin shared formula.
func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
for k := range xlsx.SheetData.Row {
for i := range xlsx.SheetData.Row[k].C {
if xlsx.SheetData.Row[k].C[i].F == nil {
continue
}
if xlsx.SheetData.Row[k].C[i].F.T != STCellFormulaTypeShared {
continue
}
if xlsx.SheetData.Row[k].C[i].F.Si != si {
continue
}
if xlsx.SheetData.Row[k].C[i].F.Ref != "" {
return xlsx.SheetData.Row[k].C[i].F.Content
}
}
}
return ""
}
// SetCellFormula provides a function to set cell formula by given string and
// worksheet name.
func (f *File) SetCellFormula(sheet, axis, formula string) {
xlsx := f.workSheetReader(sheet)
@@ -263,10 +314,10 @@ func (f *File) SetCellFormula(sheet, axis, formula string) {
}
}
// SetCellHyperLink provides function to set cell hyperlink by given worksheet
// name and link URL address. LinkType defines two types of hyperlink "External"
// for web site or "Location" for moving to one of cell in this workbook. The
// below is example for external link.
// SetCellHyperLink provides a function to set cell hyperlink by given
// worksheet name and link URL address. LinkType defines two types of
// hyperlink "External" for web site or "Location" for moving to one of cell
// in this workbook. The below is example for external link.
//
// xlsx.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
// // Set underline and font color style for the cell.
@@ -299,10 +350,10 @@ func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) {
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, hyperlink)
}
// GetCellHyperLink provides function to get cell hyperlink by given worksheet
// name and axis. Boolean type value link will be ture if the cell has a
// hyperlink and the target is the address of the hyperlink. Otherwise, the
// value of link will be false and the value of the target will be a blank
// GetCellHyperLink provides a function to get cell hyperlink by given
// worksheet name and axis. Boolean type value link will be ture if the cell
// has a hyperlink and the target is the address of the hyperlink. Otherwise,
// the value of link will be false and the value of the target will be a blank
// string. For example get hyperlink of Sheet1!H6:
//
// link, target := xlsx.GetCellHyperLink("Sheet1", "H6")
@@ -327,8 +378,8 @@ func (f *File) GetCellHyperLink(sheet, axis string) (bool, string) {
return link, target
}
// MergeCell provides function to merge cells by given coordinate area and sheet
// name. For example create a merged cell of D3:E9 on Sheet1:
// MergeCell provides a function to merge cells by given coordinate area and
// sheet name. For example create a merged cell of D3:E9 on Sheet1:
//
// xlsx.MergeCell("Sheet1", "D3", "E9")
//
@@ -387,7 +438,7 @@ func (f *File) MergeCell(sheet, hcell, vcell string) {
}
}
// SetCellInt provides function to set int type value of a cell by given
// SetCellInt provides a function to set int type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellInt(sheet, axis string, value int) {
xlsx := f.workSheetReader(sheet)
@@ -411,7 +462,7 @@ func (f *File) SetCellInt(sheet, axis string, value int) {
xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
}
// prepareCellStyle provides function to prepare style index of cell in
// prepareCellStyle provides a function to prepare style index of cell in
// worksheet by given column index and style index.
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
if xlsx.Cols != nil && style == 0 {
@@ -424,8 +475,8 @@ func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
return style
}
// SetCellStr provides function to set string type value of a cell. Total number
// of characters that a cell can contain 32767 characters.
// SetCellStr provides a function to set string type value of a cell. Total
// number of characters that a cell can contain 32767 characters.
func (f *File) SetCellStr(sheet, axis, value string) {
xlsx := f.workSheetReader(sheet)
axis = f.mergeCellsParser(xlsx, axis)
@@ -460,7 +511,7 @@ func (f *File) SetCellStr(sheet, axis, value string) {
xlsx.SheetData.Row[xAxis].C[yAxis].V = value
}
// SetCellDefault provides function to set string type value of a cell as
// SetCellDefault provides a function to set string type value of a cell as
// default format without escaping the cell.
func (f *File) SetCellDefault(sheet, axis, value string) {
xlsx := f.workSheetReader(sheet)
@@ -525,7 +576,7 @@ func (f *File) SetSheetRow(sheet, axis string, slice interface{}) {
}
}
// checkCellInArea provides function to determine if a given coordinate is
// checkCellInArea provides a function to determine if a given coordinate is
// within an area.
func checkCellInArea(cell, area string) bool {
cell = strings.ToUpper(cell)

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -190,9 +199,9 @@ var (
}
)
// parseFormatChartSet provides function to parse the format settings of the
// parseFormatChartSet provides a function to parse the format settings of the
// chart with default value.
func parseFormatChartSet(formatSet string) *formatChart {
func parseFormatChartSet(formatSet string) (*formatChart, error) {
format := formatChart{
Dimension: formatChartDimension{
Width: 480,
@@ -216,8 +225,8 @@ func parseFormatChartSet(formatSet string) *formatChart {
},
ShowBlanksAs: "gap",
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AddChart provides the method to add chart in a sheet by given chart format
@@ -352,13 +361,18 @@ func parseFormatChartSet(formatSet string) *formatChart {
// minimum
//
// reverse_order: Specifies that the categories or values on reverse order (orientation of the chart). The reverse_order property is optional. The default value is false.
//
// maximum: Specifies that the fixed maximum, 0 is auto. The maximum property is optional. The default value is auto.
//
// minimum: Specifies that the fixed minimum, 0 is auto. The minimum property is optional. The default value is auto.
//
// Set chart size by dimension property. The dimension property is optional. The default width is 480, and height is 290.
//
func (f *File) AddChart(sheet, cell, format string) {
formatSet := parseFormatChartSet(format)
func (f *File) AddChart(sheet, cell, format string) error {
formatSet, err := parseFormatChartSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
@@ -371,9 +385,10 @@ func (f *File) AddChart(sheet, cell, format string) {
f.addChart(formatSet)
f.addContentTypePart(chartID, "chart")
f.addContentTypePart(drawingID, "drawings")
return err
}
// countCharts provides function to get chart files count storage in the
// countCharts provides a function to get chart files count storage in the
// folder xl/charts.
func (f *File) countCharts() int {
count := 0
@@ -385,7 +400,7 @@ func (f *File) countCharts() int {
return count
}
// prepareDrawing provides function to prepare drawing ID and XML by given
// prepareDrawing provides a function to prepare drawing ID and XML by given
// drawingID, worksheet name and default drawingXML.
func (f *File) prepareDrawing(xlsx *xlsxWorksheet, drawingID int, sheet, drawingXML string) (int, string) {
sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
@@ -402,8 +417,8 @@ func (f *File) prepareDrawing(xlsx *xlsxWorksheet, drawingID int, sheet, drawing
return drawingID, drawingXML
}
// addChart provides function to create chart as xl/charts/chart%d.xml by given
// format sets.
// addChart provides a function to create chart as xl/charts/chart%d.xml by
// given format sets.
func (f *File) addChart(formatSet *formatChart) {
count := f.countCharts()
xlsxChartSpace := xlsxChartSpace{
@@ -558,7 +573,7 @@ func (f *File) addChart(formatSet *formatChart) {
f.saveFileList(media, chart)
}
// drawBaseChart provides function to draw the c:plotArea element for bar,
// drawBaseChart provides a function to draw the c:plotArea element for bar,
// and column series charts by given format sets.
func (f *File) drawBaseChart(formatSet *formatChart) *cPlotArea {
c := cCharts{
@@ -655,7 +670,7 @@ func (f *File) drawBaseChart(formatSet *formatChart) *cPlotArea {
return charts[formatSet.Type]
}
// drawDoughnutChart provides function to draw the c:plotArea element for
// drawDoughnutChart provides a function to draw the c:plotArea element for
// doughnut chart by given format sets.
func (f *File) drawDoughnutChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
@@ -669,8 +684,8 @@ func (f *File) drawDoughnutChart(formatSet *formatChart) *cPlotArea {
}
}
// drawLineChart provides function to draw the c:plotArea element for line chart
// by given format sets.
// drawLineChart provides a function to draw the c:plotArea element for line
// chart by given format sets.
func (f *File) drawLineChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
LineChart: &cCharts{
@@ -695,8 +710,8 @@ func (f *File) drawLineChart(formatSet *formatChart) *cPlotArea {
}
}
// drawPieChart provides function to draw the c:plotArea element for pie chart
// by given format sets.
// drawPieChart provides a function to draw the c:plotArea element for pie
// chart by given format sets.
func (f *File) drawPieChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
PieChart: &cCharts{
@@ -708,8 +723,8 @@ func (f *File) drawPieChart(formatSet *formatChart) *cPlotArea {
}
}
// drawPie3DChart provides function to draw the c:plotArea element for 3D pie
// chart by given format sets.
// drawPie3DChart provides a function to draw the c:plotArea element for 3D
// pie chart by given format sets.
func (f *File) drawPie3DChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
Pie3DChart: &cCharts{
@@ -721,7 +736,7 @@ func (f *File) drawPie3DChart(formatSet *formatChart) *cPlotArea {
}
}
// drawRadarChart provides function to draw the c:plotArea element for radar
// drawRadarChart provides a function to draw the c:plotArea element for radar
// chart by given format sets.
func (f *File) drawRadarChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
@@ -744,8 +759,8 @@ func (f *File) drawRadarChart(formatSet *formatChart) *cPlotArea {
}
}
// drawScatterChart provides function to draw the c:plotArea element for scatter
// chart by given format sets.
// drawScatterChart provides a function to draw the c:plotArea element for
// scatter chart by given format sets.
func (f *File) drawScatterChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
ScatterChart: &cCharts{
@@ -767,8 +782,8 @@ func (f *File) drawScatterChart(formatSet *formatChart) *cPlotArea {
}
}
// drawChartSeries provides function to draw the c:ser element by given format
// sets.
// drawChartSeries provides a function to draw the c:ser element by given
// format sets.
func (f *File) drawChartSeries(formatSet *formatChart) *[]cSer {
ser := []cSer{}
for k := range formatSet.Series {
@@ -793,7 +808,7 @@ func (f *File) drawChartSeries(formatSet *formatChart) *[]cSer {
return &ser
}
// drawChartSeriesSpPr provides function to draw the c:spPr element by given
// drawChartSeriesSpPr provides a function to draw the c:spPr element by given
// format sets.
func (f *File) drawChartSeriesSpPr(i int, formatSet *formatChart) *cSpPr {
spPrScatter := &cSpPr{
@@ -815,8 +830,8 @@ func (f *File) drawChartSeriesSpPr(i int, formatSet *formatChart) *cSpPr {
return chartSeriesSpPr[formatSet.Type]
}
// drawChartSeriesDPt provides function to draw the c:dPt element by given data
// index and format sets.
// drawChartSeriesDPt provides a function to draw the c:dPt element by given
// data index and format sets.
func (f *File) drawChartSeriesDPt(i int, formatSet *formatChart) []*cDPt {
dpt := []*cDPt{{
IDx: &attrValInt{Val: i},
@@ -844,8 +859,8 @@ func (f *File) drawChartSeriesDPt(i int, formatSet *formatChart) []*cDPt {
return chartSeriesDPt[formatSet.Type]
}
// drawChartSeriesCat provides function to draw the c:cat element by given chart
// series and format sets.
// drawChartSeriesCat provides a function to draw the c:cat element by given
// chart series and format sets.
func (f *File) drawChartSeriesCat(v formatChartSeries, formatSet *formatChart) *cCat {
cat := &cCat{
StrRef: &cStrRef{
@@ -856,8 +871,8 @@ func (f *File) drawChartSeriesCat(v formatChartSeries, formatSet *formatChart) *
return chartSeriesCat[formatSet.Type]
}
// drawChartSeriesVal provides function to draw the c:val element by given chart
// series and format sets.
// drawChartSeriesVal provides a function to draw the c:val element by given
// chart series and format sets.
func (f *File) drawChartSeriesVal(v formatChartSeries, formatSet *formatChart) *cVal {
val := &cVal{
NumRef: &cNumRef{
@@ -868,8 +883,8 @@ func (f *File) drawChartSeriesVal(v formatChartSeries, formatSet *formatChart) *
return chartSeriesVal[formatSet.Type]
}
// drawChartSeriesMarker provides function to draw the c:marker element by given
// data index and format sets.
// drawChartSeriesMarker provides a function to draw the c:marker element by
// given data index and format sets.
func (f *File) drawChartSeriesMarker(i int, formatSet *formatChart) *cMarker {
marker := &cMarker{
Symbol: &attrValString{Val: "circle"},
@@ -894,7 +909,7 @@ func (f *File) drawChartSeriesMarker(i int, formatSet *formatChart) *cMarker {
return chartSeriesMarker[formatSet.Type]
}
// drawChartSeriesXVal provides function to draw the c:xVal element by given
// drawChartSeriesXVal provides a function to draw the c:xVal element by given
// chart series and format sets.
func (f *File) drawChartSeriesXVal(v formatChartSeries, formatSet *formatChart) *cCat {
cat := &cCat{
@@ -906,7 +921,7 @@ func (f *File) drawChartSeriesXVal(v formatChartSeries, formatSet *formatChart)
return chartSeriesXVal[formatSet.Type]
}
// drawChartSeriesYVal provides function to draw the c:yVal element by given
// drawChartSeriesYVal provides a function to draw the c:yVal element by given
// chart series and format sets.
func (f *File) drawChartSeriesYVal(v formatChartSeries, formatSet *formatChart) *cVal {
val := &cVal{
@@ -918,8 +933,8 @@ func (f *File) drawChartSeriesYVal(v formatChartSeries, formatSet *formatChart)
return chartSeriesYVal[formatSet.Type]
}
// drawChartDLbls provides function to draw the c:dLbls element by given format
// sets.
// drawChartDLbls provides a function to draw the c:dLbls element by given
// format sets.
func (f *File) drawChartDLbls(formatSet *formatChart) *cDLbls {
return &cDLbls{
ShowLegendKey: &attrValBool{Val: formatSet.Legend.ShowLegendKey},
@@ -932,15 +947,15 @@ func (f *File) drawChartDLbls(formatSet *formatChart) *cDLbls {
}
}
// drawChartSeriesDLbls provides function to draw the c:dLbls element by given
// format sets.
// drawChartSeriesDLbls provides a function to draw the c:dLbls element by
// given format sets.
func (f *File) drawChartSeriesDLbls(formatSet *formatChart) *cDLbls {
dLbls := f.drawChartDLbls(formatSet)
chartSeriesDLbls := map[string]*cDLbls{Bar: dLbls, BarStacked: dLbls, BarPercentStacked: dLbls, Bar3DClustered: dLbls, Bar3DStacked: dLbls, Bar3DPercentStacked: dLbls, Col: dLbls, ColStacked: dLbls, ColPercentStacked: dLbls, Col3DClustered: dLbls, Col3D: dLbls, Col3DStacked: dLbls, Col3DPercentStacked: dLbls, Doughnut: dLbls, Line: dLbls, Pie: dLbls, Pie3D: dLbls, Radar: dLbls, Scatter: nil}
return chartSeriesDLbls[formatSet.Type]
}
// drawPlotAreaCatAx provides function to draw the c:catAx element.
// drawPlotAreaCatAx provides a function to draw the c:catAx element.
func (f *File) drawPlotAreaCatAx(formatSet *formatChart) []*cAxs {
min := &attrValFloat{Val: formatSet.XAxis.Minimum}
max := &attrValFloat{Val: formatSet.XAxis.Maximum}
@@ -979,7 +994,7 @@ func (f *File) drawPlotAreaCatAx(formatSet *formatChart) []*cAxs {
}
}
// drawPlotAreaValAx provides function to draw the c:valAx element.
// drawPlotAreaValAx provides a function to draw the c:valAx element.
func (f *File) drawPlotAreaValAx(formatSet *formatChart) []*cAxs {
min := &attrValFloat{Val: formatSet.YAxis.Minimum}
max := &attrValFloat{Val: formatSet.YAxis.Maximum}
@@ -1015,7 +1030,7 @@ func (f *File) drawPlotAreaValAx(formatSet *formatChart) []*cAxs {
}
}
// drawPlotAreaSpPr provides function to draw the c:spPr element.
// drawPlotAreaSpPr provides a function to draw the c:spPr element.
func (f *File) drawPlotAreaSpPr() *cSpPr {
return &cSpPr{
Ln: &aLn{
@@ -1034,7 +1049,7 @@ func (f *File) drawPlotAreaSpPr() *cSpPr {
}
}
// drawPlotAreaTxPr provides function to draw the c:txPr element.
// drawPlotAreaTxPr provides a function to draw the c:txPr element.
func (f *File) drawPlotAreaTxPr() *cTxPr {
return &cTxPr{
BodyPr: aBodyPr{
@@ -1073,8 +1088,8 @@ func (f *File) drawPlotAreaTxPr() *cTxPr {
}
}
// drawingParser provides function to parse drawingXML. In order to solve the
// problem that the label structure is changed after serialization and
// drawingParser provides a function to parse drawingXML. In order to solve
// the problem that the label structure is changed after serialization and
// deserialization, two different structures: decodeWsDr and encodeWsDr are
// defined.
func (f *File) drawingParser(drawingXML string, content *xlsxWsDr) int {
@@ -1082,7 +1097,7 @@ func (f *File) drawingParser(drawingXML string, content *xlsxWsDr) int {
_, ok := f.XLSX[drawingXML]
if ok { // Append Model
decodeWsDr := decodeWsDr{}
xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
_ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
content.R = decodeWsDr.R
cNvPrID = len(decodeWsDr.OneCellAnchor) + len(decodeWsDr.TwoCellAnchor) + 1
for _, v := range decodeWsDr.OneCellAnchor {
@@ -1101,8 +1116,8 @@ func (f *File) drawingParser(drawingXML string, content *xlsxWsDr) int {
return cNvPrID
}
// addDrawingChart provides function to add chart graphic frame by given sheet,
// drawingXML, cell, width, height, relationship index and format sets.
// addDrawingChart provides a function to add chart graphic frame by given
// sheet, drawingXML, cell, width, height, relationship index and format sets.
func (f *File) addDrawingChart(sheet, drawingXML, cell string, width, height, rID int, formatSet *formatPicture) {
cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -121,8 +130,8 @@ func (f *File) SetColOutlineLevel(sheet, column string, level uint8) {
xlsx.Cols.Col = append(xlsx.Cols.Col, col)
}
// SetColWidth provides function to set the width of a single column or multiple
// columns. For example:
// SetColWidth provides a function to set the width of a single column or
// multiple columns. For example:
//
// xlsx := excelize.NewFile()
// xlsx.SetColWidth("Sheet1", "A", "H", 20)
@@ -259,8 +268,8 @@ func (f *File) positionObjectPixels(sheet string, colStart, rowStart, x1, y1, wi
return colStart, rowStart, xAbs, yAbs, colEnd, rowEnd, x2, y2
}
// getColWidth provides function to get column width in pixels by given sheet
// name and column index.
// getColWidth provides a function to get column width in pixels by given
// sheet name and column index.
func (f *File) getColWidth(sheet string, col int) int {
xlsx := f.workSheetReader(sheet)
if xlsx.Cols != nil {
@@ -278,8 +287,8 @@ func (f *File) getColWidth(sheet string, col int) int {
return int(defaultColWidthPixels)
}
// GetColWidth provides function to get column width by given worksheet name and
// column index.
// GetColWidth provides a function to get column width by given worksheet name
// and column index.
func (f *File) GetColWidth(sheet, column string) float64 {
col := TitleToNumber(strings.ToUpper(column)) + 1
xlsx := f.workSheetReader(sheet)
@@ -298,8 +307,8 @@ func (f *File) GetColWidth(sheet, column string) float64 {
return defaultColWidthPixels
}
// InsertCol provides function to insert a new column before given column index.
// For example, create a new column before column C in Sheet1:
// InsertCol provides a function to insert a new column before given column
// index. For example, create a new column before column C in Sheet1:
//
// xlsx.InsertCol("Sheet1", "C")
//
@@ -308,8 +317,8 @@ func (f *File) InsertCol(sheet, column string) {
f.adjustHelper(sheet, col, -1, 1)
}
// RemoveCol provides function to remove single column by given worksheet name
// and column index. For example, remove column C in Sheet1:
// RemoveCol provides a function to remove single column by given worksheet
// name and column index. For example, remove column C in Sheet1:
//
// xlsx.RemoveCol("Sheet1", "C")
//
@@ -346,10 +355,10 @@ func completeCol(xlsx *xlsxWorksheet, row, cell int) {
}
}
// convertColWidthToPixels provieds function to convert the width of a cell from
// user's units to pixels. Excel rounds the column width to the nearest pixel.
// If the width hasn't been set by the user we use the default value. If the
// column is hidden it has a value of zero.
// convertColWidthToPixels provieds function to convert the width of a cell
// from user's units to pixels. Excel rounds the column width to the nearest
// pixel. If the width hasn't been set by the user we use the default value.
// If the column is hidden it has a value of zero.
func convertColWidthToPixels(width float64) float64 {
var padding float64 = 5
var pixels float64

View File

@@ -1,21 +1,61 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"fmt"
"strconv"
"strings"
)
// parseFormatCommentsSet provides function to parse the format settings of the
// comment with default value.
func parseFormatCommentsSet(formatSet string) *formatComment {
// parseFormatCommentsSet provides a function to parse the format settings of
// the comment with default value.
func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
format := formatComment{
Author: "Author:",
Text: " ",
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// GetComments retrieves all comments and returns a map of worksheet name to
// the worksheet comments.
func (f *File) GetComments() (comments map[string][]Comment) {
comments = map[string][]Comment{}
for n := range f.sheetMap {
commentID := f.GetSheetIndex(n)
commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
c, ok := f.XLSX[commentsXML]
if ok {
d := xlsxComments{}
xml.Unmarshal([]byte(c), &d)
sheetComments := []Comment{}
for _, comment := range d.CommentList.Comment {
sheetComment := Comment{}
if comment.AuthorID < len(d.Authors) {
sheetComment.Author = d.Authors[comment.AuthorID].Author
}
sheetComment.Ref = comment.Ref
sheetComment.AuthorID = comment.AuthorID
for _, text := range comment.Text.R {
sheetComment.Text += text.T
}
sheetComments = append(sheetComments, sheetComment)
}
comments[n] = sheetComments
}
}
return
}
// AddComment provides the method to add comment in a sheet by given worksheet
@@ -25,8 +65,11 @@ func parseFormatCommentsSet(formatSet string) *formatComment {
//
// xlsx.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
//
func (f *File) AddComment(sheet, cell, format string) {
formatSet := parseFormatCommentsSet(format)
func (f *File) AddComment(sheet, cell, format string) error {
formatSet, err := parseFormatCommentsSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
commentID := f.countComments() + 1
@@ -46,13 +89,23 @@ func (f *File) AddComment(sheet, cell, format string) {
}
commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
f.addComment(commentsXML, cell, formatSet)
f.addDrawingVML(commentID, drawingVML, cell)
var colCount int
for i, l := range strings.Split(formatSet.Text, "\n") {
if ll := len(l); ll > colCount {
if i == 0 {
ll += len(formatSet.Author)
}
colCount = ll
}
}
f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
f.addContentTypePart(commentID, "comments")
return err
}
// addDrawingVML provides function to create comment as
// addDrawingVML provides a function to create comment as
// xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) {
col := string(strings.Map(letterOnlyMapF, cell))
row, _ := strconv.Atoi(strings.Map(intOnlyMapF, cell))
xAxis := row - 1
@@ -79,7 +132,7 @@ func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
},
VPath: &vPath{
Gradientshapeok: "t",
Connecttype: "rect",
Connecttype: "miter",
},
},
}
@@ -109,10 +162,12 @@ func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
},
ClientData: &xClientData{
ObjectType: "Note",
Anchor: "3, 15, 8, 6, 4, 54, 13, 2",
AutoFill: "False",
Row: xAxis,
Column: yAxis,
Anchor: fmt.Sprintf(
"%d, 23, %d, 0, %d, %d, %d, 5",
1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
AutoFill: "True",
Row: xAxis,
Column: yAxis,
},
}
s, _ := xml.Marshal(sp)
@@ -127,7 +182,7 @@ func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
c, ok := f.XLSX[drawingVML]
if ok {
d := decodeVmlDrawing{}
xml.Unmarshal([]byte(c), &d)
_ = xml.Unmarshal([]byte(c), &d)
for _, v := range d.Shape {
s := xlsxShape{
ID: "_x0000_s1025",
@@ -145,8 +200,8 @@ func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
f.XLSX[drawingVML] = v
}
// addComment provides function to create chart as xl/comments%d.xml by given
// cell and format sets.
// addComment provides a function to create chart as xl/comments%d.xml by
// given cell and format sets.
func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
a := formatSet.Author
t := formatSet.Text
@@ -197,7 +252,7 @@ func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
c, ok := f.XLSX[commentsXML]
if ok {
d := xlsxComments{}
xml.Unmarshal([]byte(c), &d)
_ = xml.Unmarshal([]byte(c), &d)
comments.CommentList.Comment = append(comments.CommentList.Comment, d.CommentList.Comment...)
}
comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
@@ -205,8 +260,8 @@ func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
f.saveFileList(commentsXML, v)
}
// countComments provides function to get comments files count storage in the
// folder xl.
// countComments provides a function to get comments files count storage in
// the folder xl.
func (f *File) countComments() int {
count := 0
for k := range f.XLSX {

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -8,17 +17,31 @@ import (
// timeLocationUTC defined the UTC time location.
var timeLocationUTC, _ = time.LoadLocation("UTC")
// timeToUTCTime provides function to convert time to UTC time.
// timeToUTCTime provides a function to convert time to UTC time.
func timeToUTCTime(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), timeLocationUTC)
}
// timeToExcelTime provides function to convert time to Excel time.
// timeToExcelTime provides a function to convert time to Excel time.
func timeToExcelTime(t time.Time) float64 {
return float64(t.UnixNano())/8.64e13 + 25569.0
// TODO in future this should probably also handle date1904 and like TimeFromExcelTime
var excelTime float64
var deltaDays int64
excelTime = 0
deltaDays = 290 * 364
// check if UnixNano would be out of int64 range
for t.Unix() > deltaDays*24*60*60 {
// reduce by aprox. 290 years, which is max for int64 nanoseconds
delta := time.Duration(deltaDays) * 24 * time.Hour
excelTime = excelTime + float64(deltaDays)
t = t.Add(-delta)
}
// finally add remainder of UnixNano to keep nano precision
// and 25569 which is days between 1900 and 1970
return excelTime + float64(t.UnixNano())/8.64e13 + 25569.0
}
// shiftJulianToNoon provides function to process julian date to noon.
// shiftJulianToNoon provides a function to process julian date to noon.
func shiftJulianToNoon(julianDays, julianFraction float64) (float64, float64) {
switch {
case -0.5 < julianFraction && julianFraction < 0.5:
@@ -33,7 +56,7 @@ func shiftJulianToNoon(julianDays, julianFraction float64) (float64, float64) {
return julianDays, julianFraction
}
// fractionOfADay provides function to return the integer values for hour,
// fractionOfADay provides a function to return the integer values for hour,
// minutes, seconds and nanoseconds that comprised a given fraction of a day.
// values would round to 1 us.
func fractionOfADay(fraction float64) (hours, minutes, seconds, nanoseconds int) {
@@ -54,7 +77,7 @@ func fractionOfADay(fraction float64) (hours, minutes, seconds, nanoseconds int)
return
}
// julianDateToGregorianTime provides function to convert julian date to
// julianDateToGregorianTime provides a function to convert julian date to
// gregorian time.
func julianDateToGregorianTime(part1, part2 float64) time.Time {
part1I, part1F := math.Modf(part1)
@@ -67,12 +90,12 @@ func julianDateToGregorianTime(part1, part2 float64) time.Time {
return time.Date(year, time.Month(month), day, hours, minutes, seconds, nanoseconds, time.UTC)
}
// By this point generations of programmers have repeated the algorithm sent to
// the editor of "Communications of the ACM" in 1968 (published in CACM, volume
// 11, number 10, October 1968, p.657). None of those programmers seems to have
// found it necessary to explain the constants or variable names set out by
// Henry F. Fliegel and Thomas C. Van Flandern. Maybe one day I'll buy that
// jounal and expand an explanation here - that day is not today.
// By this point generations of programmers have repeated the algorithm sent
// to the editor of "Communications of the ACM" in 1968 (published in CACM,
// volume 11, number 10, October 1968, p.657). None of those programmers seems
// to have found it necessary to explain the constants or variable names set
// out by Henry F. Fliegel and Thomas C. Van Flandern. Maybe one day I'll buy
// that jounal and expand an explanation here - that day is not today.
func doTheFliegelAndVanFlandernAlgorithm(jd int) (day, month, year int) {
l := jd + 68569
n := (4 * l) / 146097
@@ -87,9 +110,10 @@ func doTheFliegelAndVanFlandernAlgorithm(jd int) (day, month, year int) {
return d, m, y
}
// timeFromExcelTime provides function to convert an excelTime representation
// (stored as a floating point number) to a time.Time.
// timeFromExcelTime provides a function to convert an excelTime
// representation (stored as a floating point number) to a time.Time.
func timeFromExcelTime(excelTime float64, date1904 bool) time.Time {
const MDD int64 = 106750 // Max time.Duration Days, aprox. 290 years
var date time.Time
var intPart = int64(excelTime)
// Excel uses Julian dates prior to March 1st 1900, and Gregorian
@@ -113,6 +137,13 @@ func timeFromExcelTime(excelTime float64, date1904 bool) time.Time {
} else {
date = time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
}
// Duration is limited to aprox. 290 years
for intPart > MDD {
durationDays := time.Duration(MDD) * time.Hour * 24
date = date.Add(durationDays)
intPart = intPart - MDD
}
durationDays := time.Duration(intPart) * time.Hour * 24
durationPart := time.Duration(dayNanoSeconds * floatPart)
return date.Add(durationDays).Add(durationPart)

View File

@@ -1,3 +1,13 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
//
// See https://xuri.me/excelize for more information about this package.
package excelize
import (
@@ -21,6 +31,7 @@ type File struct {
Sheet map[string]*xlsxWorksheet
SheetCount int
Styles *xlsxStyleSheet
Theme *xlsxTheme
WorkBook *xlsxWorkbook
WorkBookRels *xlsxWorkbookRels
XLSX map[string][]byte
@@ -66,10 +77,11 @@ func OpenReader(r io.Reader) (*File, error) {
}
f.sheetMap = f.getSheetMap()
f.Styles = f.stylesReader()
f.Theme = f.themeReader()
return f, nil
}
// setDefaultTimeStyle provides function to set default numbers format for
// setDefaultTimeStyle provides a function to set default numbers format for
// time.Time type cell value by given worksheet name, cell coordinates and
// number format code.
func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
@@ -79,8 +91,8 @@ func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
}
}
// workSheetReader provides function to get the pointer to the structure after
// deserialization by given worksheet name.
// workSheetReader provides a function to get the pointer to the structure
// after deserialization by given worksheet name.
func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
@@ -88,7 +100,7 @@ func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
}
if f.Sheet[name] == nil {
var xlsx xlsxWorksheet
xml.Unmarshal(f.readXML(name), &xlsx)
_ = xml.Unmarshal(f.readXML(name), &xlsx)
if f.checked == nil {
f.checked = make(map[string]bool)
}
@@ -103,7 +115,7 @@ func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
return f.Sheet[name]
}
// checkSheet provides function to fill each row element and make that is
// checkSheet provides a function to fill each row element and make that is
// continuous in a worksheet of XML.
func checkSheet(xlsx *xlsxWorksheet) {
row := len(xlsx.SheetData.Row)
@@ -131,7 +143,7 @@ func checkSheet(xlsx *xlsxWorksheet) {
xlsx.SheetData = sheetData
}
// replaceWorkSheetsRelationshipsNameSpaceBytes provides function to replace
// replaceWorkSheetsRelationshipsNameSpaceBytes provides a function to replace
// xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
// Office Excel 2007.
func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
@@ -180,7 +192,7 @@ func (f *File) UpdateLinkedValue() {
}
}
// adjustHelper provides function to adjust rows and columns dimensions,
// adjustHelper provides a function to adjust rows and columns dimensions,
// hyperlinks, merged cells and auto filter when inserting or deleting rows or
// columns.
//
@@ -202,7 +214,7 @@ func (f *File) adjustHelper(sheet string, column, row, offset int) {
checkRow(xlsx)
}
// adjustColDimensions provides function to update column dimensions when
// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
for i, r := range xlsx.SheetData.Row {
@@ -218,8 +230,8 @@ func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
}
}
// adjustRowDimensions provides function to update row dimensions when inserting
// or deleting rows or columns.
// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
if rowIndex == -1 {
return
@@ -238,7 +250,7 @@ func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
}
}
// adjustHyperlinks provides function to update hyperlinks when inserting or
// adjustHyperlinks provides a function to update hyperlinks when inserting or
// deleting rows or columns.
func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
xlsx := f.workSheetReader(sheet)
@@ -278,8 +290,8 @@ func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
}
}
// adjustMergeCellsHelper provides function to update merged cells when inserting or
// deleting rows or columns.
// adjustMergeCellsHelper provides a function to update merged cells when
// inserting or deleting rows or columns.
func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
if xlsx.MergeCells != nil {
for k, v := range xlsx.MergeCells.Cells {
@@ -319,8 +331,8 @@ func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, off
}
}
// adjustMergeCells provides function to update merged cells when inserting or
// deleting rows or columns.
// adjustMergeCells provides a function to update merged cells when inserting
// or deleting rows or columns.
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
f.adjustMergeCellsHelper(xlsx, column, rowIndex, offset)
@@ -340,8 +352,8 @@ func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset in
}
}
// adjustAutoFilter provides function to update the auto filter when inserting
// or deleting rows or columns.
// adjustAutoFilter provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
f.adjustAutoFilterHelper(xlsx, column, rowIndex, offset)
@@ -374,7 +386,7 @@ func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset in
}
}
// adjustAutoFilterHelper provides function to update the auto filter when
// adjustAutoFilterHelper provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
if xlsx.AutoFilter != nil {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 53 KiB

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -8,7 +17,7 @@ import (
"os"
)
// NewFile provides function to create new file by default template. For
// NewFile provides a function to create new file by default template. For
// example:
//
// xlsx := NewFile()
@@ -36,19 +45,20 @@ func NewFile() *File {
f.WorkBookRels = f.workbookRelsReader()
f.Sheet["xl/worksheets/sheet1.xml"] = f.workSheetReader("Sheet1")
f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
f.Theme = f.themeReader()
return f
}
// Save provides function to override the xlsx file with origin path.
// Save provides a function to override the xlsx file with origin path.
func (f *File) Save() error {
if f.Path == "" {
return fmt.Errorf("No path defined for file, consider File.WriteTo or File.Write")
return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write")
}
return f.SaveAs(f.Path)
}
// SaveAs provides function to create or update to an xlsx file at the provided
// path.
// SaveAs provides a function to create or update to an xlsx file at the
// provided path.
func (f *File) SaveAs(name string) error {
file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
@@ -58,8 +68,14 @@ func (f *File) SaveAs(name string) error {
return f.Write(file)
}
// Write provides function to write to an io.Writer.
// Write provides a function to write to an io.Writer.
func (f *File) Write(w io.Writer) error {
_, err := f.WriteTo(w)
return err
}
// WriteTo implements io.WriterTo to write the file.
func (f *File) WriteTo(w io.Writer) (int64, error) {
buf := new(bytes.Buffer)
zw := zip.NewWriter(buf)
f.contentTypesWriter()
@@ -70,21 +86,17 @@ func (f *File) Write(w io.Writer) error {
for path, content := range f.XLSX {
fi, err := zw.Create(path)
if err != nil {
return err
return 0, err
}
_, err = fi.Write([]byte(content))
_, err = fi.Write(content)
if err != nil {
return err
return 0, err
}
}
err := zw.Close()
if err != nil {
return err
return 0, err
}
if _, err := buf.WriteTo(w); err != nil {
return err
}
return nil
return buf.WriteTo(w)
}

View File

@@ -1,9 +1,17 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
"archive/zip"
"bytes"
"encoding/gob"
"io"
"log"
"math"
@@ -26,7 +34,7 @@ func ReadZipReader(r *zip.Reader) (map[string][]byte, int, error) {
return fileList, worksheets, nil
}
// readXML provides function to read XML content as string.
// readXML provides a function to read XML content as string.
func (f *File) readXML(name string) []byte {
if content, ok := f.XLSX[name]; ok {
return content
@@ -34,8 +42,8 @@ func (f *File) readXML(name string) []byte {
return []byte{}
}
// saveFileList provides function to update given file content in file list of
// XLSX.
// saveFileList provides a function to update given file content in file list
// of XLSX.
func (f *File) saveFileList(name string, content []byte) {
newContent := make([]byte, 0, len(XMLHeader)+len(content))
newContent = append(newContent, []byte(XMLHeader)...)
@@ -50,12 +58,12 @@ func readFile(file *zip.File) []byte {
log.Fatal(err)
}
buff := bytes.NewBuffer(nil)
io.Copy(buff, rc)
_, _ = io.Copy(buff, rc)
rc.Close()
return buff.Bytes()
}
// ToAlphaString provides function to convert integer to Excel sheet column
// ToAlphaString provides a function to convert integer to Excel sheet column
// title. For example convert 36 to column title AK:
//
// excelize.ToAlphaString(36)
@@ -73,9 +81,9 @@ func ToAlphaString(value int) string {
return ans
}
// TitleToNumber provides function to convert Excel sheet column title to int
// (this function doesn't do value check currently). For example convert AK
// and ak to column title 36:
// TitleToNumber provides a function to convert Excel sheet column title to
// int (this function doesn't do value check currently). For example convert
// AK and ak to column title 36:
//
// excelize.TitleToNumber("AK")
// excelize.TitleToNumber("ak")
@@ -115,17 +123,6 @@ func intOnlyMapF(rune rune) rune {
return -1
}
// deepCopy provides method to creates a deep copy of whatever is passed to it
// and returns the copy in an interface. The returned value will need to be
// asserted to the correct type.
func deepCopy(dst, src interface{}) error {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(src); err != nil {
return err
}
return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
}
// boolPtr returns a pointer to a bool with the given value.
func boolPtr(b bool) *bool { return &b }
@@ -137,8 +134,8 @@ func defaultTrue(b *bool) bool {
return *b
}
// axisLowerOrEqualThan returns true if axis1 <= axis2
// axis1/axis2 can be either a column or a row axis, e.g. "A", "AAE", "42", "1", etc.
// axisLowerOrEqualThan returns true if axis1 <= axis2 axis1/axis2 can be
// either a column or a row axis, e.g. "A", "AAE", "42", "1", etc.
//
// For instance, the following comparisons are all true:
//
@@ -159,7 +156,8 @@ func axisLowerOrEqualThan(axis1, axis2 string) bool {
}
}
// getCellColRow returns the two parts of a cell identifier (its col and row) as strings
// getCellColRow returns the two parts of a cell identifier (its col and row)
// as strings
//
// For instance:
//
@@ -176,3 +174,12 @@ func getCellColRow(cell string) (col, row string) {
return cell, ""
}
// parseFormatSet provides a method to convert format string to []byte and
// handle empty string.
func parseFormatSet(formatSet string) []byte {
if formatSet != "" {
return []byte(formatSet)
}
return []byte("{}")
}

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -14,9 +23,9 @@ import (
"strings"
)
// parseFormatPictureSet provides function to parse the format settings of the
// picture with default value.
func parseFormatPictureSet(formatSet string) *formatPicture {
// parseFormatPictureSet provides a function to parse the format settings of
// the picture with default value.
func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
format := formatPicture{
FPrintsWithSheet: true,
FLocksWithSheet: false,
@@ -26,8 +35,8 @@ func parseFormatPictureSet(formatSet string) *formatPicture {
XScale: 1.0,
YScale: 1.0,
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal(parseFormatSet(formatSet), &format)
return &format, err
}
// AddPicture provides the method to add picture in a sheet by given picture
@@ -78,20 +87,66 @@ func parseFormatPictureSet(formatSet string) *formatPicture {
// positioning is move and size with cells.
func (f *File) AddPicture(sheet, cell, picture, format string) error {
var err error
var drawingHyperlinkRID int
var hyperlinkType string
// Check picture exists first.
if _, err = os.Stat(picture); os.IsNotExist(err) {
return err
}
ext, ok := supportImageTypes[path.Ext(picture)]
if !ok {
return errors.New("Unsupported image extension")
return errors.New("unsupported image extension")
}
file, _ := ioutil.ReadFile(picture)
_, name := filepath.Split(picture)
return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)
}
// AddPictureFromBytes provides the method to add picture in a sheet by given
// picture format set (such as offset, scale, aspect ratio setting and print
// settings), file base name, extension name and file bytes. For example:
//
// package main
//
// import (
// "fmt"
// _ "image/jpeg"
// "io/ioutil"
//
// "github.com/360EntSecGroup-Skylar/excelize"
// )
//
// func main() {
// xlsx := excelize.NewFile()
//
// file, err := ioutil.ReadFile("./image1.jpg")
// if err != nil {
// fmt.Println(err)
// }
// err = xlsx.AddPictureFromBytes("Sheet1", "A2", "", "Excel Logo", ".jpg", file)
// if err != nil {
// fmt.Println(err)
// }
// err = xlsx.SaveAs("./Book1.xlsx")
// if err != nil {
// fmt.Println(err)
// }
// }
//
func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
var err error
var drawingHyperlinkRID int
var hyperlinkType string
ext, ok := supportImageTypes[extension]
if !ok {
return errors.New("unsupported image extension")
}
formatSet, err := parseFormatPictureSet(format)
if err != nil {
return err
}
image, _, err := image.DecodeConfig(bytes.NewReader(file))
if err != nil {
return err
}
readFile, _ := os.Open(picture)
image, _, err := image.DecodeConfig(readFile)
_, file := filepath.Split(picture)
formatSet := parseFormatPictureSet(format)
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
@@ -107,13 +162,13 @@ func (f *File) AddPicture(sheet, cell, picture, format string) error {
}
drawingHyperlinkRID = f.addDrawingRelationships(drawingID, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
}
f.addDrawingPicture(sheet, drawingXML, cell, file, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
f.addMedia(picture, ext)
f.addDrawingPicture(sheet, drawingXML, cell, name, image.Width, image.Height, drawingRID, drawingHyperlinkRID, formatSet)
f.addMedia(file, ext)
f.addContentTypePart(drawingID, "drawings")
return err
}
// addSheetRelationships provides function to add
// addSheetRelationships provides a function to add
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name, relationship
// type and target.
func (f *File) addSheetRelationships(sheet, relType, target, targetMode string) int {
@@ -130,7 +185,7 @@ func (f *File) addSheetRelationships(sheet, relType, target, targetMode string)
_, ok = f.XLSX[rels]
if ok {
ID.Reset()
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
rID = len(sheetRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
@@ -146,9 +201,9 @@ func (f *File) addSheetRelationships(sheet, relType, target, targetMode string)
return rID
}
// deleteSheetRelationships provides function to delete relationships in
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and relationship
// index.
// deleteSheetRelationships provides a function to delete relationships in
// xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) deleteSheetRelationships(sheet, rID string) {
name, ok := f.sheetMap[trimSheetName(sheet)]
if !ok {
@@ -156,7 +211,7 @@ func (f *File) deleteSheetRelationships(sheet, rID string) {
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
for k, v := range sheetRels.Relationships {
if v.ID == rID {
sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
@@ -166,7 +221,7 @@ func (f *File) deleteSheetRelationships(sheet, rID string) {
f.saveFileList(rels, output)
}
// addSheetLegacyDrawing provides function to add legacy drawing element to
// addSheetLegacyDrawing provides a function to add legacy drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
@@ -175,7 +230,7 @@ func (f *File) addSheetLegacyDrawing(sheet string, rID int) {
}
}
// addSheetDrawing provides function to add drawing element to
// addSheetDrawing provides a function to add drawing element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetDrawing(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
@@ -184,7 +239,7 @@ func (f *File) addSheetDrawing(sheet string, rID int) {
}
}
// addSheetPicture provides function to add picture element to
// addSheetPicture provides a function to add picture element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetPicture(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
@@ -193,7 +248,7 @@ func (f *File) addSheetPicture(sheet string, rID int) {
}
}
// countDrawings provides function to get drawing files count storage in the
// countDrawings provides a function to get drawing files count storage in the
// folder xl/drawings.
func (f *File) countDrawings() int {
count := 0
@@ -205,7 +260,7 @@ func (f *File) countDrawings() int {
return count
}
// addDrawingPicture provides function to add picture by given sheet,
// addDrawingPicture provides a function to add picture by given sheet,
// drawingXML, cell, file name, width, height relationship index and format
// sets.
func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, height, rID, hyperlinkRID int, formatSet *formatPicture) {
@@ -260,8 +315,8 @@ func (f *File) addDrawingPicture(sheet, drawingXML, cell, file string, width, he
f.saveFileList(drawingXML, output)
}
// addDrawingRelationships provides function to add image part relationships in
// the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
// addDrawingRelationships provides a function to add image part relationships
// in the file xl/drawings/_rels/drawing%d.xml.rels by given drawing index,
// relationship type and target.
func (f *File) addDrawingRelationships(index int, relType, target, targetMode string) int {
var rels = "xl/drawings/_rels/drawing" + strconv.Itoa(index) + ".xml.rels"
@@ -273,7 +328,7 @@ func (f *File) addDrawingRelationships(index int, relType, target, targetMode st
_, ok := f.XLSX[rels]
if ok {
ID.Reset()
xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
rID = len(drawingRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
@@ -289,8 +344,8 @@ func (f *File) addDrawingRelationships(index int, relType, target, targetMode st
return rID
}
// countMedia provides function to get media files count storage in the folder
// xl/media/image.
// countMedia provides a function to get media files count storage in the
// folder xl/media/image.
func (f *File) countMedia() int {
count := 0
for k := range f.XLSX {
@@ -301,17 +356,16 @@ func (f *File) countMedia() int {
return count
}
// addMedia provides function to add picture into folder xl/media/image by given
// file name and extension name.
func (f *File) addMedia(file, ext string) {
// addMedia provides a function to add picture into folder xl/media/image by
// given file and extension name.
func (f *File) addMedia(file []byte, ext string) {
count := f.countMedia()
dat, _ := ioutil.ReadFile(file)
media := "xl/media/image" + strconv.Itoa(count+1) + ext
f.XLSX[media] = dat
f.XLSX[media] = file
}
// setContentTypePartImageExtensions provides function to set the content type
// for relationship parts and the Main Document part.
// setContentTypePartImageExtensions provides a function to set the content
// type for relationship parts and the Main Document part.
func (f *File) setContentTypePartImageExtensions() {
var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
content := f.contentTypesReader()
@@ -331,7 +385,7 @@ func (f *File) setContentTypePartImageExtensions() {
}
}
// setContentTypePartVMLExtensions provides function to set the content type
// setContentTypePartVMLExtensions provides a function to set the content type
// for relationship parts and the Main Document part.
func (f *File) setContentTypePartVMLExtensions() {
vml := false
@@ -349,8 +403,8 @@ func (f *File) setContentTypePartVMLExtensions() {
}
}
// addContentTypePart provides function to add content type part relationships
// in the file [Content_Types].xml by given index.
// addContentTypePart provides a function to add content type part
// relationships in the file [Content_Types].xml by given index.
func (f *File) addContentTypePart(index int, contentType string) {
setContentType := map[string]func(){
"comments": f.setContentTypePartVMLExtensions,
@@ -384,7 +438,7 @@ func (f *File) addContentTypePart(index int, contentType string) {
})
}
// getSheetRelationshipsTargetByID provides function to get Target attribute
// getSheetRelationshipsTargetByID provides a function to get Target attribute
// value in xl/worksheets/_rels/sheet%d.xml.rels by given worksheet name and
// relationship index.
func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
@@ -394,7 +448,7 @@ func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
for _, v := range sheetRels.Relationships {
if v.ID == rID {
return v.Target
@@ -403,9 +457,9 @@ func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
return ""
}
// GetPicture provides function to get picture base name and raw content embed
// in XLSX by given worksheet and cell name. This function returns the file name
// in XLSX and file contents as []byte data types. For example:
// GetPicture provides a function to get picture base name and raw content
// embed in XLSX by given worksheet and cell name. This function returns the
// file name in XLSX and file contents as []byte data types. For example:
//
// xlsx, err := excelize.OpenFile("./Book1.xlsx")
// if err != nil {
@@ -431,10 +485,10 @@ func (f *File) GetPicture(sheet, cell string) (string, []byte) {
_, ok := f.XLSX[drawingXML]
if !ok {
return "", []byte{}
return "", nil
}
decodeWsDr := decodeWsDr{}
xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
_ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))
@@ -446,7 +500,7 @@ func (f *File) GetPicture(sheet, cell string) (string, []byte) {
for _, anchor := range decodeWsDr.TwoCellAnchor {
decodeTwoCellAnchor := decodeTwoCellAnchor{}
xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
_ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
@@ -460,15 +514,16 @@ func (f *File) GetPicture(sheet, cell string) (string, []byte) {
return "", []byte{}
}
// getDrawingRelationships provides function to get drawing relationships from
// xl/drawings/_rels/drawing%s.xml.rels by given file name and relationship ID.
// getDrawingRelationships provides a function to get drawing relationships
// from xl/drawings/_rels/drawing%s.xml.rels by given file name and
// relationship ID.
func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
_, ok := f.XLSX[rels]
if !ok {
return nil
}
var drawingRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
for _, v := range drawingRels.Relationships {
if v.ID == rID {
return &v

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -31,7 +40,7 @@ func (f *File) GetRows(sheet string) [][]string {
output, _ := xml.Marshal(f.Sheet[name])
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
}
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
xml.NewDecoder(bytes.NewReader(f.readXML(name)))
d := f.sharedStringsReader()
var inElement string
var r xlsxRow
@@ -44,7 +53,7 @@ func (f *File) GetRows(sheet string) [][]string {
}
rows = append(rows, row)
}
decoder = xml.NewDecoder(bytes.NewReader(f.readXML(name)))
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
for {
token, _ := decoder.Token()
if token == nil {
@@ -55,7 +64,7 @@ func (f *File) GetRows(sheet string) [][]string {
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
decoder.DecodeElement(&r, &startElement)
_ = decoder.DecodeElement(&r, &startElement)
cr := r.R - 1
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
@@ -110,9 +119,9 @@ func (rows *Rows) Columns() []string {
}
startElement := rows.token.(xml.StartElement)
r := xlsxRow{}
rows.decoder.DecodeElement(&r, &startElement)
_ = rows.decoder.DecodeElement(&r, &startElement)
d := rows.f.sharedStringsReader()
row := make([]string, len(r.C), len(r.C))
row := make([]string, len(r.C))
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
val, _ := colCell.getValueFrom(rows.f, d)
@@ -132,7 +141,7 @@ func (err ErrSheetNotExist) Error() string {
// Rows return a rows iterator. For example:
//
// rows, err := xlsx.GetRows("Sheet1")
// rows, err := xlsx.Rows("Sheet1")
// for rows.Next() {
// for _, colCell := range rows.Columns() {
// fmt.Print(colCell, "\t")
@@ -173,7 +182,7 @@ func (f *File) getTotalRowsCols(name string) (int, int) {
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
decoder.DecodeElement(&r, &startElement)
_ = decoder.DecodeElement(&r, &startElement)
tr = r.R
for _, colCell := range r.C {
col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
@@ -202,7 +211,7 @@ func (f *File) SetRowHeight(sheet string, row int, height float64) {
xlsx.SheetData.Row[rowIdx].CustomHeight = true
}
// getRowHeight provides function to get row height in pixels by given sheet
// getRowHeight provides a function to get row height in pixels by given sheet
// name and row index.
func (f *File) getRowHeight(sheet string, row int) int {
xlsx := f.workSheetReader(sheet)
@@ -215,7 +224,7 @@ func (f *File) getRowHeight(sheet string, row int) int {
return int(defaultRowHeightPixels)
}
// GetRowHeight provides function to get row height by given worksheet name
// GetRowHeight provides a function to get row height by given worksheet name
// and row index. For example, get the height of the first row in Sheet1:
//
// xlsx.GetRowHeight("Sheet1", 1)
@@ -231,7 +240,7 @@ func (f *File) GetRowHeight(sheet string, row int) float64 {
return defaultRowHeightPixels
}
// sharedStringsReader provides function to get the pointer to the structure
// sharedStringsReader provides a function to get the pointer to the structure
// after deserialization of xl/sharedStrings.xml.
func (f *File) sharedStringsReader() *xlsxSST {
if f.SharedStrings == nil {
@@ -240,14 +249,15 @@ func (f *File) sharedStringsReader() *xlsxSST {
if len(ss) == 0 {
ss = f.readXML("xl/SharedStrings.xml")
}
xml.Unmarshal([]byte(ss), &sharedStrings)
_ = xml.Unmarshal([]byte(ss), &sharedStrings)
f.SharedStrings = &sharedStrings
}
return f.SharedStrings
}
// getValueFrom return a value from a column/row cell, this function is inteded
// to be used with for range on rows an argument with the xlsx opened file.
// getValueFrom return a value from a column/row cell, this function is
// inteded to be used with for range on rows an argument with the xlsx opened
// file.
func (xlsx *xlsxC) getValueFrom(f *File, d *xlsxSST) (string, error) {
switch xlsx.T {
case "s":
@@ -315,9 +325,9 @@ func (f *File) SetRowOutlineLevel(sheet string, rowIndex int, level uint8) {
xlsx.SheetData.Row[rowIndex].OutlineLevel = level
}
// GetRowOutlineLevel provides a function to get outline level number of a single row by given
// worksheet name and row index. For example, get outline number of row 2 in
// Sheet1:
// GetRowOutlineLevel provides a function to get outline level number of a
// single row by given worksheet name and row index. For example, get outline
// number of row 2 in Sheet1:
//
// xlsx.GetRowOutlineLevel("Sheet1", 2)
//
@@ -329,8 +339,8 @@ func (f *File) GetRowOutlineLevel(sheet string, rowIndex int) uint8 {
return xlsx.SheetData.Row[rowIndex].OutlineLevel
}
// RemoveRow provides function to remove single row by given worksheet name and
// row index. For example, remove row 3 in Sheet1:
// RemoveRow provides a function to remove single row by given worksheet name
// and row index. For example, remove row 3 in Sheet1:
//
// xlsx.RemoveRow("Sheet1", 2)
//
@@ -349,8 +359,8 @@ func (f *File) RemoveRow(sheet string, row int) {
}
}
// InsertRow provides function to insert a new row before given row index. For
// example, create a new row before row 3 in Sheet1:
// InsertRow provides a function to insert a new row before given row index.
// For example, create a new row before row 3 in Sheet1:
//
// xlsx.InsertRow("Sheet1", 2)
//
@@ -362,8 +372,8 @@ func (f *File) InsertRow(sheet string, row int) {
f.adjustHelper(sheet, -1, row, 1)
}
// checkRow provides function to check and fill each column element for all rows
// and make that is continuous in a worksheet of XML. For example:
// checkRow provides a function to check and fill each column element for all
// rows and make that is continuous in a worksheet of XML. For example:
//
// <row r="15" spans="1:22" x14ac:dyDescent="0.2">
// <c r="A15" s="2" />
@@ -416,7 +426,7 @@ func checkRow(xlsx *xlsxWorksheet) {
}
}
// completeRow provides function to check and fill each column element for a
// completeRow provides a function to check and fill each column element for a
// single row and make that is continuous in a worksheet of XML by given row
// index and axis.
func completeRow(xlsx *xlsxWorksheet, row, cell int) {
@@ -448,9 +458,9 @@ func completeRow(xlsx *xlsxWorksheet, row, cell int) {
}
}
// convertRowHeightToPixels provides function to convert the height of a cell
// from user's units to pixels. If the height hasn't been set by the user we use
// the default value. If the row is hidden it has a value of zero.
// convertRowHeightToPixels provides a function to convert the height of a
// cell from user's units to pixels. If the height hasn't been set by the user
// we use the default value. If the row is hidden it has a value of zero.
func convertRowHeightToPixels(height float64) float64 {
var pixels float64
if height == 0 {

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -7,9 +16,9 @@ import (
"strings"
)
// parseFormatShapeSet provides function to parse the format settings of the
// parseFormatShapeSet provides a function to parse the format settings of the
// shape with default value.
func parseFormatShapeSet(formatSet string) *formatShape {
func parseFormatShapeSet(formatSet string) (*formatShape, error) {
format := formatShape{
Width: 160,
Height: 160,
@@ -23,14 +32,14 @@ func parseFormatShapeSet(formatSet string) *formatShape {
YScale: 1.0,
},
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AddShape provides the method to add shape in a sheet by given worksheet
// index, shape format set (such as offset, scale, aspect ratio setting and
// print settings) and properties set. For example, add text box (rect shape) in
// Sheet1:
// print settings) and properties set. For example, add text box (rect shape)
// in Sheet1:
//
// xlsx.AddShape("Sheet1", "G6", `{"type":"rect","color":{"line":"#4286F4","fill":"#8eb9ff"},"paragraph":[{"text":"Rectangle Shape","font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777","underline":"sng"}}],"width":180,"height": 90}`)
//
@@ -245,8 +254,11 @@ func parseFormatShapeSet(formatSet string) *formatShape {
// wavyHeavy
// wavyDbl
//
func (f *File) AddShape(sheet, cell, format string) {
formatSet := parseFormatShapeSet(format)
func (f *File) AddShape(sheet, cell, format string) error {
formatSet, err := parseFormatShapeSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first shape for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
@@ -266,9 +278,10 @@ func (f *File) AddShape(sheet, cell, format string) {
}
f.addDrawingShape(sheet, drawingXML, cell, formatSet)
f.addContentTypePart(drawingID, "drawings")
return err
}
// addDrawingShape provides function to add preset geometry by given sheet,
// addDrawingShape provides a function to add preset geometry by given sheet,
// drawingXMLand format sets.
func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *formatShape) {
textUnderlineType := map[string]bool{"none": true, "words": true, "sng": true, "dbl": true, "heavy": true, "dotted": true, "dottedHeavy": true, "dash": true, "dashHeavy": true, "dashLong": true, "dashLongHeavy": true, "dotDash": true, "dotDashHeavy": true, "dotDotDash": true, "dotDotDashHeavy": true, "wavy": true, "wavyHeavy": true, "wavyDbl": true}
@@ -393,7 +406,7 @@ func (f *File) addDrawingShape(sheet, drawingXML, cell string, formatSet *format
f.saveFileList(drawingXML, output)
}
// setShapeRef provides function to set color with hex model by given actual
// setShapeRef provides a function to set color with hex model by given actual
// color value.
func setShapeRef(color string, i int) *aRef {
if color == "" {

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -5,14 +14,17 @@ import (
"encoding/json"
"encoding/xml"
"errors"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
"unicode/utf8"
"github.com/mohae/deepcopy"
)
// NewSheet provides function to create a new sheet by given worksheet name,
// NewSheet provides a function to create a new sheet by given worksheet name,
// when creating a new XLSX file, the default sheet will be create, when you
// create a new file.
func (f *File) NewSheet(name string) int {
@@ -34,18 +46,18 @@ func (f *File) NewSheet(name string) int {
return f.SheetCount
}
// contentTypesReader provides function to get the pointer to the
// contentTypesReader provides a function to get the pointer to the
// [Content_Types].xml structure after deserialization.
func (f *File) contentTypesReader() *xlsxTypes {
if f.ContentTypes == nil {
var content xlsxTypes
xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
_ = xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
f.ContentTypes = &content
}
return f.ContentTypes
}
// contentTypesWriter provides function to save [Content_Types].xml after
// contentTypesWriter provides a function to save [Content_Types].xml after
// serialize structure.
func (f *File) contentTypesWriter() {
if f.ContentTypes != nil {
@@ -54,18 +66,18 @@ func (f *File) contentTypesWriter() {
}
}
// workbookReader provides function to get the pointer to the xl/workbook.xml
// workbookReader provides a function to get the pointer to the xl/workbook.xml
// structure after deserialization.
func (f *File) workbookReader() *xlsxWorkbook {
if f.WorkBook == nil {
var content xlsxWorkbook
xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
_ = xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
f.WorkBook = &content
}
return f.WorkBook
}
// workbookWriter provides function to save xl/workbook.xml after serialize
// workbookWriter provides a function to save xl/workbook.xml after serialize
// structure.
func (f *File) workbookWriter() {
if f.WorkBook != nil {
@@ -74,7 +86,7 @@ func (f *File) workbookWriter() {
}
}
// worksheetWriter provides function to save xl/worksheets/sheet%d.xml after
// worksheetWriter provides a function to save xl/worksheets/sheet%d.xml after
// serialize structure.
func (f *File) worksheetWriter() {
for path, sheet := range f.Sheet {
@@ -92,15 +104,17 @@ func (f *File) worksheetWriter() {
}
}
// trimCell provides function to trim blank cells which created by completeCol.
// trimCell provides a function to trim blank cells which created by completeCol.
func trimCell(column []xlsxC) []xlsxC {
col := []xlsxC{}
col := make([]xlsxC, len(column))
i := 0
for _, c := range column {
if c.S != 0 || c.V != "" || c.F != nil || c.T != "" {
col = append(col, c)
col[i] = c
i++
}
}
return col
return col[0:i]
}
// Read and update property of contents type of XLSX.
@@ -128,25 +142,33 @@ func (f *File) setSheet(index int, name string) {
// allowed in sheet title.
func (f *File) setWorkbook(name string, rid int) {
content := f.workbookReader()
rID := 0
for _, v := range content.Sheets.Sheet {
t, _ := strconv.Atoi(v.SheetID)
if t > rID {
rID = t
}
}
rID++
content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
Name: trimSheetName(name),
SheetID: strconv.Itoa(rid),
SheetID: strconv.Itoa(rID),
ID: "rId" + strconv.Itoa(rid),
})
}
// workbookRelsReader provides function to read and unmarshal workbook
// workbookRelsReader provides a function to read and unmarshal workbook
// relationships of XLSX file.
func (f *File) workbookRelsReader() *xlsxWorkbookRels {
if f.WorkBookRels == nil {
var content xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
_ = xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
f.WorkBookRels = &content
}
return f.WorkBookRels
}
// workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
// workbookRelsWriter provides a function to save xl/_rels/workbook.xml.rels after
// serialize structure.
func (f *File) workbookRelsWriter() {
if f.WorkBookRels != nil {
@@ -193,19 +215,13 @@ func (f *File) setAppXML() {
// library doesn't multiple namespace declarations in a single element of a
// document. This function is a horrible hack to fix that after the XML
// marshalling is completed.
func replaceRelationshipsNameSpace(workbookMarshal string) string {
oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`
return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
}
func replaceRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
oldXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
newXmlns := []byte(`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`)
return bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
}
// SetActiveSheet provides function to set default active worksheet of XLSX by
// SetActiveSheet provides a function to set default active worksheet of XLSX by
// given index. Note that active index is different with the index that got by
// function GetSheetMap, and it should be greater than 0 and less than total
// worksheet numbers.
@@ -241,7 +257,7 @@ func (f *File) SetActiveSheet(index int) {
}
}
// GetActiveSheetIndex provides function to get active sheet of XLSX. If not
// GetActiveSheetIndex provides a function to get active sheet of XLSX. If not
// found the active sheet will be return integer 0.
func (f *File) GetActiveSheetIndex() int {
buffer := bytes.Buffer{}
@@ -251,7 +267,7 @@ func (f *File) GetActiveSheetIndex() int {
buffer.WriteString("xl/worksheets/sheet")
buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
buffer.WriteString(".xml")
xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
_ = xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
for _, sheetView := range xlsx.SheetViews.SheetView {
if sheetView.TabSelected {
ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
@@ -263,7 +279,7 @@ func (f *File) GetActiveSheetIndex() int {
return 0
}
// SetSheetName provides function to set the worksheet name be given old and new
// SetSheetName provides a function to set the worksheet name be given old and new
// worksheet name. Maximum 31 characters are allowed in sheet title and this
// function only changes the name of the sheet and will not update the sheet
// name in the formula or reference associated with the cell. So there may be
@@ -281,7 +297,7 @@ func (f *File) SetSheetName(oldName, newName string) {
}
}
// GetSheetName provides function to get worksheet name of XLSX by given
// GetSheetName provides a function to get worksheet name of XLSX by given
// worksheet index. If given sheet index is invalid, will return an empty
// string.
func (f *File) GetSheetName(index int) string {
@@ -300,7 +316,7 @@ func (f *File) GetSheetName(index int) string {
return ""
}
// GetSheetIndex provides function to get worksheet index of XLSX by given sheet
// GetSheetIndex provides a function to get worksheet index of XLSX by given sheet
// name. If given worksheet name is invalid, will return an integer type value
// 0.
func (f *File) GetSheetIndex(name string) int {
@@ -319,7 +335,7 @@ func (f *File) GetSheetIndex(name string) int {
return 0
}
// GetSheetMap provides function to get worksheet name and index map of XLSX.
// GetSheetMap provides a function to get worksheet name and index map of XLSX.
// For example:
//
// xlsx, err := excelize.OpenFile("./Book1.xlsx")
@@ -345,7 +361,7 @@ func (f *File) GetSheetMap() map[int]string {
return sheetMap
}
// getSheetMap provides function to get worksheet name and XML file path map of
// getSheetMap provides a function to get worksheet name and XML file path map of
// XLSX.
func (f *File) getSheetMap() map[string]string {
maps := make(map[string]string)
@@ -355,8 +371,8 @@ func (f *File) getSheetMap() map[string]string {
return maps
}
// SetSheetBackground provides function to set background picture by given
// worksheet name.
// SetSheetBackground provides a function to set background picture by given
// worksheet name and file path.
func (f *File) SetSheetBackground(sheet, picture string) error {
var err error
// Check picture exists first.
@@ -365,17 +381,18 @@ func (f *File) SetSheetBackground(sheet, picture string) error {
}
ext, ok := supportImageTypes[path.Ext(picture)]
if !ok {
return errors.New("Unsupported image extension")
return errors.New("unsupported image extension")
}
pictureID := f.countMedia() + 1
rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
f.addSheetPicture(sheet, rID)
f.addMedia(picture, ext)
file, _ := ioutil.ReadFile(picture)
f.addMedia(file, ext)
f.setContentTypePartImageExtensions()
return err
}
// DeleteSheet provides function to delete worksheet in a workbook by given
// DeleteSheet provides a function to delete worksheet in a workbook by given
// worksheet name. Use this method with caution, which will affect changes in
// references such as formulas, charts, and so on. If there is any referenced
// value of the deleted worksheet, it will cause a file error when you open it.
@@ -399,7 +416,7 @@ func (f *File) DeleteSheet(name string) {
f.SetActiveSheet(len(f.GetSheetMap()))
}
// deleteSheetFromWorkbookRels provides function to remove worksheet
// deleteSheetFromWorkbookRels provides a function to remove worksheet
// relationships by given relationships ID in the file
// xl/_rels/workbook.xml.rels.
func (f *File) deleteSheetFromWorkbookRels(rID string) string {
@@ -413,7 +430,7 @@ func (f *File) deleteSheetFromWorkbookRels(rID string) string {
return ""
}
// deleteSheetFromContentTypes provides function to remove worksheet
// deleteSheetFromContentTypes provides a function to remove worksheet
// relationships by given target name in the file [Content_Types].xml.
func (f *File) deleteSheetFromContentTypes(target string) {
content := f.contentTypesReader()
@@ -424,7 +441,7 @@ func (f *File) deleteSheetFromContentTypes(target string) {
}
}
// CopySheet provides function to duplicate a worksheet by gave source and
// CopySheet provides a function to duplicate a worksheet by gave source and
// target worksheet index. Note that currently doesn't support duplicate
// workbooks that contain tables, charts or pictures. For Example:
//
@@ -435,18 +452,17 @@ func (f *File) deleteSheetFromContentTypes(target string) {
//
func (f *File) CopySheet(from, to int) error {
if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
return errors.New("Invalid worksheet index")
return errors.New("invalid worksheet index")
}
f.copySheet(from, to)
return nil
}
// copySheet provides function to duplicate a worksheet by gave source and
// copySheet provides a function to duplicate a worksheet by gave source and
// target worksheet name.
func (f *File) copySheet(from, to int) {
sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
worksheet := xlsxWorksheet{}
deepCopy(&worksheet, &sheet)
worksheet := deepcopy.Copy(sheet).(*xlsxWorksheet)
path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
if len(worksheet.SheetViews.SheetView) > 0 {
worksheet.SheetViews.SheetView[0].TabSelected = false
@@ -454,7 +470,7 @@ func (f *File) copySheet(from, to int) {
worksheet.Drawing = nil
worksheet.TableParts = nil
worksheet.PageSetUp = nil
f.Sheet[path] = &worksheet
f.Sheet[path] = worksheet
toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
_, ok := f.XLSX[fromRels]
@@ -463,7 +479,7 @@ func (f *File) copySheet(from, to int) {
}
}
// SetSheetVisible provides function to set worksheet visible by given worksheet
// SetSheetVisible provides a function to set worksheet visible by given worksheet
// name. A workbook must contain at least one visible worksheet. If the given
// worksheet has been activated, this setting will be invalidated. Sheet state
// values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
@@ -505,14 +521,14 @@ func (f *File) SetSheetVisible(name string, visible bool) {
}
}
// parseFormatPanesSet provides function to parse the panes settings.
func parseFormatPanesSet(formatSet string) *formatPanes {
// parseFormatPanesSet provides a function to parse the panes settings.
func parseFormatPanesSet(formatSet string) (*formatPanes, error) {
format := formatPanes{}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// SetPanes provides function to create and remove freeze panes and split panes
// SetPanes provides a function to create and remove freeze panes and split panes
// by given worksheet name and panes format set.
//
// activePane defines the pane that is active. The possible values for this
@@ -598,7 +614,7 @@ func parseFormatPanesSet(formatSet string) *formatPanes {
// xlsx.SetPanes("Sheet1", `{"freeze":false,"split":false}`)
//
func (f *File) SetPanes(sheet, panes string) {
fs := parseFormatPanesSet(panes)
fs, _ := parseFormatPanesSet(panes)
xlsx := f.workSheetReader(sheet)
p := &xlsxPane{
ActivePane: fs.ActivePane,
@@ -626,7 +642,7 @@ func (f *File) SetPanes(sheet, panes string) {
xlsx.SheetViews.SheetView[len(xlsx.SheetViews.SheetView)-1].Selection = s
}
// GetSheetVisible provides function to get worksheet visible by given worksheet
// GetSheetVisible provides a function to get worksheet visible by given worksheet
// name. For example, get visible state of Sheet1:
//
// xlsx.GetSheetVisible("Sheet1")
@@ -644,11 +660,19 @@ func (f *File) GetSheetVisible(name string) bool {
return visible
}
// trimSheetName provides function to trim invaild characters by given worksheet
// trimSheetName provides a function to trim invaild characters by given worksheet
// name.
func trimSheetName(name string) string {
r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
name = r.Replace(name)
r := []rune{}
for _, v := range name {
switch v {
case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
continue
default:
r = append(r, v)
}
}
name = string(r)
if utf8.RuneCountInString(name) > 31 {
name = string([]rune(name)[0:31])
}

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
// SheetPrOption is an option of a view of a worksheet. See SetSheetPrOptions().
@@ -98,7 +107,7 @@ func (o *AutoPageBreaks) getSheetPrOption(pr *xlsxSheetPr) {
*o = AutoPageBreaks(pr.PageSetUpPr.AutoPageBreaks)
}
// SetSheetPrOptions provides function to sets worksheet properties.
// SetSheetPrOptions provides a function to sets worksheet properties.
//
// Available options:
// CodeName(string)
@@ -120,7 +129,7 @@ func (f *File) SetSheetPrOptions(name string, opts ...SheetPrOption) error {
return nil
}
// GetSheetPrOptions provides function to gets worksheet properties.
// GetSheetPrOptions provides a function to gets worksheet properties.
//
// Available options:
// CodeName(string)

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "fmt"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -10,8 +19,8 @@ import (
)
// Excel styles can reference number formats that are built-in, all of which
// have an id less than 164. This is a possibly incomplete list comprised of as
// many of them as I could find.
// have an id less than 164. This is a possibly incomplete list comprised of
// as many of them as I could find.
var builtInNumFmt = map[int]string{
0: "general",
1: "0",
@@ -798,45 +807,46 @@ var validType = map[string]string{
// criteriaType defined the list of valid criteria types.
var criteriaType = map[string]string{
"between": "between",
"not between": "notBetween",
"equal to": "equal",
"=": "equal",
"==": "equal",
"not equal to": "notEqual",
"!=": "notEqual",
"<>": "notEqual",
"greater than": "greaterThan",
">": "greaterThan",
"less than": "lessThan",
"<": "lessThan",
"between": "between",
"not between": "notBetween",
"equal to": "equal",
"=": "equal",
"==": "equal",
"not equal to": "notEqual",
"!=": "notEqual",
"<>": "notEqual",
"greater than": "greaterThan",
">": "greaterThan",
"less than": "lessThan",
"<": "lessThan",
"greater than or equal to": "greaterThanOrEqual",
">=": "greaterThanOrEqual",
"less than or equal to": "lessThanOrEqual",
"<=": "lessThanOrEqual",
"containing": "containsText",
"not containing": "notContains",
"begins with": "beginsWith",
"ends with": "endsWith",
"yesterday": "yesterday",
"today": "today",
"last 7 days": "last7Days",
"last week": "lastWeek",
"this week": "thisWeek",
"continue week": "continueWeek",
"last month": "lastMonth",
"this month": "thisMonth",
"continue month": "continueMonth",
">=": "greaterThanOrEqual",
"less than or equal to": "lessThanOrEqual",
"<=": "lessThanOrEqual",
"containing": "containsText",
"not containing": "notContains",
"begins with": "beginsWith",
"ends with": "endsWith",
"yesterday": "yesterday",
"today": "today",
"last 7 days": "last7Days",
"last week": "lastWeek",
"this week": "thisWeek",
"continue week": "continueWeek",
"last month": "lastMonth",
"this month": "thisMonth",
"continue month": "continueMonth",
}
// formatToString provides function to return original string by given built-in
// number formats code and cell string.
// formatToString provides a function to return original string by given
// built-in number formats code and cell string.
func formatToString(i int, v string) string {
return v
}
// formatToInt provides function to convert original string to integer format as
// string type by given built-in number formats code and cell string.
// formatToInt provides a function to convert original string to integer
// format as string type by given built-in number formats code and cell
// string.
func formatToInt(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -845,8 +855,9 @@ func formatToInt(i int, v string) string {
return fmt.Sprintf("%d", int(f))
}
// formatToFloat provides function to convert original string to float format as
// string type by given built-in number formats code and cell string.
// formatToFloat provides a function to convert original string to float
// format as string type by given built-in number formats code and cell
// string.
func formatToFloat(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -855,8 +866,8 @@ func formatToFloat(i int, v string) string {
return fmt.Sprintf("%.2f", f)
}
// formatToA provides function to convert original string to special format as
// string type by given built-in number formats code and cell string.
// formatToA provides a function to convert original string to special format
// as string type by given built-in number formats code and cell string.
func formatToA(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -870,8 +881,8 @@ func formatToA(i int, v string) string {
return fmt.Sprintf("%d", t)
}
// formatToB provides function to convert original string to special format as
// string type by given built-in number formats code and cell string.
// formatToB provides a function to convert original string to special format
// as string type by given built-in number formats code and cell string.
func formatToB(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -883,8 +894,8 @@ func formatToB(i int, v string) string {
return fmt.Sprintf("%.2f", f)
}
// formatToC provides function to convert original string to special format as
// string type by given built-in number formats code and cell string.
// formatToC provides a function to convert original string to special format
// as string type by given built-in number formats code and cell string.
func formatToC(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -894,8 +905,8 @@ func formatToC(i int, v string) string {
return fmt.Sprintf("%d%%", int(f))
}
// formatToD provides function to convert original string to special format as
// string type by given built-in number formats code and cell string.
// formatToD provides a function to convert original string to special format
// as string type by given built-in number formats code and cell string.
func formatToD(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -905,8 +916,8 @@ func formatToD(i int, v string) string {
return fmt.Sprintf("%.2f%%", f)
}
// formatToE provides function to convert original string to special format as
// string type by given built-in number formats code and cell string.
// formatToE provides a function to convert original string to special format
// as string type by given built-in number formats code and cell string.
func formatToE(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -915,17 +926,17 @@ func formatToE(i int, v string) string {
return fmt.Sprintf("%.e", f)
}
// parseTime provides function to returns a string parsed using time.Time.
// parseTime provides a function to returns a string parsed using time.Time.
// Replace Excel placeholders with Go time placeholders. For example, replace
// yyyy with 2006. These are in a specific order, due to the fact that m is used
// in month, minute, and am/pm. It would be easier to fix that with regular
// expressions, but if it's possible to keep this simple it would be easier to
// maintain. Full-length month and days (e.g. March, Tuesday) have letters in
// them that would be replaced by other characters below (such as the 'h' in
// March, or the 'd' in Tuesday) below. First we convert them to arbitrary
// characters unused in Excel Date formats, and then at the end, turn them to
// what they should actually be.
// Based off: http://www.ozgrid.com/Excel/CustomFormats.htm
// yyyy with 2006. These are in a specific order, due to the fact that m is
// used in month, minute, and am/pm. It would be easier to fix that with
// regular expressions, but if it's possible to keep this simple it would be
// easier to maintain. Full-length month and days (e.g. March, Tuesday) have
// letters in them that would be replaced by other characters below (such as
// the 'h' in March, or the 'd' in Tuesday) below. First we convert them to
// arbitrary characters unused in Excel Date formats, and then at the end,
// turn them to what they should actually be. Based off:
// http://www.ozgrid.com/Excel/CustomFormats.htm
func parseTime(i int, v string) string {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
@@ -983,18 +994,18 @@ func is12HourTime(format string) bool {
return strings.Contains(format, "am/pm") || strings.Contains(format, "AM/PM") || strings.Contains(format, "a/p") || strings.Contains(format, "A/P")
}
// stylesReader provides function to get the pointer to the structure after
// stylesReader provides a function to get the pointer to the structure after
// deserialization of xl/styles.xml.
func (f *File) stylesReader() *xlsxStyleSheet {
if f.Styles == nil {
var styleSheet xlsxStyleSheet
xml.Unmarshal([]byte(f.readXML("xl/styles.xml")), &styleSheet)
_ = xml.Unmarshal([]byte(f.readXML("xl/styles.xml")), &styleSheet)
f.Styles = &styleSheet
}
return f.Styles
}
// styleSheetWriter provides function to save xl/styles.xml after serialize
// styleSheetWriter provides a function to save xl/styles.xml after serialize
// structure.
func (f *File) styleSheetWriter() {
if f.Styles != nil {
@@ -1003,7 +1014,7 @@ func (f *File) styleSheetWriter() {
}
}
// parseFormatStyleSet provides function to parse the format settings of the
// parseFormatStyleSet provides a function to parse the format settings of the
// cells and conditional formats.
func parseFormatStyleSet(style string) (*formatStyle, error) {
format := formatStyle{
@@ -1013,8 +1024,8 @@ func parseFormatStyleSet(style string) (*formatStyle, error) {
return &format, err
}
// NewStyle provides function to create style for cells by given style format.
// Note that the color field uses RGB color code.
// NewStyle provides a function to create style for cells by given style
// format. Note that the color field uses RGB color code.
//
// The following shows the border styles sorted by excelize index number:
//
@@ -1404,7 +1415,7 @@ func parseFormatStyleSet(style string) (*formatStyle, error) {
// 173 | $ English (New Zealand)
// 174 | $ English (Singapore)
// 175 | $ English (Trinidad & Tobago)
// 176 | $ English (U.S. Vigin Islands)
// 176 | $ English (U.S. Virgin Islands)
// 177 | $ English (United States)
// 178 | $ French (Canada)
// 179 | $ Hawaiian (United States)
@@ -1906,10 +1917,10 @@ func (f *File) NewStyle(style string) (int, error) {
return cellXfsID, nil
}
// NewConditionalStyle provides function to create style for conditional format
// by given style format. The parameters are the same as function NewStyle().
// Note that the color field uses RGB color code and only support to set font,
// fills, alignment and borders currently.
// NewConditionalStyle provides a function to create style for conditional
// format by given style format. The parameters are the same as function
// NewStyle(). Note that the color field uses RGB color code and only support
// to set font, fills, alignment and borders currently.
func (f *File) NewConditionalStyle(style string) (int, error) {
s := f.stylesReader()
fs, err := parseFormatStyleSet(style)
@@ -1935,7 +1946,8 @@ func (f *File) NewConditionalStyle(style string) (int, error) {
return s.Dxfs.Count - 1, nil
}
// setFont provides function to add font style by given cell format settings.
// setFont provides a function to add font style by given cell format
// settings.
func setFont(formatStyle *formatStyle) *font {
fontUnderlineType := map[string]string{"single": "single", "double": "double"}
if formatStyle.Font.Size < 1 {
@@ -1963,8 +1975,8 @@ func setFont(formatStyle *formatStyle) *font {
return &f
}
// setNumFmt provides function to check if number format code in the range of
// built-in values.
// setNumFmt provides a function to check if number format code in the range
// of built-in values.
func setNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
dp := "0."
numFmtID := 164 // Default custom number format code from 164.
@@ -2011,7 +2023,7 @@ func setNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
return formatStyle.NumFmt
}
// setCustomNumFmt provides function to set custom number format code.
// setCustomNumFmt provides a function to set custom number format code.
func setCustomNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
nf := xlsxNumFmt{FormatCode: *formatStyle.CustomNumFmt}
if style.NumFmts != nil {
@@ -2029,7 +2041,7 @@ func setCustomNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
return nf.NumFmtID
}
// setLangNumFmt provides function to set number format code with language.
// setLangNumFmt provides a function to set number format code with language.
func setLangNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
numFmts, ok := langNumFmt[formatStyle.Lang]
if !ok {
@@ -2056,8 +2068,8 @@ func setLangNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int {
return nf.NumFmtID
}
// setFills provides function to add fill elements in the styles.xml by given
// cell format settings.
// setFills provides a function to add fill elements in the styles.xml by
// given cell format settings.
func setFills(formatStyle *formatStyle, fg bool) *xlsxFill {
var patterns = []string{
"none",
@@ -2137,9 +2149,10 @@ func setFills(formatStyle *formatStyle, fg bool) *xlsxFill {
return &fill
}
// setAlignment provides function to formatting information pertaining to text
// alignment in cells. There are a variety of choices for how text is aligned
// both horizontally and vertically, as well as indentation settings, and so on.
// setAlignment provides a function to formatting information pertaining to
// text alignment in cells. There are a variety of choices for how text is
// aligned both horizontally and vertically, as well as indentation settings,
// and so on.
func setAlignment(formatStyle *formatStyle) *xlsxAlignment {
var alignment xlsxAlignment
if formatStyle.Alignment != nil {
@@ -2156,7 +2169,7 @@ func setAlignment(formatStyle *formatStyle) *xlsxAlignment {
return &alignment
}
// setProtection provides function to set protection properties associated
// setProtection provides a function to set protection properties associated
// with the cell.
func setProtection(formatStyle *formatStyle) *xlsxProtection {
var protection xlsxProtection
@@ -2167,7 +2180,7 @@ func setProtection(formatStyle *formatStyle) *xlsxProtection {
return &protection
}
// setBorders provides function to add border elements in the styles.xml by
// setBorders provides a function to add border elements in the styles.xml by
// given borders format settings.
func setBorders(formatStyle *formatStyle) *xlsxBorder {
var styles = []string{
@@ -2219,7 +2232,7 @@ func setBorders(formatStyle *formatStyle) *xlsxBorder {
return &border
}
// setCellXfs provides function to set describes all of the formatting for a
// setCellXfs provides a function to set describes all of the formatting for a
// cell.
func setCellXfs(style *xlsxStyleSheet, fontID, numFmtID, fillID, borderID int, applyAlignment, applyProtection bool, alignment *xlsxAlignment, protection *xlsxProtection) int {
var xf xlsxXf
@@ -2246,9 +2259,10 @@ func setCellXfs(style *xlsxStyleSheet, fontID, numFmtID, fillID, borderID int, a
return style.CellXfs.Count - 1
}
// SetCellStyle provides function to add style attribute for cells by given
// SetCellStyle provides a function to add style attribute for cells by given
// worksheet name, coordinate area and style ID. Note that diagonalDown and
// diagonalUp type border should be use same color in the same coordinate area.
// diagonalUp type border should be use same color in the same coordinate
// area.
//
// For example create a borders of cell H9 on Sheet1:
//
@@ -2352,9 +2366,10 @@ func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) {
}
}
// SetConditionalFormat provides function to create conditional formatting rule
// for cell value. Conditional formatting is a feature of Excel which allows you
// to apply a format to a cell or a range of cells based on certain criteria.
// SetConditionalFormat provides a function to create conditional formatting
// rule for cell value. Conditional formatting is a feature of Excel which
// allows you to apply a format to a cell or a range of cells based on certain
// criteria.
//
// The type option is a required parameter and it has no default value.
// Allowable type values and their associated parameters are:
@@ -2407,7 +2422,7 @@ func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) {
//
// The criteria parameter is used to set the criteria by which the cell data
// will be evaluated. It has no default value. The most common criteria as
// applied to {'type': 'cell'} are:
// applied to {"type""cell"} are:
//
// between |
// not between |
@@ -2562,10 +2577,12 @@ func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) {
//
// bar_color - Used for data_bar. Same as min_color, see above.
//
func (f *File) SetConditionalFormat(sheet, area, formatSet string) {
func (f *File) SetConditionalFormat(sheet, area, formatSet string) error {
var format []*formatConditional
json.Unmarshal([]byte(formatSet), &format)
err := json.Unmarshal([]byte(formatSet), &format)
if err != nil {
return err
}
drawContFmtFunc := map[string]func(p int, ct string, fmtCond *formatConditional) *xlsxCfRule{
"cellIs": drawCondFmtCellIs,
"top10": drawCondFmtTop10,
@@ -2601,11 +2618,12 @@ func (f *File) SetConditionalFormat(sheet, area, formatSet string) {
SQRef: area,
CfRule: cfRule,
})
return err
}
// drawCondFmtCellIs provides function to create conditional formatting rule for
// cell value (include between, not between, equal, not equal, greater than and
// less than) by given priority, criteria type and format settings.
// drawCondFmtCellIs provides a function to create conditional formatting rule
// for cell value (include between, not between, equal, not equal, greater
// than and less than) by given priority, criteria type and format settings.
func drawCondFmtCellIs(p int, ct string, format *formatConditional) *xlsxCfRule {
c := &xlsxCfRule{
Priority: p + 1,
@@ -2626,8 +2644,8 @@ func drawCondFmtCellIs(p int, ct string, format *formatConditional) *xlsxCfRule
return c
}
// drawCondFmtTop10 provides function to create conditional formatting rule for
// top N (default is top 10) by given priority, criteria type and format
// drawCondFmtTop10 provides a function to create conditional formatting rule
// for top N (default is top 10) by given priority, criteria type and format
// settings.
func drawCondFmtTop10(p int, ct string, format *formatConditional) *xlsxCfRule {
c := &xlsxCfRule{
@@ -2644,9 +2662,9 @@ func drawCondFmtTop10(p int, ct string, format *formatConditional) *xlsxCfRule {
return c
}
// drawCondFmtAboveAverage provides function to create conditional formatting
// rule for above average and below average by given priority, criteria type and
// format settings.
// drawCondFmtAboveAverage provides a function to create conditional
// formatting rule for above average and below average by given priority,
// criteria type and format settings.
func drawCondFmtAboveAverage(p int, ct string, format *formatConditional) *xlsxCfRule {
return &xlsxCfRule{
Priority: p + 1,
@@ -2656,7 +2674,7 @@ func drawCondFmtAboveAverage(p int, ct string, format *formatConditional) *xlsxC
}
}
// drawCondFmtDuplicateUniqueValues provides function to create conditional
// drawCondFmtDuplicateUniqueValues provides a function to create conditional
// formatting rule for duplicate and unique values by given priority, criteria
// type and format settings.
func drawCondFmtDuplicateUniqueValues(p int, ct string, format *formatConditional) *xlsxCfRule {
@@ -2667,16 +2685,29 @@ func drawCondFmtDuplicateUniqueValues(p int, ct string, format *formatConditiona
}
}
// drawCondFmtColorScale provides function to create conditional formatting rule
// for color scale (include 2 color scale and 3 color scale) by given priority,
// criteria type and format settings.
// drawCondFmtColorScale provides a function to create conditional formatting
// rule for color scale (include 2 color scale and 3 color scale) by given
// priority, criteria type and format settings.
func drawCondFmtColorScale(p int, ct string, format *formatConditional) *xlsxCfRule {
minValue := format.MinValue
if minValue == "" {
minValue = "0"
}
maxValue := format.MaxValue
if maxValue == "" {
maxValue = "0"
}
midValue := format.MidValue
if midValue == "" {
midValue = "50"
}
c := &xlsxCfRule{
Priority: p + 1,
Type: "colorScale",
ColorScale: &xlsxColorScale{
Cfvo: []*xlsxCfvo{
{Type: format.MinType},
{Type: format.MinType, Val: minValue},
},
Color: []*xlsxColor{
{RGB: getPaletteColor(format.MinColor)},
@@ -2684,16 +2715,16 @@ func drawCondFmtColorScale(p int, ct string, format *formatConditional) *xlsxCfR
},
}
if validType[format.Type] == "3_color_scale" {
c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MidType, Val: 50})
c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MidType, Val: midValue})
c.ColorScale.Color = append(c.ColorScale.Color, &xlsxColor{RGB: getPaletteColor(format.MidColor)})
}
c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MaxType})
c.ColorScale.Cfvo = append(c.ColorScale.Cfvo, &xlsxCfvo{Type: format.MaxType, Val: maxValue})
c.ColorScale.Color = append(c.ColorScale.Color, &xlsxColor{RGB: getPaletteColor(format.MaxColor)})
return c
}
// drawCondFmtDataBar provides function to create conditional formatting rule
// for data bar by given priority, criteria type and format settings.
// drawCondFmtDataBar provides a function to create conditional formatting
// rule for data bar by given priority, criteria type and format settings.
func drawCondFmtDataBar(p int, ct string, format *formatConditional) *xlsxCfRule {
return &xlsxCfRule{
Priority: p + 1,
@@ -2705,8 +2736,8 @@ func drawCondFmtDataBar(p int, ct string, format *formatConditional) *xlsxCfRule
}
}
// drawConfFmtExp provides function to create conditional formatting rule for
// expression by given priority, criteria type and format settings.
// drawConfFmtExp provides a function to create conditional formatting rule
// for expression by given priority, criteria type and format settings.
func drawConfFmtExp(p int, ct string, format *formatConditional) *xlsxCfRule {
return &xlsxCfRule{
Priority: p + 1,
@@ -2716,7 +2747,34 @@ func drawConfFmtExp(p int, ct string, format *formatConditional) *xlsxCfRule {
}
}
// getPaletteColor provides function to convert the RBG color by given string.
// getPaletteColor provides a function to convert the RBG color by given
// string.
func getPaletteColor(color string) string {
return "FF" + strings.Replace(strings.ToUpper(color), "#", "", -1)
}
// themeReader provides a function to get the pointer to the xl/theme/theme1.xml
// structure after deserialization.
func (f *File) themeReader() *xlsxTheme {
var theme xlsxTheme
_ = xml.Unmarshal([]byte(f.readXML("xl/theme/theme1.xml")), &theme)
return &theme
}
// ThemeColor applied the color with tint value.
func ThemeColor(baseColor string, tint float64) string {
if tint == 0 {
return "FF" + baseColor
}
r, _ := strconv.ParseInt(baseColor[0:2], 16, 64)
g, _ := strconv.ParseInt(baseColor[2:4], 16, 64)
b, _ := strconv.ParseInt(baseColor[4:6], 16, 64)
h, s, l := RGBToHSL(uint8(r), uint8(g), uint8(b))
if tint < 0 {
l *= (1 + tint)
} else {
l = l*(1-tint) + (1 - (1 - tint))
}
br, bg, bb := HSLToRGB(h, s, l)
return fmt.Sprintf("FF%02X%02X%02X", br, bg, bb)
}

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import (
@@ -9,15 +18,15 @@ import (
"strings"
)
// parseFormatTableSet provides function to parse the format settings of the
// parseFormatTableSet provides a function to parse the format settings of the
// table with default value.
func parseFormatTableSet(formatSet string) *formatTable {
func parseFormatTableSet(formatSet string) (*formatTable, error) {
format := formatTable{
TableStyle: "",
ShowRowStripes: true,
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal(parseFormatSet(formatSet), &format)
return &format, err
}
// AddTable provides the method to add table in a worksheet by given worksheet
@@ -41,8 +50,11 @@ func parseFormatTableSet(formatSet string) *formatTable {
// TableStyleMedium1 - TableStyleMedium28
// TableStyleDark1 - TableStyleDark11
//
func (f *File) AddTable(sheet, hcell, vcell, format string) {
formatSet := parseFormatTableSet(format)
func (f *File) AddTable(sheet, hcell, vcell, format string) error {
formatSet, err := parseFormatTableSet(format)
if err != nil {
return err
}
hcell = strings.ToUpper(hcell)
vcell = strings.ToUpper(vcell)
// Coordinate conversion, convert C1:B3 to 2,0,1,2.
@@ -69,10 +81,11 @@ func (f *File) AddTable(sheet, hcell, vcell, format string) {
f.addSheetTable(sheet, rID)
f.addTable(sheet, tableXML, hxAxis, hyAxis, vxAxis, vyAxis, tableID, formatSet)
f.addContentTypePart(tableID, "table")
return err
}
// countTables provides function to get table files count storage in the folder
// xl/tables.
// countTables provides a function to get table files count storage in the
// folder xl/tables.
func (f *File) countTables() int {
count := 0
for k := range f.XLSX {
@@ -83,7 +96,7 @@ func (f *File) countTables() int {
return count
}
// addSheetTable provides function to add tablePart element to
// addSheetTable provides a function to add tablePart element to
// xl/worksheets/sheet%d.xml by given worksheet name and relationship index.
func (f *File) addSheetTable(sheet string, rID int) {
xlsx := f.workSheetReader(sheet)
@@ -97,8 +110,8 @@ func (f *File) addSheetTable(sheet string, rID int) {
xlsx.TableParts.TableParts = append(xlsx.TableParts.TableParts, table)
}
// addTable provides function to add table by given worksheet name, coordinate
// area and format set.
// addTable provides a function to add table by given worksheet name,
// coordinate area and format set.
func (f *File) addTable(sheet, tableXML string, hxAxis, hyAxis, vxAxis, vyAxis, i int, formatSet *formatTable) {
// Correct the minimum number of rows, the table at least two lines.
if hyAxis == vyAxis {
@@ -153,12 +166,12 @@ func (f *File) addTable(sheet, tableXML string, hxAxis, hyAxis, vxAxis, vyAxis,
f.saveFileList(tableXML, table)
}
// parseAutoFilterSet provides function to parse the settings of the auto
// parseAutoFilterSet provides a function to parse the settings of the auto
// filter.
func parseAutoFilterSet(formatSet string) *formatAutoFilter {
func parseAutoFilterSet(formatSet string) (*formatAutoFilter, error) {
format := formatAutoFilter{}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AutoFilter provides the method to add auto filter in a worksheet by given
@@ -232,7 +245,8 @@ func parseAutoFilterSet(formatSet string) *formatAutoFilter {
// Price < 2000
//
func (f *File) AutoFilter(sheet, hcell, vcell, format string) error {
formatSet := parseAutoFilterSet(format)
formatSet, _ := parseAutoFilterSet(format)
hcell = strings.ToUpper(hcell)
vcell = strings.ToUpper(vcell)
@@ -256,11 +270,10 @@ func (f *File) AutoFilter(sheet, hcell, vcell, format string) error {
}
ref := ToAlphaString(hxAxis) + strconv.Itoa(hyAxis+1) + ":" + ToAlphaString(vxAxis) + strconv.Itoa(vyAxis+1)
refRange := vxAxis - hxAxis
err := f.autoFilter(sheet, ref, refRange, hxAxis, formatSet)
return err
return f.autoFilter(sheet, ref, refRange, hxAxis, formatSet)
}
// autoFilter provides function to extract the tokens from the filter
// autoFilter provides a function to extract the tokens from the filter
// expression. The tokens are mainly non-whitespace groups.
func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *formatAutoFilter) error {
xlsx := f.workSheetReader(sheet)
@@ -278,7 +291,7 @@ func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *fo
col := TitleToNumber(formatSet.Column)
offset := col - hxAxis
if offset < 0 || offset > refRange {
return fmt.Errorf("Incorrect index of column '%s'", formatSet.Column)
return fmt.Errorf("incorrect index of column '%s'", formatSet.Column)
}
filter.FilterColumn = &xlsxFilterColumn{
ColID: offset,
@@ -286,7 +299,7 @@ func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *fo
re := regexp.MustCompile(`"(?:[^"]|"")*"|\S+`)
token := re.FindAllString(formatSet.Expression, -1)
if len(token) != 3 && len(token) != 7 {
return fmt.Errorf("Incorrect number of tokens in criteria '%s'", formatSet.Expression)
return fmt.Errorf("incorrect number of tokens in criteria '%s'", formatSet.Expression)
}
expressions, tokens, err := f.parseFilterExpression(formatSet.Expression, token)
if err != nil {
@@ -297,8 +310,8 @@ func (f *File) autoFilter(sheet, ref string, refRange, hxAxis int, formatSet *fo
return nil
}
// writeAutoFilter provides function to check for single or double custom filters
// as default filters and handle them accordingly.
// writeAutoFilter provides a function to check for single or double custom
// filters as default filters and handle them accordingly.
func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []string) {
if len(exp) == 1 && exp[0] == 2 {
// Single equality.
@@ -325,7 +338,7 @@ func (f *File) writeAutoFilter(filter *xlsxAutoFilter, exp []int, tokens []strin
}
}
// writeCustomFilter provides function to write the <customFilter> element.
// writeCustomFilter provides a function to write the <customFilter> element.
func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val string) {
operators := map[int]string{
1: "lessThan",
@@ -349,8 +362,9 @@ func (f *File) writeCustomFilter(filter *xlsxAutoFilter, operator int, val strin
}
}
// parseFilterExpression provides function to converts the tokens of a possibly
// conditional expression into 1 or 2 sub expressions for further parsing.
// parseFilterExpression provides a function to converts the tokens of a
// possibly conditional expression into 1 or 2 sub expressions for further
// parsing.
//
// Examples:
//
@@ -390,7 +404,7 @@ func (f *File) parseFilterExpression(expression string, tokens []string) ([]int,
return expressions, t, nil
}
// parseFilterTokens provides function to parse the 3 tokens of a filter
// parseFilterTokens provides a function to parse the 3 tokens of a filter
// expression and return the operator and token.
func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, string, error) {
operators := map[string]int{
@@ -410,7 +424,7 @@ func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, str
operator, ok := operators[strings.ToLower(tokens[1])]
if !ok {
// Convert the operator from a number to a descriptive string.
return []int{}, "", fmt.Errorf("Unknown operator: %s", tokens[1])
return []int{}, "", fmt.Errorf("unknown operator: %s", tokens[1])
}
token := tokens[2]
// Special handling for Blanks/NonBlanks.
@@ -418,7 +432,7 @@ func (f *File) parseFilterTokens(expression string, tokens []string) ([]int, str
if re {
// Only allow Equals or NotEqual in this context.
if operator != 2 && operator != 5 {
return []int{operator}, token, fmt.Errorf("The operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression)
return []int{operator}, token, fmt.Errorf("the operator '%s' in expression '%s' is not valid in relation to Blanks/NonBlanks'", tokens[1], expression)
}
token = strings.ToLower(token)
// The operator should always be 2 (=) to flag a "simple" equality in

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
//
// This file contains default templates for XML files we don't yet populated
// based on content.
@@ -7,10 +16,12 @@ package excelize
const XMLHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
var (
// XMLHeaderByte define an XML declaration can also contain a standalone
// declaration.
XMLHeaderByte = []byte(XMLHeader)
)
const templateDocpropsApp = `<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><TotalTime>0</TotalTime><Application>Golang Excelize</Application></Properties>`
const templateDocpropsApp = `<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><TotalTime>0</TotalTime><Application>Go Excelize</Application></Properties>`
const templateContentTypes = `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>`

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"
@@ -53,3 +62,11 @@ type formatComment struct {
Author string `json:"author"`
Text string `json:"text"`
}
// Comment directly maps the comment information.
type Comment struct {
Author string `json:"author"`
AuthorID int `json:"author_id"`
Ref string `json:"ref"`
Text string `json:"text"`
}

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"

View File

@@ -1,3 +1,12 @@
// Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.8 or later.
package excelize
import "encoding/xml"
@@ -18,7 +27,7 @@ type xlsxWorksheet struct {
MergeCells *xlsxMergeCells `xml:"mergeCells"`
PhoneticPr *xlsxPhoneticPr `xml:"phoneticPr"`
ConditionalFormatting []*xlsxConditionalFormatting `xml:"conditionalFormatting"`
DataValidations *xlsxDataValidations `xml:"dataValidations"`
DataValidations *xlsxDataValidations `xml:"dataValidations,omitempty"`
Hyperlinks *xlsxHyperlinks `xml:"hyperlinks"`
PrintOptions *xlsxPrintOptions `xml:"printOptions"`
PageMargins *xlsxPageMargins `xml:"pageMargins"`
@@ -294,11 +303,30 @@ type xlsxMergeCells struct {
// xlsxDataValidations expresses all data validation information for cells in a
// sheet which have data validation features applied.
type xlsxDataValidations struct {
Count int `xml:"count,attr,omitempty"`
DisablePrompts bool `xml:"disablePrompts,attr,omitempty"`
XWindow int `xml:"xWindow,attr,omitempty"`
YWindow int `xml:"yWindow,attr,omitempty"`
DataValidation string `xml:",innerxml"`
Count int `xml:"count,attr,omitempty"`
DisablePrompts bool `xml:"disablePrompts,attr,omitempty"`
XWindow int `xml:"xWindow,attr,omitempty"`
YWindow int `xml:"yWindow,attr,omitempty"`
DataValidation []*DataValidation `xml:"dataValidation"`
}
// DataValidation directly maps the a single item of data validation defined
// on a range of the worksheet.
type DataValidation struct {
AllowBlank bool `xml:"allowBlank,attr"`
Error *string `xml:"error,attr"`
ErrorStyle *string `xml:"errorStyle,attr"`
ErrorTitle *string `xml:"errorTitle,attr"`
Operator string `xml:"operator,attr"`
Prompt *string `xml:"prompt,attr"`
PromptTitle *string `xml:"promptTitle"`
ShowDropDown bool `xml:"showDropDown,attr"`
ShowErrorMessage bool `xml:"showErrorMessage,attr"`
ShowInputMessage bool `xml:"showInputMessage,attr"`
Sqref string `xml:"sqref,attr"`
Type string `xml:"type,attr"`
Formula1 string `xml:"formula1"`
Formula2 string `xml:"formula2"`
}
// xlsxC directly maps the c element in the namespace
@@ -446,7 +474,7 @@ type xlsxIconSet struct {
type xlsxCfvo struct {
Gte bool `xml:"gte,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
Val int `xml:"val,attr"`
Val string `xml:"val,attr"`
ExtLst *xlsxExtLst `xml:"extLst"`
}

View File

@@ -234,7 +234,7 @@ func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) Se
}
delayed := DelayWithRetryAfter(resp, r.Context().Done())
if !delayed && !DelayForBackoff(backoff, attempt, r.Context().Done()) {
return nil, r.Context().Err()
return resp, r.Context().Err()
}
// don't count a 429 against the number of attempts
// so that we continue to retry until it succeeds

View File

@@ -20,7 +20,7 @@ import (
)
// Number contains the semantic version of this SDK.
const Number = "v10.15.4"
const Number = "v10.15.5"
var (
userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s",

View File

@@ -1,8 +1,8 @@
language: go
go:
- 1.8.x
- 1.9.x
- 1.10.x
- 1.9.7
- 1.10.4
- 1.11
env:
global:
@@ -28,7 +28,7 @@ script:
- make test
- make vet
- make errcheck
- make fmt
- if [ "$TRAVIS_GO_VERSION" = "1.11" ]; then make fmt; fi
after_success:
- bash <(curl -s https://codecov.io/bash)

View File

@@ -1,5 +1,21 @@
# Changelog
#### Version 1.19.0 (2018-09-27)
New Features:
- Implement a higher-level consumer group
([#1099](https://github.com/Shopify/sarama/pull/1099)).
Improvements:
- Add support for Go 1.11
([#1176](https://github.com/Shopify/sarama/pull/1176)).
Bug Fixes:
- Fix encoding of `MetadataResponse` with version 2 and higher
([#1174](https://github.com/Shopify/sarama/pull/1174)).
- Fix race condition in mock async producer
([#1174](https://github.com/Shopify/sarama/pull/1174)).
#### Version 1.18.0 (2018-09-07)
New Features:

View File

@@ -4,7 +4,7 @@ default: fmt vet errcheck test
test:
echo "" > coverage.txt
for d in `go list ./... | grep -v vendor`; do \
go test -p 1 -v -timeout 90s -race -coverprofile=profile.out -covermode=atomic $$d || exit 1; \
go test -p 1 -v -timeout 240s -race -coverprofile=profile.out -covermode=atomic $$d || exit 1; \
if [ -f profile.out ]; then \
cat profile.out >> coverage.txt; \
rm profile.out; \

View File

@@ -21,7 +21,7 @@ You might also want to look at the [Frequently Asked Questions](https://github.c
Sarama provides a "2 releases + 2 months" compatibility guarantee: we support
the two latest stable releases of Kafka and Go, and we provide a two month
grace period for older releases. This means we currently officially support
Go 1.8 through 1.10, and Kafka 0.11 through 1.1, although older releases are
Go 1.8 through 1.11, and Kafka 1.0 through 2.0, although older releases are
still likely to work.
Sarama follows semantic versioning and provides API stability via the gopkg.in service.

View File

@@ -173,14 +173,55 @@ type Config struct {
// Consumer is the namespace for configuration related to consuming messages,
// used by the Consumer.
//
// Note that Sarama's Consumer type does not currently support automatic
// consumer-group rebalancing and offset tracking. For Zookeeper-based
// tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka
// library builds on Sarama to add this support. For Kafka-based tracking
// (Kafka 0.9 and later), the https://github.com/bsm/sarama-cluster library
// builds on Sarama to add this support.
Consumer struct {
// Group is the namespace for configuring consumer group.
Group struct {
Session struct {
// The timeout used to detect consumer failures when using Kafka's group management facility.
// The consumer sends periodic heartbeats to indicate its liveness to the broker.
// If no heartbeats are received by the broker before the expiration of this session timeout,
// then the broker will remove this consumer from the group and initiate a rebalance.
// Note that the value must be in the allowable range as configured in the broker configuration
// by `group.min.session.timeout.ms` and `group.max.session.timeout.ms` (default 10s)
Timeout time.Duration
}
Heartbeat struct {
// The expected time between heartbeats to the consumer coordinator when using Kafka's group
// management facilities. Heartbeats are used to ensure that the consumer's session stays active and
// to facilitate rebalancing when new consumers join or leave the group.
// The value must be set lower than Consumer.Group.Session.Timeout, but typically should be set no
// higher than 1/3 of that value.
// It can be adjusted even lower to control the expected time for normal rebalances (default 3s)
Interval time.Duration
}
Rebalance struct {
// Strategy for allocating topic partitions to members (default BalanceStrategyRange)
Strategy BalanceStrategy
// The maximum allowed time for each worker to join the group once a rebalance has begun.
// This is basically a limit on the amount of time needed for all tasks to flush any pending
// data and commit offsets. If the timeout is exceeded, then the worker will be removed from
// the group, which will cause offset commit failures (default 60s).
Timeout time.Duration
Retry struct {
// When a new consumer joins a consumer group the set of consumers attempt to "rebalance"
// the load to assign partitions to each consumer. If the set of consumers changes while
// this assignment is taking place the rebalance will fail and retry. This setting controls
// the maximum number of attempts before giving up (default 4).
Max int
// Backoff time between retries during rebalance (default 2s)
Backoff time.Duration
}
}
Member struct {
// Custom metadata to include when joining the group. The user data for all joined members
// can be retrieved by sending a DescribeGroupRequest to the broker that is the
// coordinator for the group.
UserData []byte
}
}
Retry struct {
// How long to wait after a failing to read from a partition before
// trying again (default 2s).
@@ -331,6 +372,13 @@ func NewConfig() *Config {
c.Consumer.Offsets.Initial = OffsetNewest
c.Consumer.Offsets.Retry.Max = 3
c.Consumer.Group.Session.Timeout = 10 * time.Second
c.Consumer.Group.Heartbeat.Interval = 3 * time.Second
c.Consumer.Group.Rebalance.Strategy = BalanceStrategyRange
c.Consumer.Group.Rebalance.Timeout = 60 * time.Second
c.Consumer.Group.Rebalance.Retry.Max = 4
c.Consumer.Group.Rebalance.Retry.Backoff = 2 * time.Second
c.ClientID = defaultClientID
c.ChannelBufferSize = 256
c.Version = MinVersion
@@ -378,6 +426,15 @@ func (c *Config) Validate() error {
if c.Consumer.Offsets.Retention%time.Millisecond != 0 {
Logger.Println("Consumer.Offsets.Retention only supports millisecond precision; nanoseconds will be truncated.")
}
if c.Consumer.Group.Session.Timeout%time.Millisecond != 0 {
Logger.Println("Consumer.Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.")
}
if c.Consumer.Group.Heartbeat.Interval%time.Millisecond != 0 {
Logger.Println("Consumer.Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.")
}
if c.Consumer.Group.Rebalance.Timeout%time.Millisecond != 0 {
Logger.Println("Consumer.Group.Rebalance.Timeout only supports millisecond precision; nanoseconds will be truncated.")
}
if c.ClientID == defaultClientID {
Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
}
@@ -476,6 +533,24 @@ func (c *Config) Validate() error {
return ConfigurationError("Consumer.Offsets.Retry.Max must be >= 0")
}
// validate the Consumer Group values
switch {
case c.Consumer.Group.Session.Timeout <= 2*time.Millisecond:
return ConfigurationError("Consumer.Group.Session.Timeout must be >= 2ms")
case c.Consumer.Group.Heartbeat.Interval < 1*time.Millisecond:
return ConfigurationError("Consumer.Group.Heartbeat.Interval must be >= 1ms")
case c.Consumer.Group.Heartbeat.Interval >= c.Consumer.Group.Session.Timeout:
return ConfigurationError("Consumer.Group.Heartbeat.Interval must be < Consumer.Group.Session.Timeout")
case c.Consumer.Group.Rebalance.Strategy == nil:
return ConfigurationError("Consumer.Group.Rebalance.Strategy must not be empty")
case c.Consumer.Group.Rebalance.Timeout <= time.Millisecond:
return ConfigurationError("Consumer.Group.Rebalance.Timeout must be >= 1ms")
case c.Consumer.Group.Rebalance.Retry.Max < 0:
return ConfigurationError("Consumer.Group.Rebalance.Retry.Max must be >= 0")
case c.Consumer.Group.Rebalance.Retry.Backoff < 0:
return ConfigurationError("Consumer.Group.Rebalance.Retry.Backoff must be >= 0")
}
// validate misc shared values
switch {
case c.ChannelBufferSize < 0:

View File

@@ -2,7 +2,7 @@ name: sarama
up:
- go:
version: '1.10'
version: '1.11'
commands:
test:

View File

@@ -207,6 +207,10 @@ func (r *MetadataResponse) decode(pd packetDecoder, version int16) (err error) {
}
func (r *MetadataResponse) encode(pe packetEncoder) error {
if r.Version >= 3 {
pe.putInt32(r.ThrottleTimeMs)
}
err := pe.putArrayLength(len(r.Brokers))
if err != nil {
return err
@@ -218,6 +222,13 @@ func (r *MetadataResponse) encode(pe packetEncoder) error {
}
}
if r.Version >= 2 {
err := pe.putNullableString(r.ClusterID)
if err != nil {
return err
}
}
if r.Version >= 1 {
pe.putInt32(r.ControllerID)
}

View File

@@ -27,11 +27,14 @@ type offsetManager struct {
group string
ticker *time.Ticker
memberID string
generation int32
broker *Broker
brokerLock sync.RWMutex
poms map[string]map[int32]*partitionOffsetManager
pomsLock sync.Mutex
pomsLock sync.RWMutex
closeOnce sync.Once
closing chan none
@@ -41,6 +44,10 @@ type offsetManager struct {
// NewOffsetManagerFromClient creates a new OffsetManager from the given client.
// It is still necessary to call Close() on the underlying client when finished with the partition manager.
func NewOffsetManagerFromClient(group string, client Client) (OffsetManager, error) {
return newOffsetManagerFromClient(group, "", GroupGenerationUndefined, client)
}
func newOffsetManagerFromClient(group, memberID string, generation int32, client Client) (*offsetManager, error) {
// Check that we are not dealing with a closed Client before processing any other arguments
if client.Closed() {
return nil, ErrClosedClient
@@ -54,6 +61,9 @@ func NewOffsetManagerFromClient(group string, client Client) (OffsetManager, err
ticker: time.NewTicker(conf.Consumer.Offsets.CommitInterval),
poms: make(map[string]map[int32]*partitionOffsetManager),
memberID: memberID,
generation: generation,
closing: make(chan none),
closed: make(chan none),
}
@@ -245,20 +255,22 @@ func (om *offsetManager) constructRequest() *OffsetCommitRequest {
r = &OffsetCommitRequest{
Version: 1,
ConsumerGroup: om.group,
ConsumerGroupGeneration: GroupGenerationUndefined,
ConsumerID: om.memberID,
ConsumerGroupGeneration: om.generation,
}
} else {
r = &OffsetCommitRequest{
Version: 2,
RetentionTime: int64(om.conf.Consumer.Offsets.Retention / time.Millisecond),
ConsumerGroup: om.group,
ConsumerGroupGeneration: GroupGenerationUndefined,
ConsumerID: om.memberID,
ConsumerGroupGeneration: om.generation,
}
}
om.pomsLock.Lock()
defer om.pomsLock.Unlock()
om.pomsLock.RLock()
defer om.pomsLock.RUnlock()
for _, topicManagers := range om.poms {
for _, pom := range topicManagers {
@@ -278,8 +290,8 @@ func (om *offsetManager) constructRequest() *OffsetCommitRequest {
}
func (om *offsetManager) handleResponse(broker *Broker, req *OffsetCommitRequest, resp *OffsetCommitResponse) {
om.pomsLock.Lock()
defer om.pomsLock.Unlock()
om.pomsLock.RLock()
defer om.pomsLock.RUnlock()
for _, topicManagers := range om.poms {
for _, pom := range topicManagers {
@@ -329,8 +341,8 @@ func (om *offsetManager) handleResponse(broker *Broker, req *OffsetCommitRequest
}
func (om *offsetManager) handleError(err error) {
om.pomsLock.Lock()
defer om.pomsLock.Unlock()
om.pomsLock.RLock()
defer om.pomsLock.RUnlock()
for _, topicManagers := range om.poms {
for _, pom := range topicManagers {
@@ -340,8 +352,8 @@ func (om *offsetManager) handleError(err error) {
}
func (om *offsetManager) asyncClosePOMs() {
om.pomsLock.Lock()
defer om.pomsLock.Unlock()
om.pomsLock.RLock()
defer om.pomsLock.RUnlock()
for _, topicManagers := range om.poms {
for _, pom := range topicManagers {
@@ -375,6 +387,18 @@ func (om *offsetManager) releasePOMs(force bool) (remaining int) {
return
}
func (om *offsetManager) findPOM(topic string, partition int32) *partitionOffsetManager {
om.pomsLock.RLock()
defer om.pomsLock.RUnlock()
if partitions, ok := om.poms[topic]; ok {
if pom, ok := partitions[partition]; ok {
return pom
}
}
return nil
}
// Partition Offset Manager
// PartitionOffsetManager uses Kafka to store and fetch consumed partition offsets. You MUST call Close()

View File

@@ -1,5 +1,7 @@
language: go
go: 1.5
go:
- 1.7
- 1.11
install:
- go get "github.com/smartystreets/goconvey/convey"
- go get -v .

View File

@@ -93,8 +93,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// BroadcastTo is a server level broadcast function.
func (s *Server) BroadcastTo(room, message string, args ...interface{}) {
s.namespace.BroadcastTo(room, message, args...)
func (s *Server) BroadcastTo(room, event string, args ...interface{}) {
s.namespace.BroadcastTo(room, event, args...)
}
func (s *Server) loop() {

View File

@@ -1665,9 +1665,9 @@ func setTA(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) {
return nil, &ParseError{f, "bad TA DigestType", l}, ""
}
rr.DigestType = uint8(i)
s, e, c1 := endingToString(c, "bad TA Digest", f)
if e != nil {
return nil, e.(*ParseError), c1
s, err, c1 := endingToString(c, "bad TA Digest", f)
if err != nil {
return nil, err, c1
}
rr.Digest = s
return rr, nil, c1

View File

@@ -63,6 +63,12 @@ type ResponseWriter interface {
Hijack()
}
// A ConnectionStater interface is used by a DNS Handler to access TLS connection state
// when available.
type ConnectionStater interface {
ConnectionState() *tls.ConnectionState
}
type response struct {
msg []byte
hijacked bool // connection has been hijacked by handler
@@ -894,3 +900,15 @@ func (w *response) Close() error {
}
return nil
}
// ConnectionState() implements the ConnectionStater.ConnectionState() interface.
func (w *response) ConnectionState() *tls.ConnectionState {
type tlsConnectionStater interface {
ConnectionState() tls.ConnectionState
}
if v, ok := w.tcp.(tlsConnectionStater); ok {
t := v.ConnectionState()
return &t
}
return nil
}

View File

@@ -3,7 +3,7 @@ package dns
import "fmt"
// Version is current version of this library.
var Version = V{1, 0, 9}
var Version = V{1, 0, 10}
// V holds the version of this library.
type V struct {

View File

@@ -15,6 +15,9 @@ Lines: 1
vim
Mode: 644
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26231/cwd
SymlinkTo: /usr/bin
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26231/exe
SymlinkTo: /usr/bin/vim
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@@ -111,6 +114,9 @@ SymlinkTo: mnt:[4026531840]
Path: fixtures/26231/ns/net
SymlinkTo: net:[4026531993]
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26231/root
SymlinkTo: /
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26231/stat
Lines: 1
26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0
@@ -128,6 +134,9 @@ Lines: 1
ata_sff
Mode: 644
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26232/cwd
SymlinkTo: /does/not/exist
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Directory: fixtures/26232/fd
Mode: 755
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@@ -167,6 +176,9 @@ Max realtime priority 0 0
Max realtime timeout unlimited unlimited us
Mode: 644
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26232/root
SymlinkTo: /does/not/exist
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/26232/stat
Lines: 1
33 (ata_sff) S 2 0 0 0 -1 69238880 0 0 0 0 0 0 0 0 0 -20 1 0 5 0 0 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 18446744073709551615 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0
@@ -444,3 +456,7 @@ Path: fixtures/symlinktargets/xyz
Lines: 0
Mode: 644
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Path: fixtures/.unpacked
Lines: 0
Mode: 664
# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

View File

@@ -156,6 +156,26 @@ func (p Proc) Executable() (string, error) {
return exe, err
}
// Cwd returns the absolute path to the current working directory of the process.
func (p Proc) Cwd() (string, error) {
wd, err := os.Readlink(p.path("cwd"))
if os.IsNotExist(err) {
return "", nil
}
return wd, err
}
// RootDir returns the absolute path to the process's root directory (as set by chroot)
func (p Proc) RootDir() (string, error) {
rdir, err := os.Readlink(p.path("root"))
if os.IsNotExist(err) {
return "", nil
}
return rdir, err
}
// FileDescriptors returns the currently open file descriptors of a process.
func (p Proc) FileDescriptors() ([]uintptr, error) {
names, err := p.fileDescriptors()

View File

@@ -1,13 +1,51 @@
language: go
go:
- 1.9.x
- 1.10.x
env:
- GOMAXPROCS=4 GORACE=halt_on_error=1
install:
- go get github.com/stretchr/testify/assert
- go get gopkg.in/gemnasium/logrus-airbrake-hook.v2
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v ./...
matrix:
include:
- go: 1.10.x
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v ./...
- go: 1.11.x
env: GO111MODULE=on
install:
- go mod download
script:
- go test -race -v ./...
- go: 1.11.x
env: GO111MODULE=off
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v ./...
- go: 1.10.x
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v -tags appengine ./...
- go: 1.11.x
env: GO111MODULE=on
install:
- go mod download
script:
- go test -race -v -tags appengine ./...
- go: 1.11.x
env: GO111MODULE=off
install:
- go get github.com/stretchr/testify/assert
- go get golang.org/x/crypto/ssh/terminal
- go get golang.org/x/sys/unix
- go get golang.org/x/sys/windows
script:
- go test -race -v -tags appengine ./...

View File

@@ -1,3 +1,33 @@
# 1.1.0
This new release introduces:
* several fixes:
* a fix for a race condition on entry formatting
* proper cleanup of previously used entries before putting them back in the pool
* the extra new line at the end of message in text formatter has been removed
* a new global public API to check if a level is activated: IsLevelEnabled
* the following methods have been added to the Logger object
* IsLevelEnabled
* SetFormatter
* SetOutput
* ReplaceHooks
* introduction of go module
* an indent configuration for the json formatter
* output colour support for windows
* the field sort function is now configurable for text formatter
* the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
# 1.0.6
This new release introduces:
* a new api WithTime which allows to easily force the time of the log entry
which is mostly useful for logger wrapper
* a fix reverting the immutability of the entry given as parameter to the hooks
a new configuration field of the json formatter in order to put all the fields
in a nested dictionnary
* a new SetOutput method in the Logger
* a new configuration of the textformatter to configure the name of the default keys
* a new configuration of the text formatter to disable the level truncation
# 1.0.5
* Fix hooks race (#707)

View File

@@ -41,7 +41,7 @@ type Entry struct {
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
Message string
// When formatter is called in entry.log(), an Buffer may be set to entry
// When formatter is called in entry.log(), a Buffer may be set to entry
Buffer *bytes.Buffer
}
@@ -137,9 +137,9 @@ func (entry *Entry) fireHooks() {
}
func (entry *Entry) write() {
serialized, err := entry.Logger.Formatter.Format(entry)
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
serialized, err := entry.Logger.Formatter.Format(entry)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
} else {
@@ -151,7 +151,7 @@ func (entry *Entry) write() {
}
func (entry *Entry) Debug(args ...interface{}) {
if entry.Logger.level() >= DebugLevel {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.log(DebugLevel, fmt.Sprint(args...))
}
}
@@ -161,13 +161,13 @@ func (entry *Entry) Print(args ...interface{}) {
}
func (entry *Entry) Info(args ...interface{}) {
if entry.Logger.level() >= InfoLevel {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.log(InfoLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Warn(args ...interface{}) {
if entry.Logger.level() >= WarnLevel {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.log(WarnLevel, fmt.Sprint(args...))
}
}
@@ -177,20 +177,20 @@ func (entry *Entry) Warning(args ...interface{}) {
}
func (entry *Entry) Error(args ...interface{}) {
if entry.Logger.level() >= ErrorLevel {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.log(ErrorLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Fatal(args ...interface{}) {
if entry.Logger.level() >= FatalLevel {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.log(FatalLevel, fmt.Sprint(args...))
}
Exit(1)
}
func (entry *Entry) Panic(args ...interface{}) {
if entry.Logger.level() >= PanicLevel {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.log(PanicLevel, fmt.Sprint(args...))
}
panic(fmt.Sprint(args...))
@@ -199,13 +199,13 @@ func (entry *Entry) Panic(args ...interface{}) {
// Entry Printf family functions
func (entry *Entry) Debugf(format string, args ...interface{}) {
if entry.Logger.level() >= DebugLevel {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.Debug(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Infof(format string, args ...interface{}) {
if entry.Logger.level() >= InfoLevel {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.Info(fmt.Sprintf(format, args...))
}
}
@@ -215,7 +215,7 @@ func (entry *Entry) Printf(format string, args ...interface{}) {
}
func (entry *Entry) Warnf(format string, args ...interface{}) {
if entry.Logger.level() >= WarnLevel {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.Warn(fmt.Sprintf(format, args...))
}
}
@@ -225,20 +225,20 @@ func (entry *Entry) Warningf(format string, args ...interface{}) {
}
func (entry *Entry) Errorf(format string, args ...interface{}) {
if entry.Logger.level() >= ErrorLevel {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.Error(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Fatalf(format string, args ...interface{}) {
if entry.Logger.level() >= FatalLevel {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.Fatal(fmt.Sprintf(format, args...))
}
Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
if entry.Logger.level() >= PanicLevel {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.Panic(fmt.Sprintf(format, args...))
}
}
@@ -246,13 +246,13 @@ func (entry *Entry) Panicf(format string, args ...interface{}) {
// Entry Println family functions
func (entry *Entry) Debugln(args ...interface{}) {
if entry.Logger.level() >= DebugLevel {
if entry.Logger.IsLevelEnabled(DebugLevel) {
entry.Debug(entry.sprintlnn(args...))
}
}
func (entry *Entry) Infoln(args ...interface{}) {
if entry.Logger.level() >= InfoLevel {
if entry.Logger.IsLevelEnabled(InfoLevel) {
entry.Info(entry.sprintlnn(args...))
}
}
@@ -262,7 +262,7 @@ func (entry *Entry) Println(args ...interface{}) {
}
func (entry *Entry) Warnln(args ...interface{}) {
if entry.Logger.level() >= WarnLevel {
if entry.Logger.IsLevelEnabled(WarnLevel) {
entry.Warn(entry.sprintlnn(args...))
}
}
@@ -272,20 +272,20 @@ func (entry *Entry) Warningln(args ...interface{}) {
}
func (entry *Entry) Errorln(args ...interface{}) {
if entry.Logger.level() >= ErrorLevel {
if entry.Logger.IsLevelEnabled(ErrorLevel) {
entry.Error(entry.sprintlnn(args...))
}
}
func (entry *Entry) Fatalln(args ...interface{}) {
if entry.Logger.level() >= FatalLevel {
if entry.Logger.IsLevelEnabled(FatalLevel) {
entry.Fatal(entry.sprintlnn(args...))
}
Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
if entry.Logger.level() >= PanicLevel {
if entry.Logger.IsLevelEnabled(PanicLevel) {
entry.Panic(entry.sprintlnn(args...))
}
}

View File

@@ -21,30 +21,27 @@ func SetOutput(out io.Writer) {
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter Formatter) {
std.mu.Lock()
defer std.mu.Unlock()
std.Formatter = formatter
std.SetFormatter(formatter)
}
// SetLevel sets the standard logger level.
func SetLevel(level Level) {
std.mu.Lock()
defer std.mu.Unlock()
std.SetLevel(level)
}
// GetLevel returns the standard logger level.
func GetLevel() Level {
std.mu.Lock()
defer std.mu.Unlock()
return std.level()
return std.GetLevel()
}
// IsLevelEnabled checks if the log level of the standard logger is greater than the level param
func IsLevelEnabled(level Level) bool {
return std.IsLevelEnabled(level)
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook Hook) {
std.mu.Lock()
defer std.mu.Unlock()
std.Hooks.Add(hook)
std.AddHook(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.

View File

@@ -1,6 +1,7 @@
package logrus
import (
"bytes"
"encoding/json"
"fmt"
)
@@ -46,6 +47,9 @@ type JSONFormatter struct {
// },
// }
FieldMap FieldMap
// PrettyPrint will indent all json logs
PrettyPrint bool
}
// Format renders a single log entry
@@ -81,9 +85,20 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
serialized, err := json.Marshal(data)
if err != nil {
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
encoder := json.NewEncoder(b)
if f.PrettyPrint {
encoder.SetIndent("", " ")
}
if err := encoder.Encode(data); err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
return b.Bytes(), nil
}

View File

@@ -11,7 +11,7 @@ import (
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventorous, such as logging to Kafka.
// something more adventurous, such as logging to Kafka.
Out io.Writer
// Hooks for the logger instance. These allow firing events based on logging
// levels and log entries. For example, to send errors to an error tracking
@@ -85,6 +85,7 @@ func (logger *Logger) newEntry() *Entry {
}
func (logger *Logger) releaseEntry(entry *Entry) {
entry.Data = map[string]interface{}{}
logger.entryPool.Put(entry)
}
@@ -121,7 +122,7 @@ func (logger *Logger) WithTime(t time.Time) *Entry {
}
func (logger *Logger) Debugf(format string, args ...interface{}) {
if logger.level() >= DebugLevel {
if logger.IsLevelEnabled(DebugLevel) {
entry := logger.newEntry()
entry.Debugf(format, args...)
logger.releaseEntry(entry)
@@ -129,7 +130,7 @@ func (logger *Logger) Debugf(format string, args ...interface{}) {
}
func (logger *Logger) Infof(format string, args ...interface{}) {
if logger.level() >= InfoLevel {
if logger.IsLevelEnabled(InfoLevel) {
entry := logger.newEntry()
entry.Infof(format, args...)
logger.releaseEntry(entry)
@@ -143,7 +144,7 @@ func (logger *Logger) Printf(format string, args ...interface{}) {
}
func (logger *Logger) Warnf(format string, args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warnf(format, args...)
logger.releaseEntry(entry)
@@ -151,7 +152,7 @@ func (logger *Logger) Warnf(format string, args ...interface{}) {
}
func (logger *Logger) Warningf(format string, args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warnf(format, args...)
logger.releaseEntry(entry)
@@ -159,7 +160,7 @@ func (logger *Logger) Warningf(format string, args ...interface{}) {
}
func (logger *Logger) Errorf(format string, args ...interface{}) {
if logger.level() >= ErrorLevel {
if logger.IsLevelEnabled(ErrorLevel) {
entry := logger.newEntry()
entry.Errorf(format, args...)
logger.releaseEntry(entry)
@@ -167,7 +168,7 @@ func (logger *Logger) Errorf(format string, args ...interface{}) {
}
func (logger *Logger) Fatalf(format string, args ...interface{}) {
if logger.level() >= FatalLevel {
if logger.IsLevelEnabled(FatalLevel) {
entry := logger.newEntry()
entry.Fatalf(format, args...)
logger.releaseEntry(entry)
@@ -176,7 +177,7 @@ func (logger *Logger) Fatalf(format string, args ...interface{}) {
}
func (logger *Logger) Panicf(format string, args ...interface{}) {
if logger.level() >= PanicLevel {
if logger.IsLevelEnabled(PanicLevel) {
entry := logger.newEntry()
entry.Panicf(format, args...)
logger.releaseEntry(entry)
@@ -184,7 +185,7 @@ func (logger *Logger) Panicf(format string, args ...interface{}) {
}
func (logger *Logger) Debug(args ...interface{}) {
if logger.level() >= DebugLevel {
if logger.IsLevelEnabled(DebugLevel) {
entry := logger.newEntry()
entry.Debug(args...)
logger.releaseEntry(entry)
@@ -192,7 +193,7 @@ func (logger *Logger) Debug(args ...interface{}) {
}
func (logger *Logger) Info(args ...interface{}) {
if logger.level() >= InfoLevel {
if logger.IsLevelEnabled(InfoLevel) {
entry := logger.newEntry()
entry.Info(args...)
logger.releaseEntry(entry)
@@ -206,7 +207,7 @@ func (logger *Logger) Print(args ...interface{}) {
}
func (logger *Logger) Warn(args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warn(args...)
logger.releaseEntry(entry)
@@ -214,7 +215,7 @@ func (logger *Logger) Warn(args ...interface{}) {
}
func (logger *Logger) Warning(args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warn(args...)
logger.releaseEntry(entry)
@@ -222,7 +223,7 @@ func (logger *Logger) Warning(args ...interface{}) {
}
func (logger *Logger) Error(args ...interface{}) {
if logger.level() >= ErrorLevel {
if logger.IsLevelEnabled(ErrorLevel) {
entry := logger.newEntry()
entry.Error(args...)
logger.releaseEntry(entry)
@@ -230,7 +231,7 @@ func (logger *Logger) Error(args ...interface{}) {
}
func (logger *Logger) Fatal(args ...interface{}) {
if logger.level() >= FatalLevel {
if logger.IsLevelEnabled(FatalLevel) {
entry := logger.newEntry()
entry.Fatal(args...)
logger.releaseEntry(entry)
@@ -239,7 +240,7 @@ func (logger *Logger) Fatal(args ...interface{}) {
}
func (logger *Logger) Panic(args ...interface{}) {
if logger.level() >= PanicLevel {
if logger.IsLevelEnabled(PanicLevel) {
entry := logger.newEntry()
entry.Panic(args...)
logger.releaseEntry(entry)
@@ -247,7 +248,7 @@ func (logger *Logger) Panic(args ...interface{}) {
}
func (logger *Logger) Debugln(args ...interface{}) {
if logger.level() >= DebugLevel {
if logger.IsLevelEnabled(DebugLevel) {
entry := logger.newEntry()
entry.Debugln(args...)
logger.releaseEntry(entry)
@@ -255,7 +256,7 @@ func (logger *Logger) Debugln(args ...interface{}) {
}
func (logger *Logger) Infoln(args ...interface{}) {
if logger.level() >= InfoLevel {
if logger.IsLevelEnabled(InfoLevel) {
entry := logger.newEntry()
entry.Infoln(args...)
logger.releaseEntry(entry)
@@ -269,7 +270,7 @@ func (logger *Logger) Println(args ...interface{}) {
}
func (logger *Logger) Warnln(args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warnln(args...)
logger.releaseEntry(entry)
@@ -277,7 +278,7 @@ func (logger *Logger) Warnln(args ...interface{}) {
}
func (logger *Logger) Warningln(args ...interface{}) {
if logger.level() >= WarnLevel {
if logger.IsLevelEnabled(WarnLevel) {
entry := logger.newEntry()
entry.Warnln(args...)
logger.releaseEntry(entry)
@@ -285,7 +286,7 @@ func (logger *Logger) Warningln(args ...interface{}) {
}
func (logger *Logger) Errorln(args ...interface{}) {
if logger.level() >= ErrorLevel {
if logger.IsLevelEnabled(ErrorLevel) {
entry := logger.newEntry()
entry.Errorln(args...)
logger.releaseEntry(entry)
@@ -293,7 +294,7 @@ func (logger *Logger) Errorln(args ...interface{}) {
}
func (logger *Logger) Fatalln(args ...interface{}) {
if logger.level() >= FatalLevel {
if logger.IsLevelEnabled(FatalLevel) {
entry := logger.newEntry()
entry.Fatalln(args...)
logger.releaseEntry(entry)
@@ -302,7 +303,7 @@ func (logger *Logger) Fatalln(args ...interface{}) {
}
func (logger *Logger) Panicln(args ...interface{}) {
if logger.level() >= PanicLevel {
if logger.IsLevelEnabled(PanicLevel) {
entry := logger.newEntry()
entry.Panicln(args...)
logger.releaseEntry(entry)
@@ -320,18 +321,47 @@ func (logger *Logger) level() Level {
return Level(atomic.LoadUint32((*uint32)(&logger.Level)))
}
// SetLevel sets the logger level.
func (logger *Logger) SetLevel(level Level) {
atomic.StoreUint32((*uint32)(&logger.Level), uint32(level))
}
func (logger *Logger) SetOutput(out io.Writer) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Out = out
// GetLevel returns the logger level.
func (logger *Logger) GetLevel() Level {
return logger.level()
}
// AddHook adds a hook to the logger hooks.
func (logger *Logger) AddHook(hook Hook) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Hooks.Add(hook)
}
// IsLevelEnabled checks if the log level of the logger is greater than the level param
func (logger *Logger) IsLevelEnabled(level Level) bool {
return logger.level() >= level
}
// SetFormatter sets the logger formatter.
func (logger *Logger) SetFormatter(formatter Formatter) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Formatter = formatter
}
// SetOutput sets the logger output.
func (logger *Logger) SetOutput(output io.Writer) {
logger.mu.Lock()
defer logger.mu.Unlock()
logger.Out = output
}
// ReplaceHooks replaces the logger hooks and returns the old ones
func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks {
logger.mu.Lock()
oldHooks := logger.Hooks
logger.Hooks = hooks
logger.mu.Unlock()
return oldHooks
}

View File

@@ -140,4 +140,11 @@ type FieldLogger interface {
Errorln(args ...interface{})
Fatalln(args ...interface{})
Panicln(args ...interface{})
// IsDebugEnabled() bool
// IsInfoEnabled() bool
// IsWarnEnabled() bool
// IsErrorEnabled() bool
// IsFatalEnabled() bool
// IsPanicEnabled() bool
}

View File

@@ -1,10 +1,17 @@
// +build darwin freebsd openbsd netbsd dragonfly
// +build !appengine,!gopherjs
// +build !appengine,!js
package logrus
import "golang.org/x/sys/unix"
import (
"io"
"golang.org/x/sys/unix"
)
const ioctlReadTermios = unix.TIOCGETA
type Termios unix.Termios
func initTerminal(w io.Writer) {
}

View File

@@ -1,4 +1,4 @@
// +build appengine gopherjs
// +build appengine
package logrus

View File

@@ -1,4 +1,4 @@
// +build !appengine,!gopherjs
// +build !appengine,!js,!windows
package logrus

View File

@@ -3,12 +3,19 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !appengine,!gopherjs
// +build !appengine,!js
package logrus
import "golang.org/x/sys/unix"
import (
"io"
"golang.org/x/sys/unix"
)
const ioctlReadTermios = unix.TCGETS
type Termios unix.Termios
func initTerminal(w io.Writer) {
}

View File

@@ -3,6 +3,7 @@ package logrus
import (
"bytes"
"fmt"
"os"
"sort"
"strings"
"sync"
@@ -35,6 +36,9 @@ type TextFormatter struct {
// Force disabling colors.
DisableColors bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
EnvironmentOverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
@@ -51,6 +55,9 @@ type TextFormatter struct {
// be desired.
DisableSorting bool
// The keys sorting function, when uninitialized it uses sort.Strings.
SortingFunc func([]string)
// Disables the truncation of the level text to 4 characters.
DisableLevelTruncation bool
@@ -69,15 +76,35 @@ type TextFormatter struct {
// FieldKeyMsg: "@message"}}
FieldMap FieldMap
sync.Once
terminalInitOnce sync.Once
}
func (f *TextFormatter) init(entry *Entry) {
if entry.Logger != nil {
f.isTerminal = checkIfTerminal(entry.Logger.Out)
if f.isTerminal {
initTerminal(entry.Logger.Out)
}
}
}
func (f *TextFormatter) isColored() bool {
isColored := f.ForceColors || f.isTerminal
if f.EnvironmentOverrideColors {
if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" {
isColored = true
} else if ok && force == "0" {
isColored = false
} else if os.Getenv("CLICOLOR") == "0" {
isColored = false
}
}
return isColored && !f.DisableColors
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
prefixFieldClashes(entry.Data, f.FieldMap)
@@ -87,8 +114,29 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
keys = append(keys, k)
}
fixedKeys := make([]string, 0, 3+len(entry.Data))
if !f.DisableTimestamp {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
}
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
if entry.Message != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
}
if !f.DisableSorting {
sort.Strings(keys)
if f.SortingFunc == nil {
sort.Strings(keys)
fixedKeys = append(fixedKeys, keys...)
} else {
if !f.isColored() {
fixedKeys = append(fixedKeys, keys...)
f.SortingFunc(fixedKeys)
} else {
f.SortingFunc(keys)
}
}
} else {
fixedKeys = append(fixedKeys, keys...)
}
var b *bytes.Buffer
@@ -98,26 +146,28 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
b = &bytes.Buffer{}
}
f.Do(func() { f.init(entry) })
isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
f.terminalInitOnce.Do(func() { f.init(entry) })
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if isColored {
if f.isColored() {
f.printColored(b, entry, keys, timestampFormat)
} else {
if !f.DisableTimestamp {
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyTime), entry.Time.Format(timestampFormat))
}
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyLevel), entry.Level.String())
if entry.Message != "" {
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyMsg), entry.Message)
}
for _, key := range keys {
f.appendKeyValue(b, key, entry.Data[key])
for _, key := range fixedKeys {
var value interface{}
switch key {
case f.FieldMap.resolve(FieldKeyTime):
value = entry.Time.Format(timestampFormat)
case f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String()
case f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message
default:
value = entry.Data[key]
}
f.appendKeyValue(b, key, value)
}
}
@@ -143,6 +193,10 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin
levelText = levelText[0:4]
}
// Remove a single newline if it already exists in the message to keep
// the behavior of logrus text_formatter the same as the stdlib log package
entry.Message = strings.TrimSuffix(entry.Message, "\n")
if f.DisableTimestamp {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
} else if !f.FullTimestamp {

View File

@@ -199,7 +199,7 @@ func (w *writeResHeaders) staysWithinBuffer(max int) bool {
// TODO: this is a common one. It'd be nice to return true
// here and get into the fast path if we could be clever and
// calculate the size fast enough, or at least a conservative
// uppper bound that usually fires. (Maybe if w.h and
// upper bound that usually fires. (Maybe if w.h and
// w.trailers are nil, so we don't need to enumerate it.)
// Otherwise I'm afraid that just calculating the length to
// answer this question would be slower than the ~2µs benefit.

View File

@@ -6,17 +6,7 @@
// +build ppc
// Functions to access/create device major and minor numbers matching the
// encoding used by the Linux kernel and glibc.
//
// The information below is extracted and adapted from bits/sysmacros.h in the
// glibc sources:
//
// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
// number and m is a hex digit of the minor number. This is backward compatible
// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
// backward compatible with the Linux kernel, which for some architectures uses
// 32-bit dev_t, encoded as mmmM MMmm.
// encoding used by AIX.
package unix

View File

@@ -6,17 +6,7 @@
// +build ppc64
// Functions to access/create device major and minor numbers matching the
// encoding used by the Linux kernel and glibc.
//
// The information below is extracted and adapted from bits/sysmacros.h in the
// glibc sources:
//
// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
// number and m is a hex digit of the minor number. This is backward compatible
// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
// backward compatible with the Linux kernel, which for some architectures uses
// 32-bit dev_t, encoded as mmmM MMmm.
// encoding used AIX.
package unix

View File

@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
package unix

View File

@@ -46,6 +46,7 @@ includes_AIX='
#include <sys/stropts.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/termio.h>
#include <termios.h>
#include <fcntl.h>
@@ -86,6 +87,7 @@ includes_DragonFly='
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
@@ -215,6 +217,7 @@ struct ltchars {
#include <linux/watchdog.h>
#include <linux/hdreg.h>
#include <linux/rtc.h>
#include <linux/if_xdp.h>
#include <mtd/ubi-user.h>
#include <net/route.h>
#include <asm/termbits.h>
@@ -245,6 +248,16 @@ struct ltchars {
#define FS_KEY_DESC_PREFIX "fscrypt:"
#define FS_KEY_DESC_PREFIX_SIZE 8
#define FS_MAX_KEY_SIZE 64
// XDP socket constants do not appear to be picked up otherwise.
// Copied from samples/bpf/xdpsock_user.c.
#ifndef SOL_XDP
#define SOL_XDP 283
#endif
#ifndef AF_XDP
#define AF_XDP 44
#endif
'
includes_NetBSD='
@@ -253,6 +266,7 @@ includes_NetBSD='
#include <sys/event.h>
#include <sys/extattr.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
@@ -278,6 +292,7 @@ includes_OpenBSD='
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stat.h>
@@ -379,6 +394,7 @@ ccflags="$@"
$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}
$2 !~ /^ECCAPBITS/ &&
$2 !~ /^ETH_/ &&
$2 !~ /^EPROC_/ &&
$2 !~ /^EQUIV_/ &&
@@ -425,6 +441,7 @@ ccflags="$@"
$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||
$2 ~ /^HW_MACHINE$/ ||
$2 ~ /^SYSCTL_VERS/ ||
$2 !~ "MNT_BITS" &&
$2 ~ /^(MS|MNT|UMOUNT)_/ ||
$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||
@@ -475,6 +492,7 @@ ccflags="$@"
$2 ~ /^FSOPT_/ ||
$2 ~ /^WDIOC_/ ||
$2 ~ /^NFN/ ||
$2 ~ /^XDP_/ ||
$2 ~ /^(HDIO|WIN|SMART)_/ ||
$2 !~ "WMESGLEN" &&
$2 ~ /^W[A-Z0-9]+$/ ||

View File

@@ -345,11 +345,11 @@ func IoctlSetInt(fd int, req uint, value int) error {
return ioctl(fd, req, uintptr(value))
}
func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
func ioctlSetWinsize(fd int, req uint, value *Winsize) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
func IoctlSetTermios(fd int, req uint, value *Termios) error {
func ioctlSetTermios(fd int, req uint, value *Termios) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
@@ -419,8 +419,10 @@ func Flock(fd int, how int) (err error) {
//sysnb Getsid(pid int) (sid int, err error)
//sysnb Kill(pid int, sig syscall.Signal) (err error)
//sys Klogctl(typ int, buf []byte) (n int, err error) = syslog
//sys Mkdir(dirfd int, path string, mode uint32) (err error)
//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
//sys Mkfifo(path string, mode uint32) (err error)
//sys Mknod(path string, mode uint32, dev int) (err error)
//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
//sys Open(path string, mode int, perm uint32) (fd int, err error) = open64

View File

@@ -692,6 +692,24 @@ func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
}
type SockaddrXDP struct {
Flags uint16
Ifindex uint32
QueueID uint32
SharedUmemFD uint32
raw RawSockaddrXDP
}
func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_XDP
sa.raw.Flags = sa.Flags
sa.raw.Ifindex = sa.Ifindex
sa.raw.Queue_id = sa.QueueID
sa.raw.Shared_umem_fd = sa.SharedUmemFD
return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil
}
func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
switch rsa.Addr.Family {
case AF_NETLINK:
@@ -793,6 +811,15 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
}
return sa, nil
}
case AF_XDP:
pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa))
sa := &SockaddrXDP{
Flags: pp.Flags,
Ifindex: pp.Ifindex,
QueueID: pp.Queue_id,
SharedUmemFD: pp.Shared_umem_fd,
}
return sa, nil
}
return nil, EAFNOSUPPORT
}
@@ -1273,6 +1300,7 @@ func Mount(source string, target string, fstype string, flags uintptr, data stri
//sys Adjtimex(buf *Timex) (state int, err error)
//sys Chdir(path string) (err error)
//sys Chroot(path string) (err error)
//sys ClockGetres(clockid int32, res *Timespec) (err error)
//sys ClockGettime(clockid int32, time *Timespec) (err error)
//sys Close(fd int) (err error)
//sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
@@ -1496,7 +1524,6 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
// Brk
// Capget
// Capset
// ClockGetres
// ClockNanosleep
// ClockSettime
// Clone

View File

@@ -93,6 +93,23 @@ func nametomib(name string) (mib []_C_int, err error) {
return mib, nil
}
func SysctlClockinfo(name string) (*Clockinfo, error) {
mib, err := sysctlmib(name)
if err != nil {
return nil, err
}
n := uintptr(SizeofClockinfo)
buf := make([]byte, SizeofClockinfo)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return nil, err
}
if n != SizeofClockinfo {
return nil, EIO
}
return (*Clockinfo)(unsafe.Pointer(&buf[0])), nil
}
//sysnb pipe() (fd1 int, fd2 int, err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {

View File

@@ -22,6 +22,11 @@ package unix
#include <utime.h>
#include <sys/utsname.h>
#include <sys/poll.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/termio.h>
#include <sys/ioctl.h>
#include <termios.h>
@@ -33,7 +38,6 @@ package unix
#include <dirent.h>
#include <fcntl.h>
#include <gcrypt.h>
enum {
sizeofPtr = sizeof(void*),
@@ -224,6 +228,9 @@ type Flock_t C.struct_flock64
// Statfs
type Fsid_t C.struct_fsid_t
type Fsid64_t C.struct_fsid64_t
type Statfs_t C.struct_statfs
const RNDGETENTCNT = 0x80045200

View File

@@ -279,3 +279,9 @@ type Sysctlnode C.struct_sysctlnode
// Uname
type Utsname C.struct_utsname
// Clockinfo
const SizeofClockinfo = C.sizeof_struct_clockinfo
type Clockinfo C.struct_clockinfo

View File

@@ -867,6 +867,9 @@ const (
TAB2 = 0x800
TAB3 = 0xc00
TABDLY = 0xc00
TCFLSH = 0x540c
TCGETA = 0x5405
TCGETS = 0x5401
TCIFLUSH = 0x0
TCIOFF = 0x2
TCIOFLUSH = 0x2
@@ -915,6 +918,15 @@ const (
TCP_TIMESTAMP_OPTLEN = 0xc
TCP_UNSETPRIV = 0x28
TCSAFLUSH = 0x2
TCSBRK = 0x5409
TCSETA = 0x5406
TCSETAF = 0x5408
TCSETAW = 0x5407
TCSETS = 0x5402
TCSETSF = 0x5404
TCSETSW = 0x5403
TCXONC = 0x540b
TIOC = 0x5400
TIOCCBRK = 0x2000747a
TIOCCDTR = 0x20007478
TIOCCONS = 0x80047462

View File

@@ -867,6 +867,9 @@ const (
TAB2 = 0x800
TAB3 = 0xc00
TABDLY = 0xc00
TCFLSH = 0x540c
TCGETA = 0x5405
TCGETS = 0x5401
TCIFLUSH = 0x0
TCIOFF = 0x2
TCIOFLUSH = 0x2
@@ -915,6 +918,15 @@ const (
TCP_TIMESTAMP_OPTLEN = 0xc
TCP_UNSETPRIV = 0x28
TCSAFLUSH = 0x2
TCSBRK = 0x5409
TCSETA = 0x5406
TCSETAF = 0x5408
TCSETAW = 0x5407
TCSETS = 0x5402
TCSETSF = 0x5404
TCSETSW = 0x5403
TCXONC = 0x540b
TIOC = 0x5400
TIOCCBRK = 0x2000747a
TIOCCDTR = 0x20007478
TIOCCONS = 0xffffffff80047462

View File

@@ -880,6 +880,40 @@ const (
MAP_VPAGETABLE = 0x2000
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_AUTOMOUNTED = 0x20
MNT_CMDFLAGS = 0xf0000
MNT_DEFEXPORTED = 0x200
MNT_DELEXPORT = 0x20000
MNT_EXKERB = 0x800
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXPUBLIC = 0x20000000
MNT_EXRDONLY = 0x80
MNT_FORCE = 0x80000
MNT_IGNORE = 0x800000
MNT_LAZY = 0x4
MNT_LOCAL = 0x1000
MNT_NOATIME = 0x10000000
MNT_NOCLUSTERR = 0x40000000
MNT_NOCLUSTERW = 0x80000000
MNT_NODEV = 0x10
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOSYMFOLLOW = 0x400000
MNT_NOWAIT = 0x2
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x200000
MNT_SUIDDIR = 0x100000
MNT_SYNCHRONOUS = 0x2
MNT_TRIM = 0x1000000
MNT_UPDATE = 0x10000
MNT_USER = 0x8000
MNT_VISFLAGMASK = 0xf1f0ffff
MNT_WAIT = 0x1
MSG_CMSG_CLOEXEC = 0x1000
MSG_CTRUNC = 0x20
MSG_DONTROUTE = 0x4

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1811,6 +1812,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2293,6 +2295,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1812,6 +1813,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2293,6 +2295,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1818,6 +1819,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2299,6 +2301,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1802,6 +1803,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2284,6 +2286,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1811,6 +1812,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1009
SO_ATTACH_BPF = 0x32
@@ -2295,6 +2297,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1811,6 +1812,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1009
SO_ATTACH_BPF = 0x32
@@ -2295,6 +2297,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1811,6 +1812,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1009
SO_ATTACH_BPF = 0x32
@@ -2295,6 +2297,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1811,6 +1812,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1009
SO_ATTACH_BPF = 0x32
@@ -2295,6 +2297,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1867,6 +1868,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2352,6 +2354,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4000
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0xc00
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1867,6 +1868,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2352,6 +2354,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4000
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0xc00
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1799,6 +1800,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2280,6 +2282,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -64,6 +64,7 @@ const (
AF_VSOCK = 0x28
AF_WANPIPE = 0x19
AF_X25 = 0x9
AF_XDP = 0x2c
ALG_OP_DECRYPT = 0x0
ALG_OP_ENCRYPT = 0x1
ALG_SET_AEAD_ASSOCLEN = 0x4
@@ -1872,6 +1873,7 @@ const (
SOL_TIPC = 0x10f
SOL_TLS = 0x11a
SOL_X25 = 0x106
SOL_XDP = 0x11b
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x1e
SO_ATTACH_BPF = 0x32
@@ -2353,6 +2355,26 @@ const (
XATTR_CREATE = 0x1
XATTR_REPLACE = 0x2
XCASE = 0x4
XDP_COPY = 0x2
XDP_FLAGS_DRV_MODE = 0x4
XDP_FLAGS_HW_MODE = 0x8
XDP_FLAGS_MASK = 0xf
XDP_FLAGS_MODES = 0xe
XDP_FLAGS_SKB_MODE = 0x2
XDP_FLAGS_UPDATE_IF_NOEXIST = 0x1
XDP_MMAP_OFFSETS = 0x1
XDP_PGOFF_RX_RING = 0x0
XDP_PGOFF_TX_RING = 0x80000000
XDP_RX_RING = 0x2
XDP_SHARED_UMEM = 0x1
XDP_STATISTICS = 0x7
XDP_TX_RING = 0x3
XDP_UMEM_COMPLETION_RING = 0x6
XDP_UMEM_FILL_RING = 0x5
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4
XDP_ZEROCOPY = 0x4
XENFS_SUPER_MAGIC = 0xabba1974
XTABS = 0x1800
ZSMALLOC_MAGIC = 0x58295829

View File

@@ -1020,6 +1020,43 @@ const (
MAP_WIRED = 0x800
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_BASIC_FLAGS = 0xe782807f
MNT_DEFEXPORTED = 0x200
MNT_DISCARD = 0x800000
MNT_EXKERB = 0x800
MNT_EXNORESPORT = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXPUBLIC = 0x10000000
MNT_EXRDONLY = 0x80
MNT_EXTATTR = 0x1000000
MNT_FORCE = 0x80000
MNT_GETARGS = 0x400000
MNT_IGNORE = 0x100000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_LOG = 0x2000000
MNT_NOATIME = 0x4000000
MNT_NOCOREDUMP = 0x8000
MNT_NODEV = 0x10
MNT_NODEVMTIME = 0x40000000
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_OP_FLAGS = 0x4d0000
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELATIME = 0x20000
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x80000000
MNT_SYMPERM = 0x20000000
MNT_SYNCHRONOUS = 0x2
MNT_UNION = 0x20
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0xff90ffff
MNT_WAIT = 0x1
MSG_BCAST = 0x100
MSG_CMSG_CLOEXEC = 0x800
MSG_CONTROLMBUF = 0x2000000
@@ -1113,7 +1150,10 @@ const (
RLIMIT_CPU = 0x0
RLIMIT_DATA = 0x2
RLIMIT_FSIZE = 0x1
RLIMIT_MEMLOCK = 0x6
RLIMIT_NOFILE = 0x8
RLIMIT_NPROC = 0x7
RLIMIT_RSS = 0x5
RLIMIT_STACK = 0x3
RLIM_INFINITY = 0x7fffffffffffffff
RTAX_AUTHOR = 0x6

View File

@@ -1010,6 +1010,43 @@ const (
MAP_WIRED = 0x800
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_BASIC_FLAGS = 0xe782807f
MNT_DEFEXPORTED = 0x200
MNT_DISCARD = 0x800000
MNT_EXKERB = 0x800
MNT_EXNORESPORT = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXPUBLIC = 0x10000000
MNT_EXRDONLY = 0x80
MNT_EXTATTR = 0x1000000
MNT_FORCE = 0x80000
MNT_GETARGS = 0x400000
MNT_IGNORE = 0x100000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_LOG = 0x2000000
MNT_NOATIME = 0x4000000
MNT_NOCOREDUMP = 0x8000
MNT_NODEV = 0x10
MNT_NODEVMTIME = 0x40000000
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_OP_FLAGS = 0x4d0000
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELATIME = 0x20000
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x80000000
MNT_SYMPERM = 0x20000000
MNT_SYNCHRONOUS = 0x2
MNT_UNION = 0x20
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0xff90ffff
MNT_WAIT = 0x1
MSG_BCAST = 0x100
MSG_CMSG_CLOEXEC = 0x800
MSG_CONTROLMBUF = 0x2000000
@@ -1103,7 +1140,10 @@ const (
RLIMIT_CPU = 0x0
RLIMIT_DATA = 0x2
RLIMIT_FSIZE = 0x1
RLIMIT_MEMLOCK = 0x6
RLIMIT_NOFILE = 0x8
RLIMIT_NPROC = 0x7
RLIMIT_RSS = 0x5
RLIMIT_STACK = 0x3
RLIM_INFINITY = 0x7fffffffffffffff
RTAX_AUTHOR = 0x6

View File

@@ -1000,6 +1000,43 @@ const (
MAP_STACK = 0x2000
MAP_TRYFIXED = 0x400
MAP_WIRED = 0x800
MNT_ASYNC = 0x40
MNT_BASIC_FLAGS = 0xe782807f
MNT_DEFEXPORTED = 0x200
MNT_DISCARD = 0x800000
MNT_EXKERB = 0x800
MNT_EXNORESPORT = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXPUBLIC = 0x10000000
MNT_EXRDONLY = 0x80
MNT_EXTATTR = 0x1000000
MNT_FORCE = 0x80000
MNT_GETARGS = 0x400000
MNT_IGNORE = 0x100000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_LOG = 0x2000000
MNT_NOATIME = 0x4000000
MNT_NOCOREDUMP = 0x8000
MNT_NODEV = 0x10
MNT_NODEVMTIME = 0x40000000
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_OP_FLAGS = 0x4d0000
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELATIME = 0x20000
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x80000000
MNT_SYMPERM = 0x20000000
MNT_SYNCHRONOUS = 0x2
MNT_UNION = 0x20
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0xff90ffff
MNT_WAIT = 0x1
MSG_BCAST = 0x100
MSG_CMSG_CLOEXEC = 0x800
MSG_CONTROLMBUF = 0x2000000
@@ -1093,7 +1130,10 @@ const (
RLIMIT_CPU = 0x0
RLIMIT_DATA = 0x2
RLIMIT_FSIZE = 0x1
RLIMIT_MEMLOCK = 0x6
RLIMIT_NOFILE = 0x8
RLIMIT_NPROC = 0x7
RLIMIT_RSS = 0x5
RLIMIT_STACK = 0x3
RLIM_INFINITY = 0x7fffffffffffffff
RTAX_AUTHOR = 0x6

View File

@@ -899,6 +899,32 @@ const (
MAP_TRYFIXED = 0x400
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_DEFEXPORTED = 0x200
MNT_DELEXPORT = 0x20000
MNT_DOOMED = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXRDONLY = 0x80
MNT_FORCE = 0x80000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_NOATIME = 0x8000
MNT_NODEV = 0x10
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x4000000
MNT_SYNCHRONOUS = 0x2
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0x400ffff
MNT_WAIT = 0x1
MNT_WANTRDWR = 0x2000000
MNT_WXALLOWED = 0x800
MSG_BCAST = 0x100
MSG_CTRUNC = 0x20
MSG_DONTROUTE = 0x4

View File

@@ -939,6 +939,32 @@ const (
MAP_TRYFIXED = 0x0
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_DEFEXPORTED = 0x200
MNT_DELEXPORT = 0x20000
MNT_DOOMED = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXRDONLY = 0x80
MNT_FORCE = 0x80000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_NOATIME = 0x8000
MNT_NODEV = 0x10
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x4000000
MNT_SYNCHRONOUS = 0x2
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0x400ffff
MNT_WAIT = 0x1
MNT_WANTRDWR = 0x2000000
MNT_WXALLOWED = 0x800
MSG_BCAST = 0x100
MSG_CMSG_CLOEXEC = 0x800
MSG_CTRUNC = 0x20

View File

@@ -899,6 +899,32 @@ const (
MAP_TRYFIXED = 0x0
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_DEFEXPORTED = 0x200
MNT_DELEXPORT = 0x20000
MNT_DOOMED = 0x8000000
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXRDONLY = 0x80
MNT_FORCE = 0x80000
MNT_LAZY = 0x3
MNT_LOCAL = 0x1000
MNT_NOATIME = 0x8000
MNT_NODEV = 0x10
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOWAIT = 0x2
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x4000000
MNT_SYNCHRONOUS = 0x2
MNT_UPDATE = 0x10000
MNT_VISFLAGMASK = 0x400ffff
MNT_WAIT = 0x1
MNT_WANTRDWR = 0x2000000
MNT_WXALLOWED = 0x800
MSG_BCAST = 0x100
MSG_CMSG_CLOEXEC = 0x800
MSG_CTRUNC = 0x20

View File

@@ -39,8 +39,10 @@ int getrusage(int, uintptr_t);
int getsid(int);
int kill(int, int);
int syslog(int, uintptr_t, size_t);
int mkdir(int, uintptr_t, unsigned int);
int mkdirat(int, uintptr_t, unsigned int);
int mkfifo(uintptr_t, unsigned int);
int mknod(uintptr_t, unsigned int, int);
int mknodat(int, uintptr_t, unsigned int, int);
int nanosleep(uintptr_t, uintptr_t);
int open64(uintptr_t, int, unsigned int);
@@ -502,6 +504,17 @@ func Klogctl(typ int, buf []byte) (n int, err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdir(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
@@ -524,6 +537,17 @@ func Mkfifo(path string, mode uint32) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknod(C.uintptr_t(_p0), C.uint(mode), C.int(dev))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev))

View File

@@ -39,8 +39,10 @@ int getrusage(int, uintptr_t);
int getsid(int);
int kill(int, int);
int syslog(int, uintptr_t, size_t);
int mkdir(int, uintptr_t, unsigned int);
int mkdirat(int, uintptr_t, unsigned int);
int mkfifo(uintptr_t, unsigned int);
int mknod(uintptr_t, unsigned int, int);
int mknodat(int, uintptr_t, unsigned int, int);
int nanosleep(uintptr_t, uintptr_t);
int open64(uintptr_t, int, unsigned int);
@@ -502,6 +504,17 @@ func Klogctl(typ int, buf []byte) (n int, err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdir(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
@@ -524,6 +537,17 @@ func Mkfifo(path string, mode uint32) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknod(C.uintptr_t(_p0), C.uint(mode), C.int(dev))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev))

View File

@@ -417,6 +417,16 @@ func Chroot(path string) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ClockGetres(clockid int32, res *Timespec) (err error) {
_, _, e1 := Syscall(SYS_CLOCK_GETRES, uintptr(clockid), uintptr(unsafe.Pointer(res)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ClockGettime(clockid int32, time *Timespec) (err error) {
_, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0)
if e1 != 0 {

Some files were not shown because too many files have changed in this diff Show More