Compare commits

...

No commits in common. "master" and "gh-pages" have entirely different histories.

768 changed files with 5 additions and 150561 deletions

View File

@ -1,17 +0,0 @@
# 版权 @2022 凹语言 作者。保留所有权利。
name: Close PRs
on:
pull_request_target:
types: [opened]
jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: superbrothers/close-pull-request@v3
with:
# Optional. Post a issue comment just before closing a pull request.
comment: "这里是镜像仓库, 不接受 PR, 请移步 https://gitee.com/wa-lang"

View File

@ -1,36 +0,0 @@
name: Deploy
on:
push:
branches:
- master
pull_request:
branches:
- master
types:
- closed
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- run: make -C internal/app/wawasm
- run: make -C waroot/examples/snake publish
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
personal_token: ${{ secrets.WA_DEPLOY }}
publish_dir: docs
publish_branch: gh-pages
force_orphan: true
user_name: "github-actions[bot]"
user_email: "github-actions[bot]@users.noreply.github.com"

View File

@ -1,45 +0,0 @@
# https://github.com/goreleaser/goreleaser-action
name: Release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
Test:
runs-on: ubuntu-latest
if: ${{github.repository == 'wa-lang/wa'}}
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- run: make ci-test-all
Publish:
runs-on: ubuntu-latest
if: ${{github.repository == 'wa-lang/wa'}}
needs: [Test]
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v4
with:
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.WA_DEPLOY }}

View File

@ -1,89 +0,0 @@
# 版权 @2022 凹语言 作者。保留所有权利。
name: Wa
on:
pull_request:
push:
branches:
- main
- master
- "releases/*"
jobs:
build-and-test-ubuntu:
runs-on: ubuntu-latest
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- run: go version
- run: go env
- run: make ci-test-all
- run: go test -v -coverprofile=profile.cov ./...
- run: go install
- run: wa -h
- run: cd waroot && wa run examples/prime
- run: cd waroot && wa run hello.wa
- run: cd waroot && wa run -target=chrome hello.wa
- uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: profile.cov
build-and-test-windows:
runs-on: windows-latest
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- run: go version
- run: go env
- run: make ci-test-all
- run: go test -v ./...
- run: go install
- run: wa -h
- run: cd waroot && wa run examples/prime
- run: cd waroot && wa run hello.wa
- run: cd waroot && wa run -target=chrome hello.wa
build-and-test-macos:
runs-on: macos-12
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- run: go version
- run: go env
- run: make ci-test-all
- run: go test -v ./...
- run: go install
- run: wa -h
- run: cd waroot && wa run examples/prime
- run: cd waroot && wa run hello.wa
- run: cd waroot && wa run -target=chrome hello.wa

25
.gitignore vendored
View File

@ -1,25 +0,0 @@
/.fleet
/.vscode
/_build*
/hello
wa
wa.exe
wat2wasm
wat2wasm.exe
*.exe
*.dll
*.a
*.so
*.dylib
*.ll
*.s
*.out*
*.wasm
*.wasm.*
y.wa.*
/docs/snake/*
_target

View File

@ -1,86 +0,0 @@
# This is an example .goreleaser.yml file with some sane defaults.
# Make sure to check the documentation at http://goreleaser.com
before:
hooks:
- go version
builds:
- id: default
env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm64
# 使用 ldflags="-s -w" 去掉符号表和调试信息,以减少发布包的大小
ldflags:
- -s
- -w
ignore:
- goos: linux
goarch: arm64
- goos: windows
goarch: arm64
main: .
archives:
- id: default
builds:
- default
name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
format_overrides:
- goos: windows
format: zip
checksum:
name_template: 'checksums.txt'
changelog:
use: github
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
release:
github:
owner: wa-lang
name: wa
draft: false
footer: |
Homepage https://wa-lang.org
brews:
- tap:
owner: wa-lang
name: homebrew-tap
url_template: "https://github.com/wa-lang/wa/releases/download/{{ .Tag }}/{{ .ArtifactName }}"
download_strategy: CurlDownloadStrategy
# Git author used to commit to the repository.
# Defaults are shown.
commit_author:
name: GoReleaser Bot
email: goreleaser@carlosbecker.com
folder: HomebrewFormula
homepage: "https://github.com/wa-lang/wa"
description: "The Wa Programming Language"
license: "AGPL-3.0 license"
skip_upload: false
test: |
system "#{bin}/wa"
scoop:
url_template: "https://github.com/wa-lang/wa/releases/download/{{ .Tag }}/{{ .ArtifactName }}"
bucket:
owner: wa-lang
name: scoop-bucket
branch: master
token: "{{ .Env.GITHUB_TOKEN }}"
folder: Scoops
commit_author:
name: goreleaserbot
email: bot@goreleaser.com
commit_msg_template: "Scoop update for {{ .ProjectName }} version {{ .Tag }}"
homepage: "http://github.com/wa-lang/wa"
description: "The Wa Programming Language"
license: AGPL-3.0 license

View File

@ -1,70 +0,0 @@
version: '1.0'
name: branch-pipeline
displayName: BranchPipeline
stages:
- stage:
name: compile
displayName: 编译
steps:
- step: build@golang
name: build_golang
displayName: Golang 构建
# 支持1.8、1.10、1.11、1.12、1.13、1.14、1.15、1.16八个版本
golangVersion: 1.17
# 构建命令
commands: |
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go test -v ./...
mkdir -p output/wa-lang-darwin
mkdir -p output/wa-lang-linux64
mkdir -p output/wa-lang-win64
GOOS=darwin GOARCH=amd64 go build -o output/wa-lang-darwin/wa main.go
GOOS=linux GOARCH=amd64 go build -o output/wa-lang-linux64/wa main.go
GOOS=windows GOARCH=amd64 go build -o output/wa-lang-win64/wa.exe main.go
chmod +X output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa -h
#./output/wa-lang-linux64/wa waroot/hello.wa
#./output/wa-lang-linux64/wa run waroot/examples/prime
#./output/wa-lang-linux64/wa run waroot/hello.wa
# 非必填字段开启后表示将构建产物暂存但不会上传到制品库中7天后自动清除
artifacts:
# 构建产物名字作为产物的唯一标识可向下传递支持自定义默认为BUILD_ARTIFACT。在下游可以通过${BUILD_ARTIFACT}方式引用来获取构建物地址
- name: BUILD_ARTIFACT
# 构建产物获取路径,是指代码编译完毕之后构建物的所在路径
path:
- ./output
- step: publish@general_artifacts
name: publish_general_artifacts
displayName: 上传制品
# 上游构建任务定义的产物名默认BUILD_ARTIFACT
dependArtifact: BUILD_ARTIFACT
# 上传到制品库时的制品命名默认output
artifactName: output
dependsOn: build_golang
- stage:
name: release
displayName: 发布
steps:
- step: publish@release_artifacts
name: publish_release_artifacts
displayName: '发布'
# 上游上传制品任务的产出
dependArtifact: output
# 发布制品版本号
version: '1.0.0.0'
# 是否开启版本号自增,默认开启
autoIncrement: true
triggers:
push:
branches:
exclude:
- master
include:
- .*

View File

@ -1,68 +0,0 @@
version: '1.0'
name: master-pipeline
displayName: MasterPipeline
stages:
- stage:
name: compile
displayName: 编译
steps:
- step: build@golang
name: build_golang
displayName: Golang 构建
# 支持1.8、1.10、1.11、1.12、1.13、1.14、1.15、1.16八个版本
golangVersion: 1.17
# 构建命令
commands: |
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,
go test -v ./...
mkdir -p output/wa-lang-darwin
mkdir -p output/wa-lang-linux64
mkdir -p output/wa-lang-win64
GOOS=darwin GOARCH=amd64 go build -o output/wa-lang-darwin/wa main.go
GOOS=linux GOARCH=amd64 go build -o output/wa-lang-linux64/wa main.go
GOOS=windows GOARCH=amd64 go build -o output/wa-lang-win64/wa.exe main.go
chmod +X output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa -h
#./output/wa-lang-linux64/wa waroot/hello.wa
#./output/wa-lang-linux64/wa run waroot/examples/prime
#./output/wa-lang-linux64/wa run waroot/hello.wa
# 非必填字段开启后表示将构建产物暂存但不会上传到制品库中24小时后自动清除
artifacts:
# 构建产物名字作为产物的唯一标识可向下传递支持自定义默认为BUILD_ARTIFACT。在下游可以通过${BUILD_ARTIFACT}方式引用来获取构建物地址
- name: BUILD_ARTIFACT
# 构建产物获取路径,是指代码编译完毕之后构建物的所在路径
path:
- ./output
- step: publish@general_artifacts
name: publish_general_artifacts
displayName: 上传制品
# 上游构建任务定义的产物名默认BUILD_ARTIFACT
dependArtifact: BUILD_ARTIFACT
# 上传到制品库时的制品命名默认output
artifactName: output
dependsOn: build_golang
- stage:
name: release
displayName: 发布
steps:
- step: publish@release_artifacts
name: publish_release_artifacts
displayName: '发布'
# 上游上传制品任务的产出
dependArtifact: output
# 发布制品版本号
version: '1.0.0.0'
# 是否开启版本号自增,默认开启
autoIncrement: true
triggers:
push:
branches:
include:
- master

View File

@ -1,55 +0,0 @@
version: '1.0'
name: pr-pipeline
displayName: PRPipeline
stages:
- stage:
name: compile
displayName: 编译
steps:
- step: build@golang
name: build_golang
displayName: Golang 构建
# 支持1.8、1.10、1.11、1.12、1.13、1.14、1.15、1.16八个版本
golangVersion: 1.17
# 构建命令
commands: |
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,
go test -v ./...
mkdir -p output/wa-lang-darwin
mkdir -p output/wa-lang-linux64
mkdir -p output/wa-lang-win64
GOOS=darwin GOARCH=amd64 go build -o output/wa-lang-darwin/wa main.go
GOOS=linux GOARCH=amd64 go build -o output/wa-lang-linux64/wa main.go
GOOS=windows GOARCH=amd64 go build -o output/wa-lang-win64/wa.exe main.go
chmod +X output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa
./output/wa-lang-linux64/wa -h
#./output/wa-lang-linux64/wa waroot/hello.wa
#./output/wa-lang-linux64/wa run waroot/examples/prime
#./output/wa-lang-linux64/wa run waroot/hello.wa
# 非必填字段开启后表示将构建产物暂存但不会上传到制品库中7天后自动清除
artifacts:
# 构建产物名字作为产物的唯一标识可向下传递支持自定义默认为BUILD_ARTIFACT。在下游可以通过${BUILD_ARTIFACT}方式引用来获取构建物地址
- name: BUILD_ARTIFACT
# 构建产物获取路径,是指代码编译完毕之后构建物的所在路径
path:
- ./output
- step: publish@general_artifacts
name: publish_general_artifacts
displayName: 上传制品
# 上游构建任务定义的产物名默认BUILD_ARTIFACT
dependArtifact: BUILD_ARTIFACT
# 上传到制品库时的制品命名默认output
artifactName: output
dependsOn: build_golang
triggers:
pr:
branches:
include:
- master

661
LICENSE
View File

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View File

@ -1,35 +0,0 @@
# 版权 @2019 凹语言 作者。保留所有权利。
hello:
go install
cd waroot && go run ../main.go run hello.wa
prime:
cd waroot && go run ../main.go run examples/prime
build-wasm:
GOARCH=wasm GOOS=js go build -o wa.out.wasm ./main_wasm.go
arduino-run:
go run main.go -target=arduino arduino.wa
arduino-build:
go run main.go build -target=arduino arduino.wa
wat2wasm a.out.wat -o a.out.wasm
xxd -i a.out.wasm > app.wasm.h
ci-test-all:
go install
go test ./...
@echo "== std test begin =="
go run main.go test std
@echo "== std ok =="
go run main.go run ./waroot/hello.wa
cd waroot && go run ../main.go run hello.wa
make -C ./waroot/examples ci-test-all
clean:
-rm a.out*

View File

@ -1,151 +0,0 @@
<div align="center">
<h1>凹语言</h1>
[主页](https://wa-lang.org) | [Playground](https://wa-lang.org/playground) | [路线](https://wa-lang.org/smalltalk/st0001.html) | [社区](https://wa-lang.org/community) | [日志](https://wa-lang.org/guide/changelog.html)
</div>
凹语言凹读音“Wā”是 针对 WASM 平台设计的通用编程语言,同时支持 Linux、macOS 和 Windows 等主流操作系统和 Chrome 等浏览器环境,同时也支持作为独立 Shell 脚本和被嵌入脚本模式执行。
![](docs/images/logo/logo-animate1.svg)
- 主页: [https://wa-lang.org](https://wa-lang.org)
- 参考手册: [https://wa-lang.org/man/](https://wa-lang.org/man/)
- 仓库(Gitee): [https://gitee.com/wa-lang/wa](https://gitee.com/wa-lang/wa)
- 仓库(Github): [https://github.com/wa-lang/wa](https://github.com/wa-lang/wa)
- Playground: [https://wa-lang.org/playground](https://wa-lang.org/playground)
> 说明: 除非特别声明,凹语言代码均以 AGPL-v3 开源协议授权, 具体可以参考 LICENSE 文件。
## 如何参与开发
项目尚处于原型开源阶段如果有共建和PR需求请参考 [如何贡献代码](https://wa-lang.org/community/contribute.html)。我们不再接受针对第三方依赖库修改的 PR。
> 特别注意向本仓库提交PR视同您认可并接受[凹语言贡献者协议](https://gitee.com/organizations/wa-lang/cla/wca)但在实际签署之前您的PR不会被评审或接受。
## Playground 在线预览
[https://wa-lang.org/playground](https://wa-lang.org/playground)
![](https://wa-lang.org/playground-01.png)
## 贪吃蛇游戏
- [https://wa-lang.org/wa/snake/](https://wa-lang.org/wa/snake/)
- [https://wa-lang.org/smalltalk/st0018.html](https://wa-lang.org/smalltalk/st0018.html)
![](https://wa-lang.org/st0018-03.jpg)
## 例子: 凹语言
打印字符和调用函数:
```wa
import "fmt"
global year: i32 = 2023
func main {
println("hello, Wa!")
println(add(40, 2), year)
fmt.Println(1+1)
}
func add(a: i32, b: i32) => i32 {
return a+b
}
```
运行并输出结果:
```
$ wa run hello.wa
你好,凹语言!
42 2023
2
```
## 例子: 打印素数
打印 30 以内的素数:
```wa
// 版权 @2021 凹语言™ 作者。保留所有权利。
func main {
for n := 2; n <= 30; n = n + 1 {
isPrime: int = 1
for i := 2; i*i <= n; i = i + 1 {
if x := n % i; x == 0 {
isPrime = 0
}
}
if isPrime != 0 {
println(n)
}
}
}
```
运行并输出结果:
```
$ cd waroot && wa run examples/prime
2
3
5
7
11
13
17
19
23
29
```
## 例子:用中文语法打印素数
```wz
引于 "书"
【启】:
// 打印30以内的素数
从n=2到n>30有n++
设素=1
从i=2到i*i>n有i++
设x=n%i
若x==0则
素=0
若素!=0则
书·曰n
```
运行的结果和英文语法的示例相同。
更多例子 [waroot/examples](waroot/examples)
## 贡献者名单
|贡献者|贡献点|
| --- | --- |
|柴树杉| 35000|
|丁尔男| 42500|
|史斌 | 29000|
|扈梦明| 14000|
|赵普明| 17000|
|宋汝阳| 2000|
|刘云峰| 1000|
|王湘南| 1000|
|王泽龙| 1000|
|吴烜 | 3000|
|刘斌 | 2500|
|尹贻浩| 2000|
贡献点变更记录见 [waroot/cplog](waroot/cplog) 目录。

151
README.md
View File

@ -1,151 +0,0 @@
<div align="center">
<h1>The Wa Programming Language</h1>
[简体中文](https://github.com/wa-lang/wa/blob/master/README-zh.md) | [English](https://github.com/wa-lang/wa/blob/master/README.md)
</div>
<div align="center">
[![Build Status](https://github.com/wa-lang/wa/actions/workflows/wa.yml/badge.svg)](https://github.com/wa-lang/wa/actions/workflows/wa.yml)
[![Coverage Status](https://coveralls.io/repos/github/wa-lang/wa/badge.svg)](https://coveralls.io/github/wa-lang/wa)
[![GitHub release](https://img.shields.io/github/v/tag/wa-lang/wa.svg?label=release)](https://github.com/wa-lang/wa/releases)
[![license](https://img.shields.io/github/license/wa-lang/wa.svg)](https://github.com/wa-lang/wa/blob/master/LICENSE)
</div>
Wa is a general-purpose programming language designed for developing robustness and maintainability WebAssembly software.
Instead of requiring complex toolchains to set up, you can simply go install it - or run it in a browser.
![](docs/images/logo/logo-animate1.svg)
- Home: [https://wa-lang.github.io/](https://wa-lang.github.io/)
- Manual: [https://wa-lang.github.io/man/en/](https://wa-lang.github.io/man/en/)
- Github: [https://github.com/wa-lang/wa](https://github.com/wa-lang/wa)
- Playground: [https://wa-lang.org/playground](https://wa-lang.org/playground)
> Note: Our canonical Git repository is located at https://gitee.com/wa-lang/wa. There is a mirror of the repository at https://github.com/wa-lang/wa. Unless otherwise noted, the Wa source files are distributed under the AGPL-v3 license found in the LICENSE file.
## Playground
[https://wa-lang.org/playground](https://wa-lang.org/playground)
![](https://wa-lang.org/playground-01.png)
## Snake Game
- Play: [https://wa-lang.org/wa/snake/](https://wa-lang.org/wa/snake/)
- Code: [waroot/examples/snake/README-en.md](waroot/examples/snake/README-en.md)
![](https://wa-lang.org/st0018-03.jpg)
## Example: Print Wa
Print rune and call function
```wa
import "fmt"
global year: i32 = 2023
func main {
println("hello, Wa!")
println(add(40, 2), year)
fmt.Println(1+1)
}
func add(a: i32, b: i32) => i32 {
return a+b
}
```
Execute the program:
```
$ wa run hello.wa
hello, Wa!
42 2023
2
```
## Example: Print Prime
Print prime numbers up to 30:
```wa
func main {
for n := 2; n <= 30; n = n + 1 {
isPrime: int = 1
for i := 2; i*i <= n; i = i + 1 {
if x := n % i; x == 0 {
isPrime = 0
}
}
if isPrime != 0 {
println(n)
}
}
}
```
Execute the program:
```
$ cd waroot && wa run examples/prime
2
3
5
7
11
13
17
19
23
29
```
## Example: Print Prime with Chinese syntax
Print prime numbers up to 30:
```wz
引于 "书"
【启】:
// 输出30以内的素数
从n=2到n>30有n++
设素=1
从i=2到i*i>n有i++
设x=n%i
若x==0则
素=0
若素!=0则
书·曰n
```
Output is the same as the previous example.
More examples [waroot/examples](waroot/examples)
## Contributors
|Contributor|Contribution points|
| --- | --- |
|柴树杉| 35000|
|丁尔男| 42500|
|史斌 | 29000|
|扈梦明| 14000|
|赵普明| 17000|
|宋汝阳| 2000|
|刘云峰| 1000|
|王湘南| 1000|
|王泽龙| 1000|
|吴烜 | 3000|
|刘斌 | 2500|
|尹贻浩| 2000|

View File

@ -1,110 +0,0 @@
// 版权 @2022 凹语言 作者。保留所有权利。
// 凹语言™ 功能 API 包。
package api
import (
"io/fs"
"wa-lang.org/wa/internal/backends/compiler_wat"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/format"
"wa-lang.org/wa/internal/loader"
"wa-lang.org/wa/internal/logger"
"wa-lang.org/wa/internal/wamime"
)
// 调试参数
var (
FlagDebugMode = &config.DebugMode
FlagEnableTrace_api = &config.EnableTrace_api
FlagEnableTrace_app = &config.EnableTrace_app
FlagEnableTrace_compiler = &config.EnableTrace_compiler
FlagEnableTrace_loader = &config.EnableTrace_loader
)
// 配置参数, 包含文件系统和 OS 等信息
type Config = config.Config
// 模块元信息, 主包路径
type Manifest = config.Manifest
// 模块元信息中的包信息
type Manifest_package = config.Manifest_package
// 程序对象, 包含全量的 AST 和 SSA 信息, 经过语义检查
type Program = loader.Program
// 包虚拟文件系统
type PkgVFS = config.PkgVFS
// 指针和整数大小
type StdSize = config.StdSizes
// 默认配置
func DefaultConfig() *Config {
return config.DefaultConfig()
}
// 加载 WaModFile 文件
// 如果 vfs 为空则从本地文件系统读取
func LoadManifest(vfs fs.FS, appPath string) (p *Manifest, err error) {
return config.LoadManifest(vfs, appPath)
}
// 加载程序
// 入口 appPath 是包对应目录的路径
func LoadProgram(cfg *config.Config, appPath string) (*Program, error) {
return loader.LoadProgram(cfg, appPath)
}
// 加载单文件程序
// 入口 appPath 是包对应目录的路径
func LoadProgramFile(cfg *config.Config, filename string, src interface{}) (*Program, error) {
return loader.LoadProgramFile(cfg, filename, src)
}
// 基于 VFS 加载程序
// 入口 pkgPath 是包路径, 必须是 vfs.App 子包
func LoadProgramVFS(vfs *config.PkgVFS, cfg *config.Config, pkgPath string) (*Program, error) {
return loader.LoadProgramVFS(vfs, cfg, pkgPath)
}
// 构建 wat 目标
func BuildFile(cfg *config.Config, filename string, src interface{}) (wat []byte, err error) {
prog, err := LoadProgramFile(cfg, filename, src)
if err != nil || prog == nil {
logger.Tracef(&config.EnableTrace_api, "LoadProgramVFS failed, err = %v", err)
return nil, err
}
watOut, err := compiler_wat.New().Compile(prog, "main")
return []byte(watOut), err
}
// 构建 wat 目标
func BuildVFS(cfg *config.Config, vfs *config.PkgVFS, appPkg string) (wat []byte, err error) {
prog, err := LoadProgramVFS(vfs, cfg, appPkg)
if err != nil || prog == nil {
logger.Tracef(&config.EnableTrace_api, "LoadProgramVFS failed, err = %v", err)
return nil, err
}
watOut, err := compiler_wat.New().Compile(prog, "main")
return []byte(watOut), err
}
// 格式化代码
func FormatCode(filename, code string) (string, error) {
data, _, err := format.File(nil, filename, code)
if err != nil {
return "", err
}
return string(data), nil
}
// 获取代码语法类型
func GetCodeSyntax(filename string, code []byte) string {
return wamime.GetCodeMime(filename, code)
}

View File

@ -1,32 +0,0 @@
// 版权 @2022 凹语言 作者。保留所有权利。
//go:build !wasm
// +build !wasm
package api
import (
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/wabt"
"wa-lang.org/wa/internal/wazero"
)
// 执行凹代码
func RunCode(cfg *config.Config, filename, code string, args ...string) (stdoutStderr []byte, err error) {
// 编译为 wat 格式
watBytes, err := BuildFile(cfg, filename, code)
if err != nil {
return
}
// wat 编译为 wasm
wasmBytes, err := wabt.Wat2Wasm(watBytes)
if err != nil {
return
}
// main 执行
stdout, stderr, err := wazero.RunWasm(cfg, filename, wasmBytes, args...)
stdoutStderr = append(stdout, stderr...)
return
}

View File

@ -1,86 +0,0 @@
// 版权 @2022 凹语言 作者。保留所有权利。
package api_test
import (
"fmt"
"log"
"wa-lang.org/wa/api"
)
func ExampleRunCode() {
const code = `
global gBase: i32 = 1000
func main() {
println(add(40, 2) + gBase)
}
func add(a: i32, b: i32) => i32 {
return a+b
}
`
output, err := api.RunCode(api.DefaultConfig(), "hello.wa", code)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(output))
// Output:
// 1042
}
func ExampleRunCode_args() {
const code = `
import "os"
func main {
for i, s := range os.Args[1:] {
println(i, ":", s)
}
}
`
args := []string{"aa", "bb"}
output, err := api.RunCode(api.DefaultConfig(), "hello.wa", code, args...)
if err != nil {
if len(output) != 0 {
log.Println(string(output))
}
log.Fatal(err)
}
fmt.Print(string(output))
// Output:
// 0 : aa
// 1 : bb
}
func ExampleRunCode_wz() {
const code = `
#wa:syntax=wz
引于 "书"
·"你好,凹语言中文版!"
`
output, err := api.RunCode(api.DefaultConfig(), "hello.wa", code)
if err != nil {
if len(output) != 0 {
log.Println(string(output))
}
log.Fatal(err)
}
fmt.Print(string(output))
// Output:
// 你好,凹语言中文版!
}

View File

@ -1,20 +0,0 @@
// 版权 @2022 凹语言 作者。保留所有权利。
package api_test
import (
"fmt"
"wa-lang.org/wa/api"
)
func ExampleFormatCode() {
s, err := api.FormatCode("hello.wa", "func add(a:i32, b:i32)=>i32 {return a+b}")
if err != nil {
panic(err)
}
fmt.Println(s)
// Output:
// func add(a: i32, b: i32) => i32 { return a + b }
}

View File

@ -1,54 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package api
import (
"wa-lang.org/wa/internal/config"
)
// wa 代码:
// xxx.wa
// xxx_$OS.wa
// xxx_$ARCH.wa
// xxx_$OS_$ARCH.wa
// wz 中文代码:
// xxx.wz
// xxx_$OS.wz
// xxx_$ARCH.wz
// xxx_$OS_$ARCH.wz
// ws 汇编代码:
// xxx.$BACKEND.ws
// xxx_$OS.$BACKEND.ws
// xxx_$ARCH.$BACKEND.ws
// xxx_$OS_$ARCH.$BACKEND.ws
// 编译器后端类型
const (
WaBackend_Default = config.WaBackend_Default // 默认
WaBackend_clang = config.WaBackend_clang // 输出 c
WaBackend_llvm = config.WaBackend_llvm // 输出 llir
WaBackend_wat = config.WaBackend_wat // 输出 wat
)
// 目标平台类型, 可管理后缀名
const (
WaOS_Default = config.WaOS_Default // 默认
WaOS_arduino = config.WaOS_arduino // Arduino 平台
WaOS_chrome = config.WaOS_chrome // Chrome 浏览器
WaOS_wasi = config.WaOS_wasi // WASI 接口
)
// 体系结构类型
const (
WaArch_Default = config.WaArch_Default // 默认
WaArch_386 = config.WaArch_386 // 386 平台
WaArch_amd64 = config.WaArch_amd64 // amd64 平台
WaArch_arm64 = config.WaArch_arm64 // arm64 平台
WaArch_riscv64 = config.WaArch_riscv64 // riscv64 平台
WaArch_wasm = config.WaArch_wasm // wasm 平台
)

View File

@ -1,49 +0,0 @@
// 版权 @2022 凹语言 作者。保留所有权利。
//go:build ignore
// +build ignore
package main
import (
"fmt"
"os"
"wa-lang.org/wa/api"
)
func main() {
output, err := api.RunCode(api.DefaultConfig(), "hello.wa", code)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Print(string(output))
output, err = api.RunCode(api.DefaultConfig(), "hello-zh.wz", code_zh)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Print(string(output))
}
const code = `
func main {
println(add(40, 2))
}
func add(a: i32, b: i32) => i32 {
return a+b
}
`
const code_zh = `
引于 "书"
·"你好,凹语言中文版!"
`

Binary file not shown.

Before

Width:  |  Height:  |  Size: 970 B

View File

@ -1,32 +0,0 @@
<!--
// 版权 @2019 凹语言 作者。保留所有权利。
// https://wa-lang.org
-->
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 400 400" width="400" height="400"
style="border: 0px solid red"
>
<path
stroke="none" fill="LightSeaGreen"
d="M60,50 h90 v100 h100 v-100 h90 l10,10 v280 l-10,10 h-280 l-10,-10 v-280"
/>
<path
stroke="none" fill="white"
d="M100,100 m-5,-5 h10 v10 h-10"
/>
<path
stroke="none" fill="white"
d="M400,100 m-100,0 m-5,-5 h10 v10 h-10"
/>
<path
stroke="white" fill="none" stroke-width="8" stroke-linecap="round"
d="M200,230 l34,34 l34,-34 M200,230 l-34,34 l-34,-34"
/>
</svg>

Before

Width:  |  Height:  |  Size: 628 B

View File

@ -1,605 +0,0 @@
# 语言规范
## 1 EBNF 记法
凹语言中文语法使用扩展的巴克斯-诺尔范式EBNF定义
```
Production = production_name "=" [ Expression ] "." .
Expression = Alternative { "|" Alternative } .
Alternative = Term { Term } .
Term = production_name | token [ "…" token ] | Group | Option | Repetition .
Group = "(" Expression ")" .
Option = "[" Expression "]" .
Repetition = "{" Expression "}" .
```
其中生成式由表达式构造,表达式通过术和以下操作符构造,自上而下优先级递增(低到高):
```
| 选择
() 分组
[] 可选0 或 1 次)
{} 重复0 到 n 次)
```
用小写生成式名用于标识词法标记。使用非最终Non-terminals词法标记使用驼峰记法CamelCase。而位于双引号 "" 内的即为词法标记。形式 a … b 表示把从 a 到 b 的字符集作为选择项。横向省略号 … 也在本文档中非正式地表示各种列举或简略的代码片断。单个字符 …(不同于三个字符 ...)并非凹语言本身的标记。
## 2 源文件表示
为了更好支持中文和其他语言地区的编程,凹语言源码为采用 UTF-8 编码的 Unicode 文本表示。每个码点都是不同的,例如,大写与小写的字母就是不同的字符。同时为了兼容 C 语言字符串的习惯,编译器会阻止字符 NULU+0000出现在源码文本中。此外如果源文件开头有 BOM 头部,则编译器应该忽略它。为了遵循流行编程语言的习惯,下划线字符被作为字母对待。
## 3 词法元素
### 3.1 注释
凹语言默认采用行注释,以 `//` 开头的表示行注释。注释不能从字符或字符串字面中开始,也不能在其它注释中。行注释可以视做一个换行符。
### 3.2 词符类型Token
构成凹语言的词符类型有:
- 关键字,如`若`。
- 标识符,如变量名称。
- 面值常量,如整数`123`、字符串`"abc"`、
- 运算操作符,如`+`、`-`。
- 分隔符,如`【】`、``。空白字符` `可用于分隔关键字和标识符。
凹语言程序源码首先会通过词法解析,转化为有效的词符序列,便于后续的语法解析工作。
### 3.2 基本字符
凹语言中文版的基本字符包括:
```
数字 = "0" … "9" .
16进制数字 = "0" … "9" | "a" … "f" | "A" … "F" .
字母 = "a" … "z" | "A" … "Z" | "_" | Unicode字母
Unicode字母 = /* 类别为"Letter"的Unicode字符 */ .
```
Unicode字符的“Letter”类别是Unicode标准定义的类别。凹语言根据Unicode标准来判定一个字符是否符合“Letter”类别。
### 3.3 标识符Identifier
标识符用做函数、变量、类型等程序实体的名称。一个标识符由一个或多个字母和数字组成。标识符的第一个字符必须是字母,以便于和数字面值区分。
```
标识符 = 字母 { 字母 | 数字 } .
```
标识符的示例:
```
a
实例
_obj
z123
这是_一个_很长_的_变量
```
### 3.5 关键字
关键字也是由字母组成的词符,但与标识符不同的是,它们是语言预先定义好的保留词,有特殊的语法意义,不能用于变量名称等。
凹中文版目前的关键字有:
```
引于 归于 设 之
若 则 又若 否则
从 到 有 直到
自 至 当 为
且......或
停之 续之
```
凹中文版还处于早期探索阶段,后续可能添加或修改新的关键字。
### 3.6 运算符
以下是凹中文版的运算符和与标点:
```
+ - * /
+= -= *= /=
++ -- ! &
【 】
《 》 〈 〉
[ ] { }
。 =>
```
运算符用于组成表达式,标点用于组成或分隔语句。
### 3.7 字面值
字面值是在凹语言代码中明确写出的值,有布尔值、整数、浮点数、字符串、字符几种类型。其中布尔值有`真`、`假`;整数字面值有二进制、八进制、十进制、十六进制几种表示格式;浮点数字面值有小数、科学计数法和十六进制浮点数几种形式;字符串有普通字符串和支持多行的原生字符串几种形式;字符则是有单引号包含表示单个字符。所有的字面值都是无类型的常量。
普通字符串和字符面值支持的转义符号:
```
\a U+0007 警报或铃声
\b U+0008 退格
\f U+000C 换页
\n U+000A 换行
\r U+000D 回车
\t U+0009 横向制表符
\v U+000b 纵向制表符
\\ U+005c 反斜杠
\' U+0027 单引号(仅在符文字面中有效)
\" U+0022 双引号(仅在字符串字面中有效)
```
以下是常见的字面值常量:
```
# 布尔字面值
# 整数
42
4_2
0600
0_600
-42
# 浮点数
0.
72.40
3.1415926
1_5. # == 15.0
0.15e+0_2 # == 15.0
0x1p-2 # == 0.25
0x2.p10 # == 2048.0
# 字符串
"凹语言" # UTF-8 输入的文本
`凹语言` # UTF-8 输入的原始字面文本
"\u65e5\u672c\u8a9e" # 显式的 Unicode 码点
"\U000065e5\U0000672c\U00008a9e" # 显式的 Unicode 码点
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" # 显式的 UTF-8 字节
# 字符
'凹'
'a'
'ä'
'\t'
'\000'
'\007'
'\xff'
'\u12e4'
'\U00101234'
```
如果源码将两个码点表示为一个字符,例如包含着重号和字母的结合形式,凹语言会当作两个字面处理(因此不能作为字符面值)。
## 4 常量
常量由字面值或常量表达式产生,包含布尔常量、字符常量、整数常量、浮点数常量和字符串常量几种。其中字符、整数、浮点数常量统称为数值常量。
数值类型常量可表示任意精度的精确值而不受到逻辑现在,因此也就没有整数溢出和 IEEE-754 浮点数的一些限制。常量可以是有类型化的或无类型化的。字面常量、真、假某些只包含无类型化操作数的常量表达式产生的新常量结构也是无类型化的。
无类型化的常量有一个默认类型,也就是当上下文中需要类型化常量时通过隐式转换出来的类型, 例如在 `设i=0` 这种无显示类型的短变量声明中会被作为`数`int类型。
语言提提供了几个默认类型:
- `布尔`,即`真`或`假`,对应英文版的`bool`
- `字`,即单个字符,如`a`、`甲`等,对应英文版的`rune`
- `数`,整数,对应英文版的`int`,整数类型还对应了几个不同位宽的类型,如`数8`表示用8为字节存储的整数。
- `小数`,浮点数,对应英文版的`float`
- `文`,文本,即字符串,对应英文版的`string`
尽管数值型常量值域无逻辑限制,但是实现时要求编译器至少有 256bit 表示整数常量和浮点数常量,如果发生溢出则需要在编译阶段给出一个错误。
## 5 变量
凹语言中变量是内存用用于保存值的存储位置,或者叫可被取地址的值。变量允许值的集合由其类型确定,比如 `数8` 类型表示 -128 到 127 的整数集合、`布尔`表示 `真``假`的布尔值集合。
变量又分为具名和匿名两种:具名变量通过标识符引用、而匿名变量通过指针来引用。变量的静态类型在声明时确定,可以明确指定或者由初始化的值类型推导。变量的值可通过在表达式中引用变量取得。如果变量尚未赋值,其值即为其类型的零值。
零值从直观上表示内存中都是0的状态布尔类型对应 `假`、数值类型对应 0、字符串对应空字符串`""`、指针和切片对应 `空`。如果是复合类型则其组成的元素均是零值。
```
设甲之布尔 # `甲`是布尔类型
设x # x值为空类型为`万物`即interface{}
设v之*T # v值为空类型为*T
```
全部的变量组成了程序的状态,也就是所谓的上下文信息。
## 6 类型
类型不仅仅决定了值的集合,同时还定义了与该类型值特定的操作集合。已命名类型可通过类型名指定。未命名类型可通过类型字面指定,它将根据既有的类型组成新的类型。
类型的 EBNF 语法如下:
```
类型定义 = "《" 类型名称 "》" ( "=" 类型面值 | ":" 类型成员列表 "。" ) .
类型名称 = 标识符 .
类型面值 = 数组类型 | 结构类型 | 指针类型 | 函数类型 | 接口类型 | 切片类型 | 映射类型 .
类型成员列表 = 类型成员 { "," 类型成员 } .
类型成员 = 成员名称 [ "之" 类型 ] .
成员名称 = 标识符 .
```
类型的定义有两种形式,一种是类型别名,用`=`表示,另一种是结构性类型,用`:`后接成员列表。
布尔值、数值与字符串类型的实例的命名是预声明的`布尔`、`数`、`文`等。 数组、结构体、指针、函数、接口、切片和映射这些复合类型可由类型字面再进行构造。
下面是定义类型的例子:
```
// 定义一个新的类型别名名字叫“字节”它实际上是“正8”整数类型的别名
《字节》 = 正8
// 定义一个新类型别名,名称叫“缓冲区”,它实际上是一个“字类型”的定长数组,即英文版的`[1024]byte`
《缓冲区》 = [字1024]
// 定义一个新的类型别名,名字叫“字典”,它实际上是一个“文”类型的映射,即英文版的`map[string]string`
《字典》 = {文:文}
// 定义一个结构性类型,名字叫“点”,它有“横”与“纵”两个成员,分别代表横坐标和纵坐标
《点》:
横之数
纵之数
```
其中 `字节`、`缓冲区`和`字典`都是类型的别名(即不产生新类型对象),而`点`则产生新的类型。
### 5.1 布尔类型
预声明的布尔类型为 bool。布尔类型表示由预声明常量 true 和 false 所代表的布尔值的集。
### 5.2 数值类型
数值类型表示整数值和浮点数值的集合。预声明和架构无关的预声明数值类型:
```
u8 所有无符号 8 位整数集0 到 255
u16 所有无符号 16 位整数集0 到 65535
u32 所有无符号 32 位整数集0 到 4294967295
u64 所有无符号 64 位整数集0 到 18446744073709551615
i8 所有带符号 8 位整数集(-128 到 127
i16 所有带符号 16 位整数集(-32768 到 32767
i32 所有带符号 32 位整数集(-2147483648 到 2147483647
i64 所有带符号 64 位整数集(-9223372036854775808 到 9223372036854775807
f32 所有 IEEE-754 32 位浮点数集
f64 所有 IEEE-754 64 位浮点数集
byte u8 的别名
rune i32 的别名
```
比如 i32 表示用 32bit 二进制补码表示的整数值集合。
此外还有大小取决于具体实现的预声明数值类型:
```
uint 32 或 64 位
int 大小与 uint 相同
uintptr 大到足以存储指针值无解释位的无符号整数
```
但是对应凹语言来说,目前 uint/int/uintptr 在 WebAssembly 平台都是用 32bit 表示。
### 5.3 字符串类型
字符串类型为 string表示字符串值的集字符串的值为字节序列。字符串值是只读不可修改的不是绑定到某个字符串值的变量一旦被创建字符串的内容就不能更改。
可使用内建函数 `len` 获取字符串 `s` 的长度。若该字符串为常量,则其长度即为编译时常量。 字符串的字节可通过整数 `0``len(s)-1` 访问。获取这样一个元素的地址是非法的:比如通过 `&s[i]` 访问字符串的第 `i` 个字节的地址是禁止的。
### 5.4 数组类型
数组是单一类型元素的序列,其中长度也是数组类型的一部分。数组的 EBNF 语法如下:
```
ArrayType = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = Type .
```
可使用内建函数 `len` 获取数组的长度,返回的结果一个常量。可通过整数下标 `0``len(a)-1` 访问数组的元素。数组类型总是一维的,但可组合构成多维的类型。
```
[32]byte
[2*N] struct { x, y :i32 }
[9527]*f64
[3][5]int
[2][2][2]f64 // 等价于[2]([2]([2]f64))
```
数组的长度可以使用常量表达式、或者是由初始化面值推导,数组的元素可以是数组从而可以构成多维数组。
### 5.5 切片类型
切片类型是在数组类型基础上抽象的类型,切片类型不包含底层数组的长度信息。切片类型底层是对某个数组的引用,未初始化切片的值为 nil。
可使用内建函数 `len` 获取切片的长度,返回的结果一个变量。可使用内建函数 `cap` 获取切片的容量,返回的结果一个变量。可通过整数下标 `0``len(a)-1` 访问切片的元素。切片一旦初始化,就总是引用一个包含其元素的底层数组。 因此,切片与引用同一个数组的其他切片共享存储;与此相反,不同的数组总是表示其不同的存储。
可以通过 make 内置函数创建切片(容量参赛是可选的):
```
make([]T, length)
make([]T, length, capacity)
```
类似于数组,切片总是一维的,但可组合构造多维切片对象。因为多维切片和多维数组的底层数据布局差异,其内部的切片必须单独进行初始化,但是带来的一个灵活性是不同子切片大小可以不同。
### 5.6 结构体类型
结构体和数组类似,数组采用下标来组织相同类型的值,而结构体定义命名的不同类型的元素序列。结构体类型中每一个元素都有一个名字和类型。字段名可显示地指定或通过匿名嵌入字段隐式地指定。在结构体中,字段名必须是唯一的。
```
StructType = "struct" "{" { FieldDecl ";" } "}" .
FieldDecl = (IdentifierList ":" Type | EmbeddedField) [ Tag ] .
EmbeddedField = [ "*" ] TypeName .
Tag = string_lit .
```
下面是结构体的例子:
```
# 空结构体
struct {}
# 带 6 个字段的结构体
struct {
x, y :int
u :f32
_ :f32 # 填充
A :*[]int
F :func()
}
```
通过有类型而无显式字段名声明的字段为匿名字段,亦称为嵌入式字段或该结构体中此种类型的嵌入。 这种字段类型必须作为一个类型名 T 或一个非接口类型名的指针 *T来实现 且 T 本身不能为指针类型。未限定类型名的行为类似于字段名。
```
# 匿名字段的结构体类型
struct {
T1 # 字段名为 T1
*T2 # 字段名为 T2
P.T3 # 字段名为 T3
*P.T4 # 字段名为 T4
x, y :i32 # 字段名为 x 和 y
}
```
字段声明可后跟一个可选的字符串字面值标注:
```
struct {
x, y : f64 "" # 空标注字符串相当于没有标注
name : string "任何字符串都允许作为标注"
_ : [4]byte "这不是一个结构体字段"
}
```
标注是结构体的类型标识的一部分,未来可通过反射机制获得。
### 5.7 指针类型
指针类型表示一个指向所有给定类型变量的指针的集合,其中指向的类型称为指针的基础类型。未初始化的指针的值为 nil。
```
PointerType = "*" BaseType .
BaseType = Type .
```
下面是指针类型的例子:
```
*Point
*[4]int
```
凹语言指针和传统的 C/C++ 指针并不完全相同,目前的实现更偏向引用。
### 5.8 函数类型
凹语言函数类型表示所有带相同形参和返回类型的集合。未初始化的函数类型变量的值为 nil。
```
FunctionType = "func" Signature .
Signature = Parameters [ "=>" Result ] .
Result = Parameters | ":" Type .
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] ":" [ "..." ] Type .
```
在形参或结果的列表中,其名称必须都存在或都不存在。 若存在,则每个名称代表一个指定类型的项,所有在签名中的非空白名称必须是唯一的。 若不存在,则每个类型代表一个此类型的项。若恰好有一个未命名的值,它可能写作一个不加括号的类型,除此之外,形参和结果的列表总是在括号中。
函数签名中加入的最后一个形参可能有一个带 `...` 前缀的类型。 带这样形参的函数被称为变参函数,它可接受零个或多个实参。
```
func()
func(x :int) => int
func(a, _ :int, z :f32) => bool
func(a, b :int, z :f32) => (bool)
func(prefix :string, values :...int)
func(a, b :int, z :f64, opt :...any) => (success bool)
func(int, int, f64) => (f64, *[]int)
func(n :int) => func(p :*T)
```
函数的类型可以用于全局函数、闭包函数、方法值等地方。
### 5.9 接口类型
接口类型定义满足方法列表的类型结合。目前只有结构体才能定义方法。未初始化的接口类型变量的值为 nil。
```
InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
MethodSpec = MethodName Signature .
MethodName = identifier .
InterfaceTypeName = TypeName .
```
下面是一个接口类型定义的方法集合:
```
# 一个简单的 File 接口
interface {
Read(b :[]byte) => (n :int, err :error)
Write(b :[]byte) => (n :int, err :error)
Close()
}
```
如果 T 类型有着接口定义的方法,那么就表示实现了接口:
```
func T.Read(p :[]byte) => (n :int, err :error)
func T.Write(p :[]byte) => (n :int, err :error)
func T.Close() error
```
其中没有定义方法集的 `interface{}` 接口可以包含任何类型的值,同时它有一个 `any` 别名。
### 5.10 map类型
map 是一个同种类型元素的无序组,该类型称为元素类型 映射通过另一类型唯一的键集索引,该类型称为键类型。未初始化的映射值为 nil。
```
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
```
比较操作符 `==``!=` 必须由键类型的操作数完全定义;因此键类型不能是函数、映射或切片。若该键类型为接口类型,这些比较运算符必须由动态键值定义;失败将导致一个异常.
同样通过 make 内置函数创建一个 map
```
make(map[string]int)
make(map[string]int, 100)
```
make创建map时第二个是一个可选的容量估计参数。
## 6 类型与值的性质
## 6.1 类型标识
若两个已命名类型的类型名源自相同的类型实现,它们就是相同的。一个已命名类型和一个未命名类型总不相同。若两个未命名类型其相应的类型字面相同,那么它们的类型相同,即它们的字面结构是否相同且其相应的组件类型是否相同。细节详述:
- 若两个数组类型其元素类型相同且长度相同,那么它们的类型相同。
- 若两个切片类型其元素类型相同,那么它们的类型相同。
- 若两个结构体类型其字段序列相同、相应字段名相同、类型相同、标注相同,那么它们的类型相同。两个匿名字段根据其名字被判定是否相同。
- 若两个指针类型其基础类型相同,那么它们的类型相同。
- 若两个函数类型其形参个数相同、返回值相同、相应形参类型相同、返回值类型相同,那么它们的类型相同。形参和返回值名无需匹配。
- 若两个接口类型其方法集相同、名字相同、函数类型相同,那么它们的类型相同。出自不同包的小写方法名总不相同。两接口类型是否相同与方法的次序无关。
- 若两个map类型其键值类型相同那么它们的类型相同。
若两个类型非相同即为不同。
## 6.2 可赋值性
在下列情况下,值 x 可赋予类型为 T 的变量:
- 当 x 的类型和 T 相同时。
- 当 x 的类型 V 和 T 有相同的 底层类型 且在 V 或 T 中至少有一个不是已命名类型时。
- 当 T 为接口类型且 x 实现了 T 时。
- 当 x 为预声明标识符 nil 且 T 为指针、函数、切片、映射、通道或接口类型时。
- 当 x 为无类型化,可通过类型 T 的值来表示的 常量时。
任何类型都可赋予下划线表示的空白标识符.
## 6.3 可表示性
若满足以下条件,则常量 x 可表示为 T 类型的值:
- x 在由 T 所确定的值的集合中。
- T 为浮点类型且 x 可被舍入到 T 的精度而不会溢出。
下面是一个例子:
```
x T x 可表示为一个 T 类型的值,因为
'a' byte 97 属于 byte 值的集合
97 rune rune 是 int32 的别名,且 97 属于 32 位整数值的集合
"foo" string "foo" 属于 string 值的集合
1024 int16 1024 属于 16 位整数的集合
42.0 byte 42 属于无符号 8 位整数的集合
1e10 u64 10000000000 属于 64 位无符号整数的集合
2.718281828459045 f32 2.718281828459045 舍入到 2.7182817,它属于 f32 值的集合
-1e-1000 f64 -1e-1000 舍入到 IEEE -0.0,它进一步简化为 0.0
0i int 0 是一个整数值
x T x 无法表示为一个 T 类型的值,因为
0 bool 0 不属于布尔值的集合
'a' string 'a' 是一个 rune它不属于 string 值的集合
1024 byte 1024 不属于无符号 8 位整数的集合
-1 uint16 -1 不属于 16 位无符号整数的集合
1.1 int 1.1 不是一个整数值
1e1000 f64 1e1000 舍入后溢出到 IEEE +Inf
```
## 7 代码块
凹语言代码块为一对大括号括住的,可能为空的一系列声明和语句。
```
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
```
除显式源码块外,还有一些隐式块:
- 全域块包含所有的 凹语言 源码文本。
- 每个包都有包含其所有 凹语言 源码文本的包块。
- 每个文件都有包含其所有 凹语言 源码文本的文件块。
- 每个 if、for 和 switch 语句都被视为处于其自身的隐式块中。
- 每个 switch 语句中的子句其行为如同隐式块。
块可嵌套并会影响作用域。
## 8 声明与作用域
凹语言中声明可将非空白标识符绑定到一个常量、类型、变量、函数、标签或包。在程序中,每个标识符都必须被声明才能被使用。同一标识符不能在同一代码块中声明两次,且在文件与包代码块中不能同时声明。
下划线表示的空白标识符可像其它标识符一样在声明中使用,但它不会引入绑定被视作未声明的。在包块中,标识符 init 仅能用作 init 函数声明,且与空白标识符一样不会引入新的绑定。
```
Declaration = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
```
已声明标识符的作用域即为该标识符所表示的具名常量、类型、变量、函数、标签或包在源文本中的作用范围。
凹语言 使用块表示词法作用域:
1. 预声明标识符的作用域为全域块。
1. 即在任何函数之外的顶级声明的表示常量、类型、变量或函数的标识符其作用域为该包块。
1. 已导入包的包名作用域为仅包含该导入声明的文件块。
1. 表示方法接收器 this、函数形参或返回值变量的标识符其作用域为该函数体。
1. 在函数中声明为常量或变量的标识符,其作用域始于该函数中具体常量实现或变量实现的结尾,止于最内部包含块的结尾。
1. 在函数中声明为类型的标识符,其作用域始于该函数中具体类型实现的标识符,止于最内部包含块的结尾。
在块中短声明的标识符可在其内部块中重新声明。
## 8.1 标签作用域
## 8.2 空白标识符
## 9 表达式
## 10 语句
## 11 包结构
## 12 初始化和执行顺序

11
go.mod
View File

@ -1,11 +0,0 @@
// @2019
module wa-lang.org/wa
go 1.17
require (
github.com/BurntSushi/toml v1.3.2
wa-lang.org/wabt-go v1.3.0
wa-lang.org/wazero v1.0.1
)

10
go.sum
View File

@ -1,10 +0,0 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/tetratelabs/wazero v1.0.0-pre.4 h1:RBJQT5OzmORkSp6MmZDWoFEr0zXjk4pmvMKAdeUnsaI=
github.com/tetratelabs/wazero v1.0.0-pre.4/go.mod h1:u8wrFmpdrykiFK0DFPiFm5a4+0RzsdmXYVtijBKqUVo=
wa-lang.org/wabt-go v1.2.3 h1:xwGW3+IrCMAPDx+ngQFx7vl0xBc1vuooRNql7i2yCiA=
wa-lang.org/wabt-go v1.2.3/go.mod h1:v4fKY/p4oMiKwQ2S2aC/wOXvJ2bk2MgtLmwK0TKTNx0=
wa-lang.org/wabt-go v1.3.0 h1:7oSrr80hGlf9G6wwf2pQQ1NXbeqBxEk3D3GDWwbYmVA=
wa-lang.org/wabt-go v1.3.0/go.mod h1:v4fKY/p4oMiKwQ2S2aC/wOXvJ2bk2MgtLmwK0TKTNx0=
wa-lang.org/wazero v1.0.1 h1:6o6M2o6TP0c6b1+jJtfFaAJQGBIk8HrDegIGzrtwmGc=
wa-lang.org/wazero v1.0.1/go.mod h1:r1lGhhlgAnh5eZyNHe/dslT0LF7aY3qZGJWCbxRqf3E=

View File

@ -15,7 +15,7 @@
<animate attributeName="r" values="0;5;5;0" dur="1s" repeatCount="1" />
</circle>
<path d="M200 230L234 264L268 230M200 230L166 264L132 230" fill="none" stroke="white" stroke-width="8" stroke-linecap="round" stroke-dasharray="0,0,0,192">
<path d="M200 230L234 264L268 230M200 230L166 264L132 230" stroke="white" stroke-width="8" stroke-linecap="round" stroke-dasharray="0,0,0,192">
<animate attributeType="XML" attributeName="stroke-dasharray" values="0,0,0,192;0,96,96,0; 192,0,0,0" keyTimes="0; 0.5;1" fill="freeze" dur="1.5s" repeatCount="1" />
</path>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -15,7 +15,7 @@
<animate attributeName="r" values="0;5;5;0" dur="1s" repeatCount="1" />
</circle>
<path d="M200 230L234 264L268 230M200 230L166 264L132 230" fill="none" stroke="white" stroke-width="8" stroke-linecap="round" stroke-dasharray="0,0,0,192">
<path d="M200 230L234 264L268 230M200 230L166 264L132 230" stroke="white" stroke-width="8" stroke-linecap="round" stroke-dasharray="0,0,0,192">
<animate attributeType="XML" attributeName="stroke-dasharray" values="0,0,0,192;0,96,96,0; 192,0,0,0" keyTimes="0; 0.5;1" fill="freeze" dur="1.5s" repeatCount="1" />
</path>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 628 B

After

Width:  |  Height:  |  Size: 628 B

View File

Before

Width:  |  Height:  |  Size: 619 B

After

Width:  |  Height:  |  Size: 619 B

View File

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

Before

Width:  |  Height:  |  Size: 591 B

After

Width:  |  Height:  |  Size: 591 B

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@ -1,74 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race,
religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting Dan Buch at dan@meatballhat.com. All complaints will be
reviewed and investigated and will result in a response that is deemed necessary
and appropriate to the circumstances. The project team is obligated to maintain
confidentiality with regard to the reporter of an incident. Further details of
specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2016 Jeremy Saenz & Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,70 +0,0 @@
cli
===
[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://pkg.go.dev/github.com/urfave/cli)
[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli)
[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli)
[![codecov](https://codecov.io/gh/urfave/cli/branch/master/graph/badge.svg)](https://codecov.io/gh/urfave/cli)
cli is a simple, fast, and fun package for building command line apps in Go. The
goal is to enable developers to write fast and distributable command line
applications in an expressive way.
## Usage Documentation
Usage documentation exists for each major version. Don't know what version you're on? You're probably using the version from the `master` branch, which is currently `v2`.
- `v2` - [./docs/v2/manual.md](./docs/v2/manual.md)
- `v1` - [./docs/v1/manual.md](./docs/v1/manual.md)
Guides for migrating to newer versions:
- `v1-to-v2` - [./docs/migrate-v1-to-v2.md](./docs/migrate-v1-to-v2.md)
## Installation
Using this package requires a working Go environment. [See the install instructions for Go](http://golang.org/doc/install.html).
Go Modules are required when using this package. [See the go blog guide on using Go Modules](https://blog.golang.org/using-go-modules).
### Using `v2` releases
```
$ GO111MODULE=on go get github.com/urfave/cli
```
```go
...
import (
"github.com/urfave/cli" // imports as package "cli"
)
...
```
### Using `v1` releases
```
$ GO111MODULE=on go get github.com/urfave/cli
```
```go
...
import (
"github.com/urfave/cli"
)
...
```
### GOPATH
Make sure your `PATH` includes the `$GOPATH/bin` directory so your commands can
be easily used:
```
export PATH=$PATH:$GOPATH/bin
```
### Supported platforms
cli is tested against multiple versions of Go on Linux, and against the latest
released version of Go on OS X and Windows. This project uses Github Actions for
builds. To see our currently supported go versions and platforms, look at the [./.github/workflows/cli.yml](https://github.com/urfave/cli/blob/master/.github/workflows/cli.yml).

View File

@ -1,195 +0,0 @@
package cli
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
"text/template"
"github.com/cpuguy83/go-md2man/v2/md2man"
)
// ToMarkdown creates a markdown string for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToMarkdown() (string, error) {
var w bytes.Buffer
if err := a.writeDocTemplate(&w, 0); err != nil {
return "", err
}
return w.String(), nil
}
// ToMan creates a man page string with section number for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToManWithSection(sectionNumber int) (string, error) {
var w bytes.Buffer
if err := a.writeDocTemplate(&w, sectionNumber); err != nil {
return "", err
}
man := md2man.Render(w.Bytes())
return string(man), nil
}
// ToMan creates a man page string for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToMan() (string, error) {
man, err := a.ToManWithSection(8)
return man, err
}
type cliTemplate struct {
App *App
SectionNum int
Commands []string
GlobalArgs []string
SynopsisArgs []string
}
func (a *App) writeDocTemplate(w io.Writer, sectionNum int) error {
const name = "cli"
t, err := template.New(name).Parse(MarkdownDocTemplate)
if err != nil {
return err
}
return t.ExecuteTemplate(w, name, &cliTemplate{
App: a,
SectionNum: sectionNum,
Commands: prepareCommands(a.Commands, 0),
GlobalArgs: prepareArgsWithValues(a.VisibleFlags()),
SynopsisArgs: prepareArgsSynopsis(a.VisibleFlags()),
})
}
func prepareCommands(commands []*Command, level int) []string {
var coms []string
for _, command := range commands {
if command.Hidden {
continue
}
usageText := prepareUsageText(command)
usage := prepareUsage(command, usageText)
prepared := fmt.Sprintf("%s %s\n\n%s%s",
strings.Repeat("#", level+2),
strings.Join(command.Names(), ", "),
usage,
usageText,
)
flags := prepareArgsWithValues(command.Flags)
if len(flags) > 0 {
prepared += fmt.Sprintf("\n%s", strings.Join(flags, "\n"))
}
coms = append(coms, prepared)
// recursevly iterate subcommands
if len(command.Subcommands) > 0 {
coms = append(
coms,
prepareCommands(command.Subcommands, level+1)...,
)
}
}
return coms
}
func prepareArgsWithValues(flags []Flag) []string {
return prepareFlags(flags, ", ", "**", "**", `""`, true)
}
func prepareArgsSynopsis(flags []Flag) []string {
return prepareFlags(flags, "|", "[", "]", "[value]", false)
}
func prepareFlags(
flags []Flag,
sep, opener, closer, value string,
addDetails bool,
) []string {
args := []string{}
for _, f := range flags {
flag, ok := f.(DocGenerationFlag)
if !ok {
continue
}
modifiedArg := opener
for _, s := range flag.Names() {
trimmed := strings.TrimSpace(s)
if len(modifiedArg) > len(opener) {
modifiedArg += sep
}
if len(trimmed) > 1 {
modifiedArg += fmt.Sprintf("--%s", trimmed)
} else {
modifiedArg += fmt.Sprintf("-%s", trimmed)
}
}
modifiedArg += closer
if flag.TakesValue() {
modifiedArg += fmt.Sprintf("=%s", value)
}
if addDetails {
modifiedArg += flagDetails(flag)
}
args = append(args, modifiedArg+"\n")
}
sort.Strings(args)
return args
}
// flagDetails returns a string containing the flags metadata
func flagDetails(flag DocGenerationFlag) string {
description := flag.GetUsage()
value := flag.GetValue()
if value != "" {
description += " (default: " + value + ")"
}
return ": " + description
}
func prepareUsageText(command *Command) string {
if command.UsageText == "" {
return ""
}
// Remove leading and trailing newlines
preparedUsageText := strings.Trim(command.UsageText, "\n")
var usageText string
if strings.Contains(preparedUsageText, "\n") {
// Format multi-line string as a code block using the 4 space schema to allow for embedded markdown such
// that it will not break the continuous code block.
for _, ln := range strings.Split(preparedUsageText, "\n") {
usageText += fmt.Sprintf(" %s\n", ln)
}
} else {
// Style a single line as a note
usageText = fmt.Sprintf(">%s\n", preparedUsageText)
}
return usageText
}
func prepareUsage(command *Command, usageText string) string {
if command.Usage == "" {
return ""
}
usage := command.Usage + "\n"
// Add a newline to the Usage IFF there is a UsageText
if usageText != "" {
usage += "\n"
}
return usage
}

View File

@ -1,540 +0,0 @@
package cli
import (
"context"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"time"
)
var (
changeLogURL = "https://github.com/urfave/cli/blob/master/docs/CHANGELOG.md"
appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
errInvalidActionType = NewExitError("ERROR invalid Action type. "+
fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+
fmt.Sprintf("See %s", appActionDeprecationURL), 2)
)
// App is the main structure of a cli application. It is recommended that
// an app be created with the cli.NewApp() function
type App struct {
// The name of the program. Defaults to path.Base(os.Args[0])
Name string
// Full name of command for help, defaults to Name
HelpName string
// Description of the program.
Usage string
// Text to override the USAGE section of help
UsageText string
// Description of the program argument format.
ArgsUsage string
// Version of the program
Version string
// Description of the program
Description string
// List of commands to execute
Commands []*Command
// List of flags to parse
Flags []Flag
// Boolean to enable bash completion commands
EnableBashCompletion bool
// Boolean to hide built-in help command and help flag
HideHelp bool
// Boolean to hide built-in help command but keep help flag.
// Ignored if HideHelp is true.
HideHelpCommand bool
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool
// categories contains the categorized commands and is populated on app startup
categories CommandCategories
// An action to execute when the shell completion flag is set
BashComplete BashCompleteFunc
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
Before BeforeFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
// The action to execute when no subcommands are specified
Action ActionFunc
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc
// Execute this function if a usage error occurs
OnUsageError OnUsageErrorFunc
// Compilation date
Compiled time.Time
// List of all authors who contributed
Authors []*Author
// Copyright of the binary if any
Copyright string
// Reader reader to write input to (useful for tests)
Reader io.Reader
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
ErrWriter io.Writer
// ExitErrHandler processes any error encountered while running an App before
// it is returned to the caller. If no function is provided, HandleExitCoder
// is used as the default behavior.
ExitErrHandler ExitErrHandlerFunc
// Other custom info
Metadata map[string]interface{}
// Carries a function which returns app specific info.
ExtraInfo func() map[string]string
// CustomAppHelpTemplate the text template for app help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomAppHelpTemplate string
// Boolean to enable short-option handling so user can combine several
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool
didSetup bool
}
// Tries to find out when this binary was compiled.
// Returns the current time if it fails to find it.
func compileTime() time.Time {
info, err := os.Stat(os.Args[0])
if err != nil {
return time.Now()
}
return info.ModTime()
}
// NewApp creates a new cli Application with some reasonable defaults for Name,
// Usage, Version and Action.
func NewApp() *App {
return &App{
Name: filepath.Base(os.Args[0]),
HelpName: filepath.Base(os.Args[0]),
Usage: "A new cli application",
UsageText: "",
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
Reader: os.Stdin,
Writer: os.Stdout,
ErrWriter: os.Stderr,
}
}
// Setup runs initialization code to ensure all data structures are ready for
// `Run` or inspection prior to `Run`. It is internally called by `Run`, but
// will return early if setup has already happened.
func (a *App) Setup() {
if a.didSetup {
return
}
a.didSetup = true
if a.Name == "" {
a.Name = filepath.Base(os.Args[0])
}
if a.HelpName == "" {
a.HelpName = a.Name
}
if a.Usage == "" {
a.Usage = "A new cli application"
}
if a.Version == "" {
a.HideVersion = true
}
if a.BashComplete == nil {
a.BashComplete = DefaultAppComplete
}
if a.Action == nil {
a.Action = helpCommand.Action
}
if a.Compiled == (time.Time{}) {
a.Compiled = compileTime()
}
if a.Reader == nil {
a.Reader = os.Stdin
}
if a.Writer == nil {
a.Writer = os.Stdout
}
if a.ErrWriter == nil {
a.ErrWriter = os.Stderr
}
var newCommands []*Command
for _, c := range a.Commands {
if c.HelpName == "" {
c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
}
newCommands = append(newCommands, c)
}
a.Commands = newCommands
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
if !a.HideHelpCommand {
a.appendCommand(helpCommand)
}
if HelpFlag != nil {
a.appendFlag(HelpFlag)
}
}
if !a.HideVersion {
a.appendFlag(VersionFlag)
}
a.categories = newCommandCategories()
for _, command := range a.Commands {
a.categories.AddCommand(command.Category, command)
}
sort.Sort(a.categories.(*commandCategories))
if a.Metadata == nil {
a.Metadata = make(map[string]interface{})
}
}
func (a *App) newFlagSet() (*flag.FlagSet, error) {
return flagSet(a.Name, a.Flags)
}
func (a *App) useShortOptionHandling() bool {
return a.UseShortOptionHandling
}
// Run is the entry point to the cli app. Parses the arguments slice and routes
// to the proper flag/args combination
func (a *App) Run(arguments []string) (err error) {
return a.RunContext(context.Background(), arguments)
}
// RunContext is like Run except it takes a Context that will be
// passed to its commands and sub-commands. Through this, you can
// propagate timeouts and cancellation requests
func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
a.Setup()
// handle the completion flag separately from the flagset since
// completion could be attempted after a flag, but before its value was put
// on the command line. this causes the flagset to interpret the completion
// flag name as the value of the flag before it which is undesirable
// note that we can only do this because the shell autocomplete function
// always appends the completion flag at the end of the command
shellComplete, arguments := checkShellCompleteFlag(a, arguments)
set, err := a.newFlagSet()
if err != nil {
return err
}
err = parseIter(set, a, arguments[1:], shellComplete)
nerr := normalizeFlags(a.Flags, set)
context := NewContext(a, set, &Context{Context: ctx})
if nerr != nil {
_, _ = fmt.Fprintln(a.Writer, nerr)
_ = ShowAppHelp(context)
return nerr
}
context.shellComplete = shellComplete
if checkCompletions(context) {
return nil
}
if err != nil {
if a.OnUsageError != nil {
err := a.OnUsageError(context, err, false)
a.handleExitCoder(context, err)
return err
}
_, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
_ = ShowAppHelp(context)
return err
}
if !a.HideHelp && checkHelp(context) {
_ = ShowAppHelp(context)
return nil
}
if !a.HideVersion && checkVersion(context) {
ShowVersion(context)
return nil
}
cerr := context.checkRequiredFlags(a.Flags)
if cerr != nil {
_ = ShowAppHelp(context)
return cerr
}
if a.After != nil {
defer func() {
if afterErr := a.After(context); afterErr != nil {
if err != nil {
err = newMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if a.Before != nil {
beforeErr := a.Before(context)
if beforeErr != nil {
a.handleExitCoder(context, beforeErr)
err = beforeErr
return err
}
}
args := context.Args()
if args.Present() {
name := args.First()
c := a.Command(name)
if c != nil {
return c.Run(context)
}
}
if a.Action == nil {
a.Action = helpCommand.Action
}
// Run default Action
err = a.Action(context)
a.handleExitCoder(context, err)
return err
}
// RunAndExitOnError calls .Run() and exits non-zero if an error was returned
//
// Deprecated: instead you should return an error that fulfills cli.ExitCoder
// to cli.App.Run. This will cause the application to exit with the given error
// code in the cli.ExitCoder
func (a *App) RunAndExitOnError() {
if err := a.Run(os.Args); err != nil {
_, _ = fmt.Fprintln(a.ErrWriter, err)
OsExiter(1)
}
}
// RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to
// generate command-specific flags
func (a *App) RunAsSubcommand(ctx *Context) (err error) {
// Setup also handles HideHelp and HideHelpCommand
a.Setup()
var newCmds []*Command
for _, c := range a.Commands {
if c.HelpName == "" {
c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
}
newCmds = append(newCmds, c)
}
a.Commands = newCmds
set, err := a.newFlagSet()
if err != nil {
return err
}
err = parseIter(set, a, ctx.Args().Tail(), ctx.shellComplete)
nerr := normalizeFlags(a.Flags, set)
context := NewContext(a, set, ctx)
if nerr != nil {
_, _ = fmt.Fprintln(a.Writer, nerr)
_, _ = fmt.Fprintln(a.Writer)
if len(a.Commands) > 0 {
_ = ShowSubcommandHelp(context)
} else {
_ = ShowCommandHelp(ctx, context.Args().First())
}
return nerr
}
if checkCompletions(context) {
return nil
}
if err != nil {
if a.OnUsageError != nil {
err = a.OnUsageError(context, err, true)
a.handleExitCoder(context, err)
return err
}
_, _ = fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error())
_ = ShowSubcommandHelp(context)
return err
}
if len(a.Commands) > 0 {
if checkSubcommandHelp(context) {
return nil
}
} else {
if checkCommandHelp(ctx, context.Args().First()) {
return nil
}
}
cerr := context.checkRequiredFlags(a.Flags)
if cerr != nil {
_ = ShowSubcommandHelp(context)
return cerr
}
if a.After != nil {
defer func() {
afterErr := a.After(context)
if afterErr != nil {
a.handleExitCoder(context, err)
if err != nil {
err = newMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if a.Before != nil {
beforeErr := a.Before(context)
if beforeErr != nil {
a.handleExitCoder(context, beforeErr)
err = beforeErr
return err
}
}
args := context.Args()
if args.Present() {
name := args.First()
c := a.Command(name)
if c != nil {
return c.Run(context)
}
}
// Run default Action
err = a.Action(context)
a.handleExitCoder(context, err)
return err
}
// Command returns the named command on App. Returns nil if the command does not exist
func (a *App) Command(name string) *Command {
for _, c := range a.Commands {
if c.HasName(name) {
return c
}
}
return nil
}
// VisibleCategories returns a slice of categories and commands that are
// Hidden=false
func (a *App) VisibleCategories() []CommandCategory {
ret := []CommandCategory{}
for _, category := range a.categories.Categories() {
if visible := func() CommandCategory {
if len(category.VisibleCommands()) > 0 {
return category
}
return nil
}(); visible != nil {
ret = append(ret, visible)
}
}
return ret
}
// VisibleCommands returns a slice of the Commands with Hidden=false
func (a *App) VisibleCommands() []*Command {
var ret []*Command
for _, command := range a.Commands {
if !command.Hidden {
ret = append(ret, command)
}
}
return ret
}
// VisibleFlags returns a slice of the Flags with Hidden=false
func (a *App) VisibleFlags() []Flag {
return visibleFlags(a.Flags)
}
func (a *App) appendFlag(fl Flag) {
if !hasFlag(a.Flags, fl) {
a.Flags = append(a.Flags, fl)
}
}
func (a *App) appendCommand(c *Command) {
if !hasCommand(a.Commands, c) {
a.Commands = append(a.Commands, c)
}
}
func (a *App) handleExitCoder(context *Context, err error) {
if a.ExitErrHandler != nil {
a.ExitErrHandler(context, err)
} else {
HandleExitCoder(err)
}
}
// Author represents someone who has contributed to a cli project.
type Author struct {
Name string // The Authors name
Email string // The Authors email
}
// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
func (a *Author) String() string {
e := ""
if a.Email != "" {
e = " <" + a.Email + ">"
}
return fmt.Sprintf("%v%v", a.Name, e)
}
// HandleAction attempts to figure out which Action signature was used. If
// it's an ActionFunc or a func with the legacy signature for Action, the func
// is run!
func HandleAction(action interface{}, context *Context) (err error) {
switch a := action.(type) {
case ActionFunc:
return a(context)
case func(*Context) error:
return a(context)
case func(*Context): // deprecated function signature
a(context)
return nil
}
return errInvalidActionType
}

View File

@ -1,54 +0,0 @@
package cli
type Args interface {
// Get returns the nth argument, or else a blank string
Get(n int) string
// First returns the first argument, or else a blank string
First() string
// Tail returns the rest of the arguments (not the first one)
// or else an empty string slice
Tail() []string
// Len returns the length of the wrapped slice
Len() int
// Present checks if there are any arguments present
Present() bool
// Slice returns a copy of the internal slice
Slice() []string
}
type args []string
func (a *args) Get(n int) string {
if len(*a) > n {
return (*a)[n]
}
return ""
}
func (a *args) First() string {
return a.Get(0)
}
func (a *args) Tail() []string {
if a.Len() >= 2 {
tail := []string((*a)[1:])
ret := make([]string, len(tail))
copy(ret, tail)
return ret
}
return []string{}
}
func (a *args) Len() int {
return len(*a)
}
func (a *args) Present() bool {
return a.Len() != 0
}
func (a *args) Slice() []string {
ret := make([]string, len(*a))
copy(ret, *a)
return ret
}

View File

@ -1,79 +0,0 @@
package cli
// CommandCategories interface allows for category manipulation
type CommandCategories interface {
// AddCommand adds a command to a category, creating a new category if necessary.
AddCommand(category string, command *Command)
// categories returns a copy of the category slice
Categories() []CommandCategory
}
type commandCategories []*commandCategory
func newCommandCategories() CommandCategories {
ret := commandCategories([]*commandCategory{})
return &ret
}
func (c *commandCategories) Less(i, j int) bool {
return lexicographicLess((*c)[i].Name(), (*c)[j].Name())
}
func (c *commandCategories) Len() int {
return len(*c)
}
func (c *commandCategories) Swap(i, j int) {
(*c)[i], (*c)[j] = (*c)[j], (*c)[i]
}
func (c *commandCategories) AddCommand(category string, command *Command) {
for _, commandCategory := range []*commandCategory(*c) {
if commandCategory.name == category {
commandCategory.commands = append(commandCategory.commands, command)
return
}
}
newVal := append(*c,
&commandCategory{name: category, commands: []*Command{command}})
*c = newVal
}
func (c *commandCategories) Categories() []CommandCategory {
ret := make([]CommandCategory, len(*c))
for i, cat := range *c {
ret[i] = cat
}
return ret
}
// CommandCategory is a category containing commands.
type CommandCategory interface {
// Name returns the category name string
Name() string
// VisibleCommands returns a slice of the Commands with Hidden=false
VisibleCommands() []*Command
}
type commandCategory struct {
name string
commands []*Command
}
func (c *commandCategory) Name() string {
return c.name
}
func (c *commandCategory) VisibleCommands() []*Command {
if c.commands == nil {
c.commands = []*Command{}
}
var ret []*Command
for _, command := range c.commands {
if !command.Hidden {
ret = append(ret, command)
}
}
return ret
}

View File

@ -1,23 +0,0 @@
// Package cli provides a minimal framework for creating and organizing command line
// Go applications. cli is designed to be easy to understand and write, the most simple
// cli application can be written as follows:
// func main() {
// (&cli.App{}).Run(os.Args)
// }
//
// Of course this application does not do much, so var's make this an actual application:
// func main() {
// app := &cli.App{
// Name: "greet",
// Usage: "say a greeting",
// Action: func(c *cli.Context) error {
// fmt.Println("Greetings")
// return nil
// },
// }
//
// app.Run(os.Args)
// }
package cli
//go:generate go run flag-gen/main.go flag-gen/assets_vfsdata.go

View File

@ -1,302 +0,0 @@
package cli
import (
"flag"
"fmt"
"sort"
"strings"
)
// Command is a subcommand for a cli.App.
type Command struct {
// The name of the command
Name string
// A list of aliases for the command
Aliases []string
// A short description of the usage of this command
Usage string
// Custom text to show on USAGE section of help
UsageText string
// A longer explanation of how the command works
Description string
// A short description of the arguments of this command
ArgsUsage string
// The category the command is part of
Category string
// The function to call when checking for bash command completions
BashComplete BashCompleteFunc
// An action to execute before any sub-subcommands are run, but after the context is ready
// If a non-nil error is returned, no sub-subcommands are run
Before BeforeFunc
// An action to execute after any subcommands are run, but after the subcommand has finished
// It is run even if Action() panics
After AfterFunc
// The function to call when this command is invoked
Action ActionFunc
// Execute this function if a usage error occurs.
OnUsageError OnUsageErrorFunc
// List of child commands
Subcommands []*Command
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
SkipFlagParsing bool
// Boolean to hide built-in help command and help flag
HideHelp bool
// Boolean to hide built-in help command but keep help flag
// Ignored if HideHelp is true.
HideHelpCommand bool
// Boolean to hide this command from help or completion
Hidden bool
// Boolean to enable short-option handling so user can combine several
// single-character bool arguments into one
// i.e. foobar -o -v -> foobar -ov
UseShortOptionHandling bool
// Full name of command for help, defaults to full command name, including parent commands.
HelpName string
commandNamePath []string
// CustomHelpTemplate the text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
CustomHelpTemplate string
}
type Commands []*Command
type CommandsByName []*Command
func (c CommandsByName) Len() int {
return len(c)
}
func (c CommandsByName) Less(i, j int) bool {
return lexicographicLess(c[i].Name, c[j].Name)
}
func (c CommandsByName) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
// FullName returns the full name of the command.
// For subcommands this ensures that parent commands are part of the command path
func (c *Command) FullName() string {
if c.commandNamePath == nil {
return c.Name
}
return strings.Join(c.commandNamePath, " ")
}
// Run invokes the command given the context, parses ctx.Args() to generate command-specific flags
func (c *Command) Run(ctx *Context) (err error) {
if len(c.Subcommands) > 0 {
return c.startApp(ctx)
}
if !c.HideHelp && HelpFlag != nil {
// append help to flags
c.appendFlag(HelpFlag)
}
if ctx.App.UseShortOptionHandling {
c.UseShortOptionHandling = true
}
set, err := c.parseFlags(ctx.Args(), ctx.shellComplete)
context := NewContext(ctx.App, set, ctx)
context.Command = c
if checkCommandCompletions(context, c.Name) {
return nil
}
if err != nil {
if c.OnUsageError != nil {
err = c.OnUsageError(context, err, false)
context.App.handleExitCoder(context, err)
return err
}
_, _ = fmt.Fprintln(context.App.Writer, "Incorrect Usage:", err.Error())
_, _ = fmt.Fprintln(context.App.Writer)
_ = ShowCommandHelp(context, c.Name)
return err
}
if checkCommandHelp(context, c.Name) {
return nil
}
cerr := context.checkRequiredFlags(c.Flags)
if cerr != nil {
_ = ShowCommandHelp(context, c.Name)
return cerr
}
if c.After != nil {
defer func() {
afterErr := c.After(context)
if afterErr != nil {
context.App.handleExitCoder(context, err)
if err != nil {
err = newMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if c.Before != nil {
err = c.Before(context)
if err != nil {
context.App.handleExitCoder(context, err)
return err
}
}
if c.Action == nil {
c.Action = helpSubcommand.Action
}
context.Command = c
err = c.Action(context)
if err != nil {
context.App.handleExitCoder(context, err)
}
return err
}
func (c *Command) newFlagSet() (*flag.FlagSet, error) {
return flagSet(c.Name, c.Flags)
}
func (c *Command) useShortOptionHandling() bool {
return c.UseShortOptionHandling
}
func (c *Command) parseFlags(args Args, shellComplete bool) (*flag.FlagSet, error) {
set, err := c.newFlagSet()
if err != nil {
return nil, err
}
if c.SkipFlagParsing {
return set, set.Parse(append([]string{"--"}, args.Tail()...))
}
err = parseIter(set, c, args.Tail(), shellComplete)
if err != nil {
return nil, err
}
err = normalizeFlags(c.Flags, set)
if err != nil {
return nil, err
}
return set, nil
}
// Names returns the names including short names and aliases.
func (c *Command) Names() []string {
return append([]string{c.Name}, c.Aliases...)
}
// HasName returns true if Command.Name matches given name
func (c *Command) HasName(name string) bool {
for _, n := range c.Names() {
if n == name {
return true
}
}
return false
}
func (c *Command) startApp(ctx *Context) error {
app := &App{
Metadata: ctx.App.Metadata,
Name: fmt.Sprintf("%s %s", ctx.App.Name, c.Name),
}
if c.HelpName == "" {
app.HelpName = c.HelpName
} else {
app.HelpName = app.Name
}
app.Usage = c.Usage
app.UsageText = c.UsageText
app.Description = c.Description
app.ArgsUsage = c.ArgsUsage
// set CommandNotFound
app.CommandNotFound = ctx.App.CommandNotFound
app.CustomAppHelpTemplate = c.CustomHelpTemplate
// set the flags and commands
app.Commands = c.Subcommands
app.Flags = c.Flags
app.HideHelp = c.HideHelp
app.HideHelpCommand = c.HideHelpCommand
app.Version = ctx.App.Version
app.HideVersion = true
app.Compiled = ctx.App.Compiled
app.Reader = ctx.App.Reader
app.Writer = ctx.App.Writer
app.ErrWriter = ctx.App.ErrWriter
app.ExitErrHandler = ctx.App.ExitErrHandler
app.UseShortOptionHandling = ctx.App.UseShortOptionHandling
app.categories = newCommandCategories()
for _, command := range c.Subcommands {
app.categories.AddCommand(command.Category, command)
}
sort.Sort(app.categories.(*commandCategories))
// bash completion
app.EnableBashCompletion = ctx.App.EnableBashCompletion
if c.BashComplete != nil {
app.BashComplete = c.BashComplete
}
// set the actions
app.Before = c.Before
app.After = c.After
if c.Action != nil {
app.Action = c.Action
} else {
app.Action = helpSubcommand.Action
}
app.OnUsageError = c.OnUsageError
for index, cc := range app.Commands {
app.Commands[index].commandNamePath = []string{c.Name, cc.Name}
}
return app.RunAsSubcommand(ctx)
}
// VisibleFlags returns a slice of the Flags with Hidden=false
func (c *Command) VisibleFlags() []Flag {
return visibleFlags(c.Flags)
}
func (c *Command) appendFlag(fl Flag) {
if !hasFlag(c.Flags, fl) {
c.Flags = append(c.Flags, fl)
}
}
func hasCommand(commands []*Command, command *Command) bool {
for _, existing := range commands {
if command == existing {
return true
}
}
return false
}

View File

@ -1,208 +0,0 @@
package cli
import (
"context"
"flag"
"strings"
)
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific args and
// parsed command-line options.
type Context struct {
context.Context
App *App
Command *Command
shellComplete bool
flagSet *flag.FlagSet
parentContext *Context
}
// NewContext creates a new context. For use in when invoking an App or Command action.
func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
c := &Context{App: app, flagSet: set, parentContext: parentCtx}
if parentCtx != nil {
c.Context = parentCtx.Context
c.shellComplete = parentCtx.shellComplete
if parentCtx.flagSet == nil {
parentCtx.flagSet = &flag.FlagSet{}
}
}
c.Command = &Command{}
if c.Context == nil {
c.Context = context.Background()
}
return c
}
// NumFlags returns the number of flags set
func (c *Context) NumFlags() int {
return c.flagSet.NFlag()
}
// Set sets a context flag to a value.
func (c *Context) Set(name, value string) error {
return c.flagSet.Set(name, value)
}
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if fs := c.lookupFlagSet(name); fs != nil {
isSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
isSet = true
}
})
if isSet {
return true
}
f := c.lookupFlag(name)
if f == nil {
return false
}
return f.IsSet()
}
return false
}
// LocalFlagNames returns a slice of flag names used in this context.
func (c *Context) LocalFlagNames() []string {
var names []string
c.flagSet.Visit(makeFlagNameVisitor(&names))
return names
}
// FlagNames returns a slice of flag names used by the this context and all of
// its parent contexts.
func (c *Context) FlagNames() []string {
var names []string
for _, ctx := range c.Lineage() {
ctx.flagSet.Visit(makeFlagNameVisitor(&names))
}
return names
}
// Lineage returns *this* context and all of its ancestor contexts in order from
// child to parent
func (c *Context) Lineage() []*Context {
var lineage []*Context
for cur := c; cur != nil; cur = cur.parentContext {
lineage = append(lineage, cur)
}
return lineage
}
// Value returns the value of the flag corresponding to `name`
func (c *Context) Value(name string) interface{} {
if fs := c.lookupFlagSet(name); fs != nil {
return fs.Lookup(name).Value.(flag.Getter).Get()
}
return nil
}
// Args returns the command line arguments associated with the context.
func (c *Context) Args() Args {
ret := args(c.flagSet.Args())
return &ret
}
// NArg returns the number of the command line arguments.
func (c *Context) NArg() int {
return c.Args().Len()
}
func (ctx *Context) lookupFlag(name string) Flag {
for _, c := range ctx.Lineage() {
if c.Command == nil {
continue
}
for _, f := range c.Command.Flags {
for _, n := range f.Names() {
if n == name {
return f
}
}
}
}
if ctx.App != nil {
for _, f := range ctx.App.Flags {
for _, n := range f.Names() {
if n == name {
return f
}
}
}
}
return nil
}
func (ctx *Context) lookupFlagSet(name string) *flag.FlagSet {
for _, c := range ctx.Lineage() {
if f := c.flagSet.Lookup(name); f != nil {
return c.flagSet
}
}
return nil
}
func (context *Context) checkRequiredFlags(flags []Flag) requiredFlagsErr {
var missingFlags []string
for _, f := range flags {
if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() {
var flagPresent bool
var flagName string
for _, key := range f.Names() {
if len(key) > 1 {
flagName = key
}
if context.IsSet(strings.TrimSpace(key)) {
flagPresent = true
}
}
if !flagPresent && flagName != "" {
missingFlags = append(missingFlags, flagName)
}
}
}
if len(missingFlags) != 0 {
return &errRequiredFlags{missingFlags: missingFlags}
}
return nil
}
func makeFlagNameVisitor(names *[]string) func(*flag.Flag) {
return func(f *flag.Flag) {
nameParts := strings.Split(f.Name, ",")
name := strings.TrimSpace(nameParts[0])
for _, part := range nameParts {
part = strings.TrimSpace(part)
if len(part) > len(name) {
name = part
}
}
if name != "" {
*names = append(*names, name)
}
}
}

View File

@ -1,163 +0,0 @@
package cli
import (
"fmt"
"io"
"os"
"strings"
)
// OsExiter is the function used when the app exits. If not set defaults to os.Exit.
var OsExiter = os.Exit
// ErrWriter is used to write errors to the user. This can be anything
// implementing the io.Writer interface and defaults to os.Stderr.
var ErrWriter io.Writer = os.Stderr
// MultiError is an error that wraps multiple errors.
type MultiError interface {
error
Errors() []error
}
// newMultiError creates a new MultiError. Pass in one or more errors.
func newMultiError(err ...error) MultiError {
ret := multiError(err)
return &ret
}
type multiError []error
// Error implements the error interface.
func (m *multiError) Error() string {
errs := make([]string, len(*m))
for i, err := range *m {
errs[i] = err.Error()
}
return strings.Join(errs, "\n")
}
// Errors returns a copy of the errors slice
func (m *multiError) Errors() []error {
errs := make([]error, len(*m))
for _, err := range *m {
errs = append(errs, err)
}
return errs
}
type requiredFlagsErr interface {
error
getMissingFlags() []string
}
type errRequiredFlags struct {
missingFlags []string
}
func (e *errRequiredFlags) Error() string {
numberOfMissingFlags := len(e.missingFlags)
if numberOfMissingFlags == 1 {
return fmt.Sprintf("Required flag %q not set", e.missingFlags[0])
}
joinedMissingFlags := strings.Join(e.missingFlags, ", ")
return fmt.Sprintf("Required flags %q not set", joinedMissingFlags)
}
func (e *errRequiredFlags) getMissingFlags() []string {
return e.missingFlags
}
// ErrorFormatter is the interface that will suitably format the error output
type ErrorFormatter interface {
Format(s fmt.State, verb rune)
}
// ExitCoder is the interface checked by `App` and `Command` for a custom exit
// code
type ExitCoder interface {
error
ExitCode() int
}
type exitError struct {
exitCode int
message interface{}
}
// NewExitError calls Exit to create a new ExitCoder.
//
// Deprecated: This function is a duplicate of Exit and will eventually be removed.
func NewExitError(message interface{}, exitCode int) ExitCoder {
return Exit(message, exitCode)
}
// Exit wraps a message and exit code into an error, which by default is
// handled with a call to os.Exit during default error handling.
//
// This is the simplest way to trigger a non-zero exit code for an App without
// having to call os.Exit manually. During testing, this behavior can be avoided
// by overiding the ExitErrHandler function on an App or the package-global
// OsExiter function.
func Exit(message interface{}, exitCode int) ExitCoder {
return &exitError{
message: message,
exitCode: exitCode,
}
}
func (ee *exitError) Error() string {
return fmt.Sprintf("%v", ee.message)
}
func (ee *exitError) ExitCode() int {
return ee.exitCode
}
// HandleExitCoder handles errors implementing ExitCoder by printing their
// message and calling OsExiter with the given exit code.
//
// If the given error instead implements MultiError, each error will be checked
// for the ExitCoder interface, and OsExiter will be called with the last exit
// code found, or exit code 1 if no ExitCoder is found.
//
// This function is the default error-handling behavior for an App.
func HandleExitCoder(err error) {
if err == nil {
return
}
if exitErr, ok := err.(ExitCoder); ok {
if err.Error() != "" {
if _, ok := exitErr.(ErrorFormatter); ok {
_, _ = fmt.Fprintf(ErrWriter, "%+v\n", err)
} else {
_, _ = fmt.Fprintln(ErrWriter, err)
}
}
OsExiter(exitErr.ExitCode())
return
}
if multiErr, ok := err.(MultiError); ok {
code := handleMultiError(multiErr)
OsExiter(code)
return
}
}
func handleMultiError(multiErr MultiError) int {
code := 1
for _, merr := range multiErr.Errors() {
if multiErr2, ok := merr.(MultiError); ok {
code = handleMultiError(multiErr2)
} else if merr != nil {
fmt.Fprintln(ErrWriter, merr)
if exitErr, ok := merr.(ExitCoder); ok {
code = exitErr.ExitCode()
}
}
}
return code
}

View File

@ -1,196 +0,0 @@
package cli
import (
"bytes"
"fmt"
"io"
"strings"
"text/template"
)
// ToFishCompletion creates a fish completion string for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToFishCompletion() (string, error) {
var w bytes.Buffer
if err := a.writeFishCompletionTemplate(&w); err != nil {
return "", err
}
return w.String(), nil
}
type fishCompletionTemplate struct {
App *App
Completions []string
AllCommands []string
}
func (a *App) writeFishCompletionTemplate(w io.Writer) error {
const name = "cli"
t, err := template.New(name).Parse(FishCompletionTemplate)
if err != nil {
return err
}
allCommands := []string{}
// Add global flags
completions := a.prepareFishFlags(a.VisibleFlags(), allCommands)
// Add help flag
if !a.HideHelp {
completions = append(
completions,
a.prepareFishFlags([]Flag{HelpFlag}, allCommands)...,
)
}
// Add version flag
if !a.HideVersion {
completions = append(
completions,
a.prepareFishFlags([]Flag{VersionFlag}, allCommands)...,
)
}
// Add commands and their flags
completions = append(
completions,
a.prepareFishCommands(a.VisibleCommands(), &allCommands, []string{})...,
)
return t.ExecuteTemplate(w, name, &fishCompletionTemplate{
App: a,
Completions: completions,
AllCommands: allCommands,
})
}
func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, previousCommands []string) []string {
completions := []string{}
for _, command := range commands {
if command.Hidden {
continue
}
var completion strings.Builder
completion.WriteString(fmt.Sprintf(
"complete -r -c %s -n '%s' -a '%s'",
a.Name,
a.fishSubcommandHelper(previousCommands),
strings.Join(command.Names(), " "),
))
if command.Usage != "" {
completion.WriteString(fmt.Sprintf(" -d '%s'",
escapeSingleQuotes(command.Usage)))
}
if !command.HideHelp {
completions = append(
completions,
a.prepareFishFlags([]Flag{HelpFlag}, command.Names())...,
)
}
*allCommands = append(*allCommands, command.Names()...)
completions = append(completions, completion.String())
completions = append(
completions,
a.prepareFishFlags(command.Flags, command.Names())...,
)
// recursevly iterate subcommands
if len(command.Subcommands) > 0 {
completions = append(
completions,
a.prepareFishCommands(
command.Subcommands, allCommands, command.Names(),
)...,
)
}
}
return completions
}
func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string {
completions := []string{}
for _, f := range flags {
flag, ok := f.(DocGenerationFlag)
if !ok {
continue
}
completion := &strings.Builder{}
completion.WriteString(fmt.Sprintf(
"complete -c %s -n '%s'",
a.Name,
a.fishSubcommandHelper(previousCommands),
))
fishAddFileFlag(f, completion)
for idx, opt := range flag.Names() {
if idx == 0 {
completion.WriteString(fmt.Sprintf(
" -l %s", strings.TrimSpace(opt),
))
} else {
completion.WriteString(fmt.Sprintf(
" -s %s", strings.TrimSpace(opt),
))
}
}
if flag.TakesValue() {
completion.WriteString(" -r")
}
if flag.GetUsage() != "" {
completion.WriteString(fmt.Sprintf(" -d '%s'",
escapeSingleQuotes(flag.GetUsage())))
}
completions = append(completions, completion.String())
}
return completions
}
func fishAddFileFlag(flag Flag, completion *strings.Builder) {
switch f := flag.(type) {
case *GenericFlag:
if f.TakesFile {
return
}
case *StringFlag:
if f.TakesFile {
return
}
case *StringSliceFlag:
if f.TakesFile {
return
}
case *PathFlag:
if f.TakesFile {
return
}
}
completion.WriteString(" -f")
}
func (a *App) fishSubcommandHelper(allCommands []string) string {
fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", a.Name)
if len(allCommands) > 0 {
fishHelper = fmt.Sprintf(
"__fish_seen_subcommand_from %s",
strings.Join(allCommands, " "),
)
}
return fishHelper
}
func escapeSingleQuotes(input string) string {
return strings.Replace(input, `'`, `\'`, -1)
}

View File

@ -1,442 +0,0 @@
package cli
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
const defaultPlaceholder = "value"
var (
slPfx = fmt.Sprintf("sl:::%d:::", time.Now().UTC().UnixNano())
commaWhitespace = regexp.MustCompile("[, ]+.*")
)
// BashCompletionFlag enables bash-completion for all commands and subcommands
var BashCompletionFlag Flag = &BoolFlag{
Name: "generate-bash-completion",
Hidden: true,
}
// VersionFlag prints the version for the application
var VersionFlag Flag = &BoolFlag{
Name: "version",
Aliases: []string{"v"},
Usage: "print the version",
}
// HelpFlag prints the help for all commands and subcommands.
// Set to nil to disable the flag. The subcommand
// will still be added unless HideHelp or HideHelpCommand is set to true.
var HelpFlag Flag = &BoolFlag{
Name: "help",
Aliases: []string{"h"},
Usage: "show help",
}
// FlagStringer converts a flag definition to a string. This is used by help
// to display a flag.
var FlagStringer FlagStringFunc = stringifyFlag
// Serializer is used to circumvent the limitations of flag.FlagSet.Set
type Serializer interface {
Serialize() string
}
// FlagNamePrefixer converts a full flag name and its placeholder into the help
// message flag prefix. This is used by the default FlagStringer.
var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames
// FlagEnvHinter annotates flag help message with the environment variable
// details. This is used by the default FlagStringer.
var FlagEnvHinter FlagEnvHintFunc = withEnvHint
// FlagFileHinter annotates flag help message with the environment variable
// details. This is used by the default FlagStringer.
var FlagFileHinter FlagFileHintFunc = withFileHint
// FlagsByName is a slice of Flag.
type FlagsByName []Flag
func (f FlagsByName) Len() int {
return len(f)
}
func (f FlagsByName) Less(i, j int) bool {
if len(f[j].Names()) == 0 {
return false
} else if len(f[i].Names()) == 0 {
return true
}
return lexicographicLess(f[i].Names()[0], f[j].Names()[0])
}
func (f FlagsByName) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
// Flag is a common interface related to parsing flags in cli.
// For more advanced flag parsing techniques, it is recommended that
// this interface be implemented.
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet) error
Names() []string
IsSet() bool
}
// RequiredFlag is an interface that allows us to mark flags as required
// it allows flags required flags to be backwards compatible with the Flag interface
type RequiredFlag interface {
Flag
IsRequired() bool
}
// DocGenerationFlag is an interface that allows documentation generation for the flag
type DocGenerationFlag interface {
Flag
// TakesValue returns true if the flag takes a value, otherwise false
TakesValue() bool
// GetUsage returns the usage string for the flag
GetUsage() string
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
GetValue() string
}
// VisibleFlag is an interface that allows to check if a flag is visible
type VisibleFlag interface {
Flag
// IsVisible returns true if the flag is not hidden, otherwise false
IsVisible() bool
}
func flagSet(name string, flags []Flag) (*flag.FlagSet, error) {
set := flag.NewFlagSet(name, flag.ContinueOnError)
for _, f := range flags {
if err := f.Apply(set); err != nil {
return nil, err
}
}
set.SetOutput(ioutil.Discard)
return set, nil
}
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
switch ff.Value.(type) {
case Serializer:
_ = set.Set(name, ff.Value.(Serializer).Serialize())
default:
_ = set.Set(name, ff.Value.String())
}
}
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
visited := make(map[string]bool)
set.Visit(func(f *flag.Flag) {
visited[f.Name] = true
})
for _, f := range flags {
parts := f.Names()
if len(parts) == 1 {
continue
}
var ff *flag.Flag
for _, name := range parts {
name = strings.Trim(name, " ")
if visited[name] {
if ff != nil {
return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
}
ff = set.Lookup(name)
}
}
if ff == nil {
continue
}
for _, name := range parts {
name = strings.Trim(name, " ")
if !visited[name] {
copyFlag(name, ff, set)
}
}
}
return nil
}
func visibleFlags(fl []Flag) []Flag {
var visible []Flag
for _, f := range fl {
if vf, ok := f.(VisibleFlag); ok && vf.IsVisible() {
visible = append(visible, f)
}
}
return visible
}
func prefixFor(name string) (prefix string) {
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
// Returns the placeholder, if any, and the unquoted usage string.
func unquoteUsage(usage string) (string, string) {
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name := usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break
}
}
return "", usage
}
func prefixedNames(names []string, placeholder string) string {
var prefixed string
for i, name := range names {
if name == "" {
continue
}
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(names)-1 {
prefixed += ", "
}
}
return prefixed
}
func withEnvHint(envVars []string, str string) string {
envText := ""
if envVars != nil && len(envVars) > 0 {
prefix := "$"
suffix := ""
sep := ", $"
if runtime.GOOS == "windows" {
prefix = "%"
suffix = "%"
sep = "%, %"
}
envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(envVars, sep), suffix)
}
return str + envText
}
func flagNames(name string, aliases []string) []string {
var ret []string
for _, part := range append([]string{name}, aliases...) {
// v1 -> v2 migration warning zone:
// Strip off anything after the first found comma or space, which
// *hopefully* makes it a tiny bit more obvious that unexpected behavior is
// caused by using the v1 form of stringly typed "Name".
ret = append(ret, commaWhitespace.ReplaceAllString(part, ""))
}
return ret
}
func flagStringSliceField(f Flag, name string) []string {
fv := flagValue(f)
field := fv.FieldByName(name)
if field.IsValid() {
return field.Interface().([]string)
}
return []string{}
}
func withFileHint(filePath, str string) string {
fileText := ""
if filePath != "" {
fileText = fmt.Sprintf(" [%s]", filePath)
}
return str + fileText
}
func flagValue(f Flag) reflect.Value {
fv := reflect.ValueOf(f)
for fv.Kind() == reflect.Ptr {
fv = reflect.Indirect(fv)
}
return fv
}
func formatDefault(format string) string {
return " (default: " + format + ")"
}
func stringifyFlag(f Flag) string {
fv := flagValue(f)
switch f := f.(type) {
case *IntSliceFlag:
return withEnvHint(flagStringSliceField(f, "EnvVars"),
stringifyIntSliceFlag(f))
case *Int64SliceFlag:
return withEnvHint(flagStringSliceField(f, "EnvVars"),
stringifyInt64SliceFlag(f))
case *Float64SliceFlag:
return withEnvHint(flagStringSliceField(f, "EnvVars"),
stringifyFloat64SliceFlag(f))
case *StringSliceFlag:
return withEnvHint(flagStringSliceField(f, "EnvVars"),
stringifyStringSliceFlag(f))
}
placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String())
needsPlaceholder := false
defaultValueString := ""
val := fv.FieldByName("Value")
if val.IsValid() {
needsPlaceholder = val.Kind() != reflect.Bool
defaultValueString = fmt.Sprintf(formatDefault("%v"), val.Interface())
if val.Kind() == reflect.String && val.String() != "" {
defaultValueString = fmt.Sprintf(formatDefault("%q"), val.String())
}
}
helpText := fv.FieldByName("DefaultText")
if helpText.IsValid() && helpText.String() != "" {
needsPlaceholder = val.Kind() != reflect.Bool
defaultValueString = fmt.Sprintf(formatDefault("%s"), helpText.String())
}
if defaultValueString == formatDefault("") {
defaultValueString = ""
}
if needsPlaceholder && placeholder == "" {
placeholder = defaultPlaceholder
}
usageWithDefault := strings.TrimSpace(usage + defaultValueString)
return withEnvHint(flagStringSliceField(f, "EnvVars"),
fmt.Sprintf("%s\t%s", prefixedNames(f.Names(), placeholder), usageWithDefault))
}
func stringifyIntSliceFlag(f *IntSliceFlag) string {
var defaultVals []string
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, i := range f.Value.Value() {
defaultVals = append(defaultVals, strconv.Itoa(i))
}
}
return stringifySliceFlag(f.Usage, f.Names(), defaultVals)
}
func stringifyInt64SliceFlag(f *Int64SliceFlag) string {
var defaultVals []string
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, i := range f.Value.Value() {
defaultVals = append(defaultVals, strconv.FormatInt(i, 10))
}
}
return stringifySliceFlag(f.Usage, f.Names(), defaultVals)
}
func stringifyFloat64SliceFlag(f *Float64SliceFlag) string {
var defaultVals []string
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, i := range f.Value.Value() {
defaultVals = append(defaultVals, strings.TrimRight(strings.TrimRight(fmt.Sprintf("%f", i), "0"), "."))
}
}
return stringifySliceFlag(f.Usage, f.Names(), defaultVals)
}
func stringifyStringSliceFlag(f *StringSliceFlag) string {
var defaultVals []string
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, s := range f.Value.Value() {
if len(s) > 0 {
defaultVals = append(defaultVals, strconv.Quote(s))
}
}
}
return stringifySliceFlag(f.Usage, f.Names(), defaultVals)
}
func stringifySliceFlag(usage string, names, defaultVals []string) string {
placeholder, usage := unquoteUsage(usage)
if placeholder == "" {
placeholder = defaultPlaceholder
}
defaultVal := ""
if len(defaultVals) > 0 {
defaultVal = fmt.Sprintf(formatDefault("%s"), strings.Join(defaultVals, ", "))
}
usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))
multiInputString := "(accepts multiple inputs)"
if usageWithDefault != "" {
multiInputString = "\t" + multiInputString
}
return fmt.Sprintf("%s\t%s%s", prefixedNames(names, placeholder), usageWithDefault, multiInputString)
}
func hasFlag(flags []Flag, fl Flag) bool {
for _, existing := range flags {
if fl == existing {
return true
}
}
return false
}
func flagFromEnvOrFile(envVars []string, filePath string) (val string, ok bool) {
for _, envVar := range envVars {
envVar = strings.TrimSpace(envVar)
if val, ok := syscall.Getenv(envVar); ok {
return val, true
}
}
for _, fileVar := range strings.Split(filePath, ",") {
if data, err := ioutil.ReadFile(fileVar); err == nil {
return string(data), true
}
}
return "", false
}

View File

@ -1,111 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// BoolFlag is a flag with type bool
type BoolFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value bool
DefaultText string
Destination *bool
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *BoolFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *BoolFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *BoolFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *BoolFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *BoolFlag) TakesValue() bool {
return false
}
// GetUsage returns the usage string for the flag
func (f *BoolFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *BoolFlag) GetValue() string {
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *BoolFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *BoolFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valBool, err := strconv.ParseBool(val)
if err != nil {
return fmt.Errorf("could not parse %q as bool value for flag %s: %s", val, f.Name, err)
}
f.Value = valBool
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.BoolVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.Bool(name, f.Value, f.Usage)
}
return nil
}
// Bool looks up the value of a local BoolFlag, returns
// false if not found
func (c *Context) Bool(name string) bool {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupBool(name, fs)
}
return false
}
func lookupBool(name string, set *flag.FlagSet) bool {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseBool(f.Value.String())
if err != nil {
return false
}
return parsed
}
return false
}

View File

@ -1,110 +0,0 @@
package cli
import (
"flag"
"fmt"
"time"
)
// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration)
type DurationFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value time.Duration
DefaultText string
Destination *time.Duration
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *DurationFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *DurationFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *DurationFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *DurationFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *DurationFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *DurationFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *DurationFlag) GetValue() string {
return f.Value.String()
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *DurationFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *DurationFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valDuration, err := time.ParseDuration(val)
if err != nil {
return fmt.Errorf("could not parse %q as duration value for flag %s: %s", val, f.Name, err)
}
f.Value = valDuration
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.DurationVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.Duration(name, f.Value, f.Usage)
}
return nil
}
// Duration looks up the value of a local DurationFlag, returns
// 0 if not found
func (c *Context) Duration(name string) time.Duration {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupDuration(name, fs)
}
return 0
}
func lookupDuration(name string, set *flag.FlagSet) time.Duration {
f := set.Lookup(name)
if f != nil {
parsed, err := time.ParseDuration(f.Value.String())
if err != nil {
return 0
}
return parsed
}
return 0
}

View File

@ -1,111 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// Float64Flag is a flag with type float64
type Float64Flag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value float64
DefaultText string
Destination *float64
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *Float64Flag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *Float64Flag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *Float64Flag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *Float64Flag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *Float64Flag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *Float64Flag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *Float64Flag) GetValue() string {
return fmt.Sprintf("%f", f.Value)
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *Float64Flag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *Float64Flag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valFloat, err := strconv.ParseFloat(val, 10)
if err != nil {
return fmt.Errorf("could not parse %q as float64 value for flag %s: %s", val, f.Name, err)
}
f.Value = valFloat
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.Float64Var(f.Destination, name, f.Value, f.Usage)
continue
}
set.Float64(name, f.Value, f.Usage)
}
return nil
}
// Float64 looks up the value of a local Float64Flag, returns
// 0 if not found
func (c *Context) Float64(name string) float64 {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupFloat64(name, fs)
}
return 0
}
func lookupFloat64(name string, set *flag.FlagSet) float64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseFloat(f.Value.String(), 64)
if err != nil {
return 0
}
return parsed
}
return 0
}

View File

@ -1,182 +0,0 @@
package cli
import (
"encoding/json"
"flag"
"fmt"
"strconv"
"strings"
)
// Float64Slice wraps []float64 to satisfy flag.Value
type Float64Slice struct {
slice []float64
hasBeenSet bool
}
// NewFloat64Slice makes a *Float64Slice with default values
func NewFloat64Slice(defaults ...float64) *Float64Slice {
return &Float64Slice{slice: append([]float64{}, defaults...)}
}
// clone allocate a copy of self object
func (f *Float64Slice) clone() *Float64Slice {
n := &Float64Slice{
slice: make([]float64, len(f.slice)),
hasBeenSet: f.hasBeenSet,
}
copy(n.slice, f.slice)
return n
}
// Set parses the value into a float64 and appends it to the list of values
func (f *Float64Slice) Set(value string) error {
if !f.hasBeenSet {
f.slice = []float64{}
f.hasBeenSet = true
}
if strings.HasPrefix(value, slPfx) {
// Deserializing assumes overwrite
_ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &f.slice)
f.hasBeenSet = true
return nil
}
tmp, err := strconv.ParseFloat(value, 64)
if err != nil {
return err
}
f.slice = append(f.slice, tmp)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (f *Float64Slice) String() string {
return fmt.Sprintf("%#v", f.slice)
}
// Serialize allows Float64Slice to fulfill Serializer
func (f *Float64Slice) Serialize() string {
jsonBytes, _ := json.Marshal(f.slice)
return fmt.Sprintf("%s%s", slPfx, string(jsonBytes))
}
// Value returns the slice of float64s set by this flag
func (f *Float64Slice) Value() []float64 {
return f.slice
}
// Get returns the slice of float64s set by this flag
func (f *Float64Slice) Get() interface{} {
return *f
}
// Float64SliceFlag is a flag with type *Float64Slice
type Float64SliceFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value *Float64Slice
DefaultText string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *Float64SliceFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *Float64SliceFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *Float64SliceFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *Float64SliceFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true if the flag takes a value, otherwise false
func (f *Float64SliceFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *Float64SliceFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *Float64SliceFlag) GetValue() string {
if f.Value != nil {
return f.Value.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *Float64SliceFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
f.Value = &Float64Slice{}
for _, s := range strings.Split(val, ",") {
if err := f.Value.Set(strings.TrimSpace(s)); err != nil {
return fmt.Errorf("could not parse %q as float64 slice value for flag %s: %s", f.Value, f.Name, err)
}
}
// Set this to false so that we reset the slice if we then set values from
// flags that have already been set by the environment.
f.Value.hasBeenSet = false
f.HasBeenSet = true
}
}
if f.Value == nil {
f.Value = &Float64Slice{}
}
copyValue := f.Value.clone()
for _, name := range f.Names() {
set.Var(copyValue, name, f.Usage)
}
return nil
}
// Float64Slice looks up the value of a local Float64SliceFlag, returns
// nil if not found
func (c *Context) Float64Slice(name string) []float64 {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupFloat64Slice(name, fs)
}
return nil
}
func lookupFloat64Slice(name string, set *flag.FlagSet) []float64 {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*Float64Slice); ok {
return slice.Value()
}
}
return nil
}

View File

@ -1,113 +0,0 @@
package cli
import (
"flag"
"fmt"
)
// Generic is a generic parseable type identified by a specific flag
type Generic interface {
Set(value string) error
String() string
}
// GenericFlag is a flag with type Generic
type GenericFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
TakesFile bool
Value Generic
DefaultText string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *GenericFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *GenericFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *GenericFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *GenericFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *GenericFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *GenericFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *GenericFlag) GetValue() string {
if f.Value != nil {
return f.Value.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *GenericFlag) IsVisible() bool {
return !f.Hidden
}
// Apply takes the flagset and calls Set on the generic flag with the value
// provided by the user for parsing by the flag
func (f GenericFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
if err := f.Value.Set(val); err != nil {
return fmt.Errorf("could not parse %q as value for flag %s: %s", val, f.Name, err)
}
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
set.Var(f.Value, name, f.Usage)
}
return nil
}
// Generic looks up the value of a local GenericFlag, returns
// nil if not found
func (c *Context) Generic(name string) interface{} {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupGeneric(name, fs)
}
return nil
}
func lookupGeneric(name string, set *flag.FlagSet) interface{} {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value, error(nil)
if err != nil {
return nil
}
return parsed
}
return nil
}

View File

@ -1,111 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// IntFlag is a flag with type int
type IntFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value int
DefaultText string
Destination *int
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *IntFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *IntFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *IntFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *IntFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *IntFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *IntFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *IntFlag) GetValue() string {
return fmt.Sprintf("%d", f.Value)
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *IntFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *IntFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valInt, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %q as int value for flag %s: %s", val, f.Name, err)
}
f.Value = int(valInt)
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.IntVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.Int(name, f.Value, f.Usage)
}
return nil
}
// Int looks up the value of a local IntFlag, returns
// 0 if not found
func (c *Context) Int(name string) int {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupInt(name, fs)
}
return 0
}
func lookupInt(name string, set *flag.FlagSet) int {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
if err != nil {
return 0
}
return int(parsed)
}
return 0
}

View File

@ -1,110 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// Int64Flag is a flag with type int64
type Int64Flag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value int64
DefaultText string
Destination *int64
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *Int64Flag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *Int64Flag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *Int64Flag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *Int64Flag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *Int64Flag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *Int64Flag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *Int64Flag) GetValue() string {
return fmt.Sprintf("%d", f.Value)
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *Int64Flag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *Int64Flag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valInt, err := strconv.ParseInt(val, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %q as int value for flag %s: %s", val, f.Name, err)
}
f.Value = valInt
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.Int64Var(f.Destination, name, f.Value, f.Usage)
continue
}
set.Int64(name, f.Value, f.Usage)
}
return nil
}
// Int64 looks up the value of a local Int64Flag, returns
// 0 if not found
func (c *Context) Int64(name string) int64 {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupInt64(name, fs)
}
return 0
}
func lookupInt64(name string, set *flag.FlagSet) int64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
if err != nil {
return 0
}
return parsed
}
return 0
}

View File

@ -1,181 +0,0 @@
package cli
import (
"encoding/json"
"flag"
"fmt"
"strconv"
"strings"
)
// Int64Slice wraps []int64 to satisfy flag.Value
type Int64Slice struct {
slice []int64
hasBeenSet bool
}
// NewInt64Slice makes an *Int64Slice with default values
func NewInt64Slice(defaults ...int64) *Int64Slice {
return &Int64Slice{slice: append([]int64{}, defaults...)}
}
// clone allocate a copy of self object
func (i *Int64Slice) clone() *Int64Slice {
n := &Int64Slice{
slice: make([]int64, len(i.slice)),
hasBeenSet: i.hasBeenSet,
}
copy(n.slice, i.slice)
return n
}
// Set parses the value into an integer and appends it to the list of values
func (i *Int64Slice) Set(value string) error {
if !i.hasBeenSet {
i.slice = []int64{}
i.hasBeenSet = true
}
if strings.HasPrefix(value, slPfx) {
// Deserializing assumes overwrite
_ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice)
i.hasBeenSet = true
return nil
}
tmp, err := strconv.ParseInt(value, 0, 64)
if err != nil {
return err
}
i.slice = append(i.slice, tmp)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (i *Int64Slice) String() string {
return fmt.Sprintf("%#v", i.slice)
}
// Serialize allows Int64Slice to fulfill Serializer
func (i *Int64Slice) Serialize() string {
jsonBytes, _ := json.Marshal(i.slice)
return fmt.Sprintf("%s%s", slPfx, string(jsonBytes))
}
// Value returns the slice of ints set by this flag
func (i *Int64Slice) Value() []int64 {
return i.slice
}
// Get returns the slice of ints set by this flag
func (i *Int64Slice) Get() interface{} {
return *i
}
// Int64SliceFlag is a flag with type *Int64Slice
type Int64SliceFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value *Int64Slice
DefaultText string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *Int64SliceFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *Int64SliceFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *Int64SliceFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *Int64SliceFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *Int64SliceFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f Int64SliceFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *Int64SliceFlag) GetValue() string {
if f.Value != nil {
return f.Value.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *Int64SliceFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
f.Value = &Int64Slice{}
for _, s := range strings.Split(val, ",") {
if err := f.Value.Set(strings.TrimSpace(s)); err != nil {
return fmt.Errorf("could not parse %q as int64 slice value for flag %s: %s", val, f.Name, err)
}
}
// Set this to false so that we reset the slice if we then set values from
// flags that have already been set by the environment.
f.Value.hasBeenSet = false
f.HasBeenSet = true
}
if f.Value == nil {
f.Value = &Int64Slice{}
}
copyValue := f.Value.clone()
for _, name := range f.Names() {
set.Var(copyValue, name, f.Usage)
}
return nil
}
// Int64Slice looks up the value of a local Int64SliceFlag, returns
// nil if not found
func (c *Context) Int64Slice(name string) []int64 {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupInt64Slice(name, fs)
}
return nil
}
func lookupInt64Slice(name string, set *flag.FlagSet) []int64 {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*Int64Slice); ok {
return slice.Value()
}
}
return nil
}

View File

@ -1,192 +0,0 @@
package cli
import (
"encoding/json"
"flag"
"fmt"
"strconv"
"strings"
)
// IntSlice wraps []int to satisfy flag.Value
type IntSlice struct {
slice []int
hasBeenSet bool
}
// NewIntSlice makes an *IntSlice with default values
func NewIntSlice(defaults ...int) *IntSlice {
return &IntSlice{slice: append([]int{}, defaults...)}
}
// clone allocate a copy of self object
func (i *IntSlice) clone() *IntSlice {
n := &IntSlice{
slice: make([]int, len(i.slice)),
hasBeenSet: i.hasBeenSet,
}
copy(n.slice, i.slice)
return n
}
// TODO: Consistently have specific Set function for Int64 and Float64 ?
// SetInt directly adds an integer to the list of values
func (i *IntSlice) SetInt(value int) {
if !i.hasBeenSet {
i.slice = []int{}
i.hasBeenSet = true
}
i.slice = append(i.slice, value)
}
// Set parses the value into an integer and appends it to the list of values
func (i *IntSlice) Set(value string) error {
if !i.hasBeenSet {
i.slice = []int{}
i.hasBeenSet = true
}
if strings.HasPrefix(value, slPfx) {
// Deserializing assumes overwrite
_ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice)
i.hasBeenSet = true
return nil
}
tmp, err := strconv.ParseInt(value, 0, 64)
if err != nil {
return err
}
i.slice = append(i.slice, int(tmp))
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (i *IntSlice) String() string {
return fmt.Sprintf("%#v", i.slice)
}
// Serialize allows IntSlice to fulfill Serializer
func (i *IntSlice) Serialize() string {
jsonBytes, _ := json.Marshal(i.slice)
return fmt.Sprintf("%s%s", slPfx, string(jsonBytes))
}
// Value returns the slice of ints set by this flag
func (i *IntSlice) Value() []int {
return i.slice
}
// Get returns the slice of ints set by this flag
func (i *IntSlice) Get() interface{} {
return *i
}
// IntSliceFlag is a flag with type *IntSlice
type IntSliceFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value *IntSlice
DefaultText string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *IntSliceFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *IntSliceFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *IntSliceFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *IntSliceFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *IntSliceFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f IntSliceFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *IntSliceFlag) GetValue() string {
if f.Value != nil {
return f.Value.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *IntSliceFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *IntSliceFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
f.Value = &IntSlice{}
for _, s := range strings.Split(val, ",") {
if err := f.Value.Set(strings.TrimSpace(s)); err != nil {
return fmt.Errorf("could not parse %q as int slice value for flag %s: %s", val, f.Name, err)
}
}
// Set this to false so that we reset the slice if we then set values from
// flags that have already been set by the environment.
f.Value.hasBeenSet = false
f.HasBeenSet = true
}
if f.Value == nil {
f.Value = &IntSlice{}
}
copyValue := f.Value.clone()
for _, name := range f.Names() {
set.Var(copyValue, name, f.Usage)
}
return nil
}
// IntSlice looks up the value of a local IntSliceFlag, returns
// nil if not found
func (c *Context) IntSlice(name string) []int {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupIntSlice(name, fs)
}
return nil
}
func lookupIntSlice(name string, set *flag.FlagSet) []int {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*IntSlice); ok {
return slice.Value()
}
}
return nil
}

View File

@ -1,100 +0,0 @@
package cli
import "flag"
type PathFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
TakesFile bool
Value string
DefaultText string
Destination *string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *PathFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *PathFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *PathFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *PathFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *PathFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *PathFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *PathFlag) GetValue() string {
return f.Value
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *PathFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *PathFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
f.Value = val
f.HasBeenSet = true
}
for _, name := range f.Names() {
if f.Destination != nil {
set.StringVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.String(name, f.Value, f.Usage)
}
return nil
}
// Path looks up the value of a local PathFlag, returns
// "" if not found
func (c *Context) Path(name string) string {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupPath(name, fs)
}
return ""
}
func lookupPath(name string, set *flag.FlagSet) string {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value.String(), error(nil)
if err != nil {
return ""
}
return parsed
}
return ""
}

View File

@ -1,100 +0,0 @@
package cli
import "flag"
// StringFlag is a flag with type string
type StringFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
TakesFile bool
Value string
DefaultText string
Destination *string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *StringFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *StringFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *StringFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *StringFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *StringFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *StringFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *StringFlag) GetValue() string {
return f.Value
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *StringFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *StringFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
f.Value = val
f.HasBeenSet = true
}
for _, name := range f.Names() {
if f.Destination != nil {
set.StringVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.String(name, f.Value, f.Usage)
}
return nil
}
// String looks up the value of a local StringFlag, returns
// "" if not found
func (c *Context) String(name string) string {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupString(name, fs)
}
return ""
}
func lookupString(name string, set *flag.FlagSet) string {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value.String(), error(nil)
if err != nil {
return ""
}
return parsed
}
return ""
}

View File

@ -1,193 +0,0 @@
package cli
import (
"encoding/json"
"flag"
"fmt"
"strings"
)
// StringSlice wraps a []string to satisfy flag.Value
type StringSlice struct {
slice []string
hasBeenSet bool
}
// NewStringSlice creates a *StringSlice with default values
func NewStringSlice(defaults ...string) *StringSlice {
return &StringSlice{slice: append([]string{}, defaults...)}
}
// clone allocate a copy of self object
func (s *StringSlice) clone() *StringSlice {
n := &StringSlice{
slice: make([]string, len(s.slice)),
hasBeenSet: s.hasBeenSet,
}
copy(n.slice, s.slice)
return n
}
// Set appends the string value to the list of values
func (s *StringSlice) Set(value string) error {
if !s.hasBeenSet {
s.slice = []string{}
s.hasBeenSet = true
}
if strings.HasPrefix(value, slPfx) {
// Deserializing assumes overwrite
_ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &s.slice)
s.hasBeenSet = true
return nil
}
s.slice = append(s.slice, value)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (s *StringSlice) String() string {
return fmt.Sprintf("%s", s.slice)
}
// Serialize allows StringSlice to fulfill Serializer
func (s *StringSlice) Serialize() string {
jsonBytes, _ := json.Marshal(s.slice)
return fmt.Sprintf("%s%s", slPfx, string(jsonBytes))
}
// Value returns the slice of strings set by this flag
func (s *StringSlice) Value() []string {
return s.slice
}
// Get returns the slice of strings set by this flag
func (s *StringSlice) Get() interface{} {
return *s
}
// StringSliceFlag is a flag with type *StringSlice
type StringSliceFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
TakesFile bool
Value *StringSlice
DefaultText string
HasBeenSet bool
Destination *StringSlice
}
// IsSet returns whether or not the flag has been set through env or file
func (f *StringSliceFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *StringSliceFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *StringSliceFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *StringSliceFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *StringSliceFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *StringSliceFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *StringSliceFlag) GetValue() string {
if f.Value != nil {
return f.Value.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *StringSliceFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
if f.Destination != nil && f.Value != nil {
f.Destination.slice = make([]string, len(f.Value.slice))
copy(f.Destination.slice, f.Value.slice)
}
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if f.Value == nil {
f.Value = &StringSlice{}
}
destination := f.Value
if f.Destination != nil {
destination = f.Destination
}
for _, s := range strings.Split(val, ",") {
if err := destination.Set(strings.TrimSpace(s)); err != nil {
return fmt.Errorf("could not parse %q as string value for flag %s: %s", val, f.Name, err)
}
}
// Set this to false so that we reset the slice if we then set values from
// flags that have already been set by the environment.
destination.hasBeenSet = false
f.HasBeenSet = true
}
if f.Value == nil {
f.Value = &StringSlice{}
}
setValue := f.Destination
if f.Destination == nil {
setValue = f.Value.clone()
}
for _, name := range f.Names() {
set.Var(setValue, name, f.Usage)
}
return nil
}
// StringSlice looks up the value of a local StringSliceFlag, returns
// nil if not found
func (c *Context) StringSlice(name string) []string {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupStringSlice(name, fs)
}
return nil
}
func lookupStringSlice(name string, set *flag.FlagSet) []string {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*StringSlice); ok {
return slice.Value()
}
}
return nil
}

View File

@ -1,169 +0,0 @@
package cli
import (
"flag"
"fmt"
"time"
)
// Timestamp wrap to satisfy golang's flag interface.
type Timestamp struct {
timestamp *time.Time
hasBeenSet bool
layout string
}
// Timestamp constructor
func NewTimestamp(timestamp time.Time) *Timestamp {
return &Timestamp{timestamp: &timestamp}
}
// Set the timestamp value directly
func (t *Timestamp) SetTimestamp(value time.Time) {
if !t.hasBeenSet {
t.timestamp = &value
t.hasBeenSet = true
}
}
// Set the timestamp string layout for future parsing
func (t *Timestamp) SetLayout(layout string) {
t.layout = layout
}
// Parses the string value to timestamp
func (t *Timestamp) Set(value string) error {
timestamp, err := time.Parse(t.layout, value)
if err != nil {
return err
}
t.timestamp = &timestamp
t.hasBeenSet = true
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (t *Timestamp) String() string {
return fmt.Sprintf("%#v", t.timestamp)
}
// Value returns the timestamp value stored in the flag
func (t *Timestamp) Value() *time.Time {
return t.timestamp
}
// Get returns the flag structure
func (t *Timestamp) Get() interface{} {
return *t
}
// TimestampFlag is a flag with type time
type TimestampFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Layout string
Value *Timestamp
DefaultText string
HasBeenSet bool
Destination *Timestamp
}
// IsSet returns whether or not the flag has been set through env or file
func (f *TimestampFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *TimestampFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *TimestampFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *TimestampFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *TimestampFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *TimestampFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *TimestampFlag) GetValue() string {
if f.Value != nil {
return f.Value.timestamp.String()
}
return ""
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *TimestampFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *TimestampFlag) Apply(set *flag.FlagSet) error {
if f.Layout == "" {
return fmt.Errorf("timestamp Layout is required")
}
if f.Value == nil {
f.Value = &Timestamp{}
}
f.Value.SetLayout(f.Layout)
if f.Destination != nil {
f.Destination.SetLayout(f.Layout)
}
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if err := f.Value.Set(val); err != nil {
return fmt.Errorf("could not parse %q as timestamp value for flag %s: %s", val, f.Name, err)
}
f.HasBeenSet = true
}
for _, name := range f.Names() {
if f.Destination != nil {
set.Var(f.Destination, name, f.Usage)
continue
}
set.Var(f.Value, name, f.Usage)
}
return nil
}
// Timestamp gets the timestamp from a flag name
func (c *Context) Timestamp(name string) *time.Time {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupTimestamp(name, fs)
}
return nil
}
// Fetches the timestamp value from the local timestampWrap
func lookupTimestamp(name string, set *flag.FlagSet) *time.Time {
f := set.Lookup(name)
if f != nil {
return (f.Value.(*Timestamp)).Value()
}
return nil
}

View File

@ -1,110 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// UintFlag is a flag with type uint
type UintFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value uint
DefaultText string
Destination *uint
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *UintFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *UintFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *UintFlag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *UintFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *UintFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *UintFlag) GetUsage() string {
return f.Usage
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *UintFlag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *UintFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valInt, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %q as uint value for flag %s: %s", val, f.Name, err)
}
f.Value = uint(valInt)
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.UintVar(f.Destination, name, f.Value, f.Usage)
continue
}
set.Uint(name, f.Value, f.Usage)
}
return nil
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *UintFlag) GetValue() string {
return fmt.Sprintf("%d", f.Value)
}
// Uint looks up the value of a local UintFlag, returns
// 0 if not found
func (c *Context) Uint(name string) uint {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupUint(name, fs)
}
return 0
}
func lookupUint(name string, set *flag.FlagSet) uint {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
if err != nil {
return 0
}
return uint(parsed)
}
return 0
}

View File

@ -1,110 +0,0 @@
package cli
import (
"flag"
"fmt"
"strconv"
)
// Uint64Flag is a flag with type uint64
type Uint64Flag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value uint64
DefaultText string
Destination *uint64
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *Uint64Flag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *Uint64Flag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *Uint64Flag) Names() []string {
return flagNames(f.Name, f.Aliases)
}
// IsRequired returns whether or not the flag is required
func (f *Uint64Flag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *Uint64Flag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *Uint64Flag) GetUsage() string {
return f.Usage
}
// IsVisible returns true if the flag is not hidden, otherwise false
func (f *Uint64Flag) IsVisible() bool {
return !f.Hidden
}
// Apply populates the flag given the flag set and environment
func (f *Uint64Flag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
valInt, err := strconv.ParseUint(val, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %q as uint64 value for flag %s: %s", val, f.Name, err)
}
f.Value = valInt
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
if f.Destination != nil {
set.Uint64Var(f.Destination, name, f.Value, f.Usage)
continue
}
set.Uint64(name, f.Value, f.Usage)
}
return nil
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *Uint64Flag) GetValue() string {
return fmt.Sprintf("%d", f.Value)
}
// Uint64 looks up the value of a local Uint64Flag, returns
// 0 if not found
func (c *Context) Uint64(name string) uint64 {
if fs := c.lookupFlagSet(name); fs != nil {
return lookupUint64(name, fs)
}
return 0
}
func lookupUint64(name string, set *flag.FlagSet) uint64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
if err != nil {
return 0
}
return parsed
}
return 0
}

View File

@ -1,44 +0,0 @@
package cli
// BashCompleteFunc is an action to execute when the shell completion flag is set
type BashCompleteFunc func(*Context)
// BeforeFunc is an action to execute before any subcommands are run, but after
// the context is ready if a non-nil error is returned, no subcommands are run
type BeforeFunc func(*Context) error
// AfterFunc is an action to execute after any subcommands are run, but after the
// subcommand has finished it is run even if Action() panics
type AfterFunc func(*Context) error
// ActionFunc is the action to execute when no subcommands are specified
type ActionFunc func(*Context) error
// CommandNotFoundFunc is executed if the proper command cannot be found
type CommandNotFoundFunc func(*Context, string)
// OnUsageErrorFunc is executed if a usage error occurs. This is useful for displaying
// customized usage error messages. This function is able to replace the
// original error messages. If this function is not set, the "Incorrect usage"
// is displayed and the execution is interrupted.
type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error
// ExitErrHandlerFunc is executed if provided in order to handle exitError values
// returned by Actions and Before/After functions.
type ExitErrHandlerFunc func(context *Context, err error)
// FlagStringFunc is used by the help generation to display a flag, which is
// expected to be a single line.
type FlagStringFunc func(Flag) string
// FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix
// text for a flag's full name.
type FlagNamePrefixFunc func(fullName []string, placeholder string) string
// FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help
// with the environment variable details.
type FlagEnvHintFunc func(envVars []string, str string) string
// FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help
// with the file path details.
type FlagFileHintFunc func(filePath, str string) string

View File

@ -1,386 +0,0 @@
package cli
import (
"fmt"
"io"
"os"
"strings"
"text/tabwriter"
"text/template"
"unicode/utf8"
)
var helpCommand = &Command{
Name: "help",
Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
ArgsUsage: "[command]",
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
return ShowCommandHelp(c, args.First())
}
_ = ShowAppHelp(c)
return nil
},
}
var helpSubcommand = &Command{
Name: "help",
Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
ArgsUsage: "[command]",
Action: func(c *Context) error {
args := c.Args()
if args.Present() {
return ShowCommandHelp(c, args.First())
}
return ShowSubcommandHelp(c)
},
}
// Prints help for the App or Command
type helpPrinter func(w io.Writer, templ string, data interface{})
// Prints help for the App or Command with custom template function.
type helpPrinterCustom func(w io.Writer, templ string, data interface{}, customFunc map[string]interface{})
// HelpPrinter is a function that writes the help output. If not set explicitly,
// this calls HelpPrinterCustom using only the default template functions.
//
// If custom logic for printing help is required, this function can be
// overridden. If the ExtraInfo field is defined on an App, this function
// should not be modified, as HelpPrinterCustom will be used directly in order
// to capture the extra information.
var HelpPrinter helpPrinter = printHelp
// HelpPrinterCustom is a function that writes the help output. It is used as
// the default implementation of HelpPrinter, and may be called directly if
// the ExtraInfo field is set on an App.
var HelpPrinterCustom helpPrinterCustom = printHelpCustom
// VersionPrinter prints the version for the App
var VersionPrinter = printVersion
// ShowAppHelpAndExit - Prints the list of subcommands for the app and exits with exit code.
func ShowAppHelpAndExit(c *Context, exitCode int) {
_ = ShowAppHelp(c)
os.Exit(exitCode)
}
// ShowAppHelp is an action that displays the help.
func ShowAppHelp(c *Context) error {
tpl := c.App.CustomAppHelpTemplate
if tpl == "" {
tpl = AppHelpTemplate
}
if c.App.ExtraInfo == nil {
HelpPrinter(c.App.Writer, tpl, c.App)
return nil
}
customAppData := func() map[string]interface{} {
return map[string]interface{}{
"ExtraInfo": c.App.ExtraInfo,
}
}
HelpPrinterCustom(c.App.Writer, tpl, c.App, customAppData())
return nil
}
// DefaultAppComplete prints the list of subcommands as the default app completion method
func DefaultAppComplete(c *Context) {
DefaultCompleteWithFlags(nil)(c)
}
func printCommandSuggestions(commands []*Command, writer io.Writer) {
for _, command := range commands {
if command.Hidden {
continue
}
if os.Getenv("_CLI_ZSH_AUTOCOMPLETE_HACK") == "1" {
for _, name := range command.Names() {
_, _ = fmt.Fprintf(writer, "%s:%s\n", name, command.Usage)
}
} else {
for _, name := range command.Names() {
_, _ = fmt.Fprintf(writer, "%s\n", name)
}
}
}
}
func cliArgContains(flagName string) bool {
for _, name := range strings.Split(flagName, ",") {
name = strings.TrimSpace(name)
count := utf8.RuneCountInString(name)
if count > 2 {
count = 2
}
flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
for _, a := range os.Args {
if a == flag {
return true
}
}
}
return false
}
func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {
cur := strings.TrimPrefix(lastArg, "-")
cur = strings.TrimPrefix(cur, "-")
for _, flag := range flags {
if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden {
continue
}
for _, name := range flag.Names() {
name = strings.TrimSpace(name)
// this will get total count utf8 letters in flag name
count := utf8.RuneCountInString(name)
if count > 2 {
count = 2 // resuse this count to generate single - or -- in flag completion
}
// if flag name has more than one utf8 letter and last argument in cli has -- prefix then
// skip flag completion for short flags example -v or -x
if strings.HasPrefix(lastArg, "--") && count == 1 {
continue
}
// match if last argument matches this flag and it is not repeated
if strings.HasPrefix(name, cur) && cur != name && !cliArgContains(name) {
flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name)
_, _ = fmt.Fprintln(writer, flagCompletion)
}
}
}
}
func DefaultCompleteWithFlags(cmd *Command) func(c *Context) {
return func(c *Context) {
if len(os.Args) > 2 {
lastArg := os.Args[len(os.Args)-2]
if strings.HasPrefix(lastArg, "-") {
printFlagSuggestions(lastArg, c.App.Flags, c.App.Writer)
if cmd != nil {
printFlagSuggestions(lastArg, cmd.Flags, c.App.Writer)
}
return
}
}
if cmd != nil {
printCommandSuggestions(cmd.Subcommands, c.App.Writer)
} else {
printCommandSuggestions(c.App.Commands, c.App.Writer)
}
}
}
// ShowCommandHelpAndExit - exits with code after showing help
func ShowCommandHelpAndExit(c *Context, command string, code int) {
_ = ShowCommandHelp(c, command)
os.Exit(code)
}
// ShowCommandHelp prints help for the given command
func ShowCommandHelp(ctx *Context, command string) error {
// show the subcommand help for a command with subcommands
if command == "" {
HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
return nil
}
for _, c := range ctx.App.Commands {
if c.HasName(command) {
templ := c.CustomHelpTemplate
if templ == "" {
templ = CommandHelpTemplate
}
HelpPrinter(ctx.App.Writer, templ, c)
return nil
}
}
if ctx.App.CommandNotFound == nil {
return Exit(fmt.Sprintf("No help topic for '%v'", command), 3)
}
ctx.App.CommandNotFound(ctx, command)
return nil
}
// ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.
func ShowSubcommandHelpAndExit(c *Context, exitCode int) {
_ = ShowSubcommandHelp(c)
os.Exit(exitCode)
}
// ShowSubcommandHelp prints help for the given subcommand
func ShowSubcommandHelp(c *Context) error {
if c == nil {
return nil
}
if c.Command != nil {
return ShowCommandHelp(c, c.Command.Name)
}
return ShowCommandHelp(c, "")
}
// ShowVersion prints the version number of the App
func ShowVersion(c *Context) {
VersionPrinter(c)
}
func printVersion(c *Context) {
_, _ = fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
}
// ShowCompletions prints the lists of commands within a given context
func ShowCompletions(c *Context) {
a := c.App
if a != nil && a.BashComplete != nil {
a.BashComplete(c)
}
}
// ShowCommandCompletions prints the custom completions for a given command
func ShowCommandCompletions(ctx *Context, command string) {
c := ctx.App.Command(command)
if c != nil {
if c.BashComplete != nil {
c.BashComplete(ctx)
} else {
DefaultCompleteWithFlags(c)(ctx)
}
}
}
// printHelpCustom is the default implementation of HelpPrinterCustom.
//
// The customFuncs map will be combined with a default template.FuncMap to
// allow using arbitrary functions in template rendering.
func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) {
funcMap := template.FuncMap{
"join": strings.Join,
"indent": indent,
"nindent": nindent,
"trim": strings.TrimSpace,
}
for key, value := range customFuncs {
funcMap[key] = value
}
w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0)
t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
err := t.Execute(w, data)
if err != nil {
// If the writer is closed, t.Execute will fail, and there's nothing
// we can do to recover.
if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" {
_, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err)
}
return
}
_ = w.Flush()
}
func printHelp(out io.Writer, templ string, data interface{}) {
HelpPrinterCustom(out, templ, data, nil)
}
func checkVersion(c *Context) bool {
found := false
for _, name := range VersionFlag.Names() {
if c.Bool(name) {
found = true
}
}
return found
}
func checkHelp(c *Context) bool {
found := false
for _, name := range HelpFlag.Names() {
if c.Bool(name) {
found = true
}
}
return found
}
func checkCommandHelp(c *Context, name string) bool {
if c.Bool("h") || c.Bool("help") {
_ = ShowCommandHelp(c, name)
return true
}
return false
}
func checkSubcommandHelp(c *Context) bool {
if c.Bool("h") || c.Bool("help") {
_ = ShowSubcommandHelp(c)
return true
}
return false
}
func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) {
if !a.EnableBashCompletion {
return false, arguments
}
pos := len(arguments) - 1
lastArg := arguments[pos]
if lastArg != "--generate-bash-completion" {
return false, arguments
}
return true, arguments[:pos]
}
func checkCompletions(c *Context) bool {
if !c.shellComplete {
return false
}
if args := c.Args(); args.Present() {
name := args.First()
if cmd := c.App.Command(name); cmd != nil {
// var the command handle the completion
return false
}
}
ShowCompletions(c)
return true
}
func checkCommandCompletions(c *Context, name string) bool {
if !c.shellComplete {
return false
}
ShowCommandCompletions(c, name)
return true
}
func indent(spaces int, v string) string {
pad := strings.Repeat(" ", spaces)
return pad + strings.Replace(v, "\n", "\n"+pad, -1)
}
func nindent(spaces int, v string) string {
return "\n" + indent(spaces, v)
}

View File

@ -1,94 +0,0 @@
package cli
import (
"flag"
"strings"
)
type iterativeParser interface {
newFlagSet() (*flag.FlagSet, error)
useShortOptionHandling() bool
}
// To enable short-option handling (e.g., "-it" vs "-i -t") we have to
// iteratively catch parsing errors. This way we achieve LR parsing without
// transforming any arguments. Otherwise, there is no way we can discriminate
// combined short options from common arguments that should be left untouched.
// Pass `shellComplete` to continue parsing options on failure during shell
// completion when, the user-supplied options may be incomplete.
func parseIter(set *flag.FlagSet, ip iterativeParser, args []string, shellComplete bool) error {
for {
err := set.Parse(args)
if !ip.useShortOptionHandling() || err == nil {
if shellComplete {
return nil
}
return err
}
errStr := err.Error()
trimmed := strings.TrimPrefix(errStr, "flag provided but not defined: -")
if errStr == trimmed {
return err
}
// regenerate the initial args with the split short opts
argsWereSplit := false
for i, arg := range args {
// skip args that are not part of the error message
if name := strings.TrimLeft(arg, "-"); name != trimmed {
continue
}
// if we can't split, the error was accurate
shortOpts := splitShortOptions(set, arg)
if len(shortOpts) == 1 {
return err
}
// swap current argument with the split version
args = append(args[:i], append(shortOpts, args[i+1:]...)...)
argsWereSplit = true
break
}
// This should be an impossible to reach code path, but in case the arg
// splitting failed to happen, this will prevent infinite loops
if !argsWereSplit {
return err
}
// Since custom parsing failed, replace the flag set before retrying
newSet, err := ip.newFlagSet()
if err != nil {
return err
}
*set = *newSet
}
}
func splitShortOptions(set *flag.FlagSet, arg string) []string {
shortFlagsExist := func(s string) bool {
for _, c := range s[1:] {
if f := set.Lookup(string(c)); f == nil {
return false
}
}
return true
}
if !isSplittable(arg) || !shortFlagsExist(arg) {
return []string{arg}
}
separated := make([]string, 0, len(arg)-1)
for _, flagChar := range arg[1:] {
separated = append(separated, "-"+string(flagChar))
}
return separated
}
func isSplittable(flagArg string) bool {
return strings.HasPrefix(flagArg, "-") && !strings.HasPrefix(flagArg, "--") && len(flagArg) > 2
}

View File

@ -1,29 +0,0 @@
package cli
import "unicode"
// lexicographicLess compares strings alphabetically considering case.
func lexicographicLess(i, j string) bool {
iRunes := []rune(i)
jRunes := []rune(j)
lenShared := len(iRunes)
if lenShared > len(jRunes) {
lenShared = len(jRunes)
}
for index := 0; index < lenShared; index++ {
ir := iRunes[index]
jr := jRunes[index]
if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr {
return lir < ljr
}
if ir != jr {
return ir < jr
}
}
return i < j
}

View File

@ -1,122 +0,0 @@
package cli
// AppHelpTemplate is the text template for the Default help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var AppHelpTemplate = `NAME:
{{.Name}}{{if .Usage}} - {{.Usage}}{{end}}
USAGE:
{{if .UsageText}}{{.UsageText | nindent 3 | trim}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
{{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
{{range $index, $option := .VisibleFlags}}{{if $index}}
{{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{.Copyright}}{{end}}
`
// CommandHelpTemplate is the text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var CommandHelpTemplate = `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{if .UsageText}}{{.UsageText | nindent 3 | trim}}{{else}}{{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Category}}
CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}{{if .VisibleFlags}}
OPTIONS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
`
// SubcommandHelpTemplate is the text template for the subcommand help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var SubcommandHelpTemplate = `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{if .UsageText}}{{.UsageText | nindent 3 | trim}}{{else}}{{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{range .VisibleCommands}}
{{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
OPTIONS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
`
var MarkdownDocTemplate = `{{if gt .SectionNum 0}}% {{ .App.Name }} {{ .SectionNum }}
{{end}}# NAME
{{ .App.Name }}{{ if .App.Usage }} - {{ .App.Usage }}{{ end }}
# SYNOPSIS
{{ .App.Name }}
{{ if .SynopsisArgs }}
` + "```" + `
{{ range $v := .SynopsisArgs }}{{ $v }}{{ end }}` + "```" + `
{{ end }}{{ if .App.Description }}
# DESCRIPTION
{{ .App.Description }}
{{ end }}
**Usage**:
` + "```" + `{{ if .App.UsageText }}
{{ .App.UsageText }}
{{ else }}
{{ .App.Name }} [GLOBAL OPTIONS] command [COMMAND OPTIONS] [ARGUMENTS...]
{{ end }}` + "```" + `
{{ if .GlobalArgs }}
# GLOBAL OPTIONS
{{ range $v := .GlobalArgs }}
{{ $v }}{{ end }}
{{ end }}{{ if .Commands }}
# COMMANDS
{{ range $v := .Commands }}
{{ $v }}{{ end }}{{ end }}`
var FishCompletionTemplate = `# {{ .App.Name }} fish shell completion
function __fish_{{ .App.Name }}_no_subcommand --description 'Test if there has been any subcommand yet'
for i in (commandline -opc)
if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }}
return 1
end
end
return 0
end
{{ range $v := .Completions }}{{ $v }}
{{ end }}`

View File

@ -1,9 +0,0 @@
Copyright (c) 2016 Sourcegraph Inc
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,12 +0,0 @@
# jsonrpc2: JSON-RPC 2.0 implementation for Go [![Build Status](https://travis-ci.org/sourcegraph/jsonrpc2.svg)](https://travis-ci.org/sourcegraph/jsonrpc2) [![Sourcegraph](https://sourcegraph.com/github.com/sourcegraph/jsonrpc2/-/badge.svg)](https://sourcegraph.com/github.com/sourcegraph/jsonrpc2?badge) [![GoDoc](https://godoc.org/github.com/sourcegraph/jsonrpc2?status.svg)](https://godoc.org/github.com/sourcegraph/jsonrpc2)
Package jsonrpc2 provides a [Go](https://golang.org) implementation of [JSON-RPC 2.0](http://www.jsonrpc.org/specification).
This package is **experimental** until further notice.
[**Open the code in Sourcegraph**](https://sourcegraph.com/github.com/sourcegraph/jsonrpc2)
## Known issues
* Batch requests and responses are not yet supported.

View File

@ -1,17 +0,0 @@
package jsonrpc2
import "context"
// AsyncHandler wraps a Handler such that each request is handled in its own
// goroutine. It is a convenience wrapper.
func AsyncHandler(h Handler) Handler {
return asyncHandler{h}
}
type asyncHandler struct {
Handler
}
func (h asyncHandler) Handle(ctx context.Context, conn *Conn, req *Request) {
go h.Handler.Handle(ctx, conn, req)
}

View File

@ -1,48 +0,0 @@
package jsonrpc2
// CallOption is an option that can be provided to (*Conn).Call to
// configure custom behavior. See Meta.
type CallOption interface {
apply(r *Request) error
}
type callOptionFunc func(r *Request) error
func (c callOptionFunc) apply(r *Request) error { return c(r) }
// Meta returns a call option which attaches the given meta object to
// the JSON-RPC 2.0 request (this is a Sourcegraph extension to JSON
// RPC 2.0 for carrying metadata).
func Meta(meta interface{}) CallOption {
return callOptionFunc(func(r *Request) error {
return r.SetMeta(meta)
})
}
// ExtraField returns a call option which attaches the given name/value pair to
// the JSON-RPC 2.0 request. This can be used to add arbitrary extensions to
// JSON RPC 2.0.
func ExtraField(name string, value interface{}) CallOption {
return callOptionFunc(func(r *Request) error {
return r.SetExtraField(name, value)
})
}
// PickID returns a call option which sets the ID on a request. Care must be
// taken to ensure there are no conflicts with any previously picked ID, nor
// with the default sequence ID.
func PickID(id ID) CallOption {
return callOptionFunc(func(r *Request) error {
r.ID = id
return nil
})
}
// StringID returns a call option that instructs the request ID to be set as a
// string.
func StringID() CallOption {
return callOptionFunc(func(r *Request) error {
r.ID.IsString = true
return nil
})
}

View File

@ -1,471 +0,0 @@
package jsonrpc2
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log"
"os"
"strconv"
"sync"
)
// Conn is a JSON-RPC client/server connection. The JSON-RPC protocol
// is symmetric, so a Conn runs on both ends of a client-server
// connection.
type Conn struct {
stream ObjectStream
h Handler
mu sync.Mutex
closed bool
seq uint64
pending map[ID]*call
sending sync.Mutex
disconnect chan struct{}
logger Logger
// Set by ConnOpt funcs.
onRecv []func(*Request, *Response)
onSend []func(*Request, *Response)
}
var _ JSONRPC2 = (*Conn)(nil)
// NewConn creates a new JSON-RPC client/server connection using the
// given ReadWriteCloser (typically a TCP connection or stdio). The
// JSON-RPC protocol is symmetric, so a Conn runs on both ends of a
// client-server connection.
//
// NewClient consumes conn, so you should call Close on the returned
// client not on the given conn.
func NewConn(ctx context.Context, stream ObjectStream, h Handler, opts ...ConnOpt) *Conn {
c := &Conn{
stream: stream,
h: h,
pending: map[ID]*call{},
disconnect: make(chan struct{}),
logger: log.New(os.Stderr, "", log.LstdFlags),
}
for _, opt := range opts {
if opt == nil {
continue
}
opt(c)
}
go c.readMessages(ctx)
return c
}
// Close closes the JSON-RPC connection. The connection may not be
// used after it has been closed.
func (c *Conn) Close() error {
return c.close(nil)
}
// Call initiates a JSON-RPC call using the specified method and params, and
// waits for the response. If the response is successful, its result is stored
// in result (a pointer to a value that can be JSON-unmarshaled into);
// otherwise, a non-nil error is returned. See DispatchCall for more details.
func (c *Conn) Call(ctx context.Context, method string, params, result interface{}, opts ...CallOption) error {
call, err := c.DispatchCall(ctx, method, params, opts...)
if err != nil {
return err
}
return call.Wait(ctx, result)
}
// DisconnectNotify returns a channel that is closed when the
// underlying connection is disconnected.
func (c *Conn) DisconnectNotify() <-chan struct{} {
return c.disconnect
}
// DispatchCall dispatches a JSON-RPC call using the specified method and
// params, and returns a call proxy or an error. Call Wait() on the returned
// proxy to receive the response. Only use this function if you need to do work
// after dispatching the request, otherwise use Call.
//
// The params member is omitted from the JSON-RPC request if the given params is
// nil. Use json.RawMessage("null") to send a JSON-RPC request with its params
// member set to null.
func (c *Conn) DispatchCall(ctx context.Context, method string, params interface{}, opts ...CallOption) (Waiter, error) {
req := &Request{Method: method}
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt.apply(req); err != nil {
return Waiter{}, err
}
}
if params != nil {
if err := req.SetParams(params); err != nil {
return Waiter{}, err
}
}
call, err := c.send(ctx, &anyMessage{request: req}, true)
if err != nil {
return Waiter{}, err
}
return Waiter{call: call}, nil
}
// Notify is like Call, but it returns when the notification request is sent
// (without waiting for a response, because JSON-RPC notifications do not have
// responses).
//
// The params member is omitted from the JSON-RPC request if the given params is
// nil. Use json.RawMessage("null") to send a JSON-RPC request with its params
// member set to null.
func (c *Conn) Notify(ctx context.Context, method string, params interface{}, opts ...CallOption) error {
req := &Request{Method: method, Notif: true}
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt.apply(req); err != nil {
return err
}
}
if params != nil {
if err := req.SetParams(params); err != nil {
return err
}
}
_, err := c.send(ctx, &anyMessage{request: req}, false)
return err
}
// Reply sends a successful response with a result.
func (c *Conn) Reply(ctx context.Context, id ID, result interface{}) error {
resp := &Response{ID: id}
if err := resp.SetResult(result); err != nil {
return err
}
_, err := c.send(ctx, &anyMessage{response: resp}, false)
return err
}
// ReplyWithError sends a response with an error.
func (c *Conn) ReplyWithError(ctx context.Context, id ID, respErr *Error) error {
_, err := c.send(ctx, &anyMessage{response: &Response{ID: id, Error: respErr}}, false)
return err
}
// SendResponse sends resp to the peer. It is lower level than (*Conn).Reply.
func (c *Conn) SendResponse(ctx context.Context, resp *Response) error {
_, err := c.send(ctx, &anyMessage{response: resp}, false)
return err
}
func (c *Conn) close(cause error) error {
c.sending.Lock()
c.mu.Lock()
defer c.sending.Unlock()
defer c.mu.Unlock()
if c.closed {
return ErrClosed
}
for _, call := range c.pending {
close(call.done)
}
if cause != nil && cause != io.EOF && cause != io.ErrUnexpectedEOF {
c.logger.Printf("jsonrpc2: protocol error: %v\n", cause)
}
close(c.disconnect)
c.closed = true
return c.stream.Close()
}
func (c *Conn) readMessages(ctx context.Context) {
var err error
for err == nil {
var m anyMessage
err = c.stream.ReadObject(&m)
if err != nil {
break
}
switch {
case m.request != nil:
for _, onRecv := range c.onRecv {
onRecv(m.request, nil)
}
c.h.Handle(ctx, c, m.request)
case m.response != nil:
resp := m.response
if resp != nil {
id := resp.ID
c.mu.Lock()
call := c.pending[id]
delete(c.pending, id)
c.mu.Unlock()
if call != nil {
call.response = resp
}
if len(c.onRecv) > 0 {
var req *Request
if call != nil {
req = call.request
}
for _, onRecv := range c.onRecv {
onRecv(req, resp)
}
}
switch {
case call == nil:
c.logger.Printf("jsonrpc2: ignoring response #%s with no corresponding request\n", id)
case resp.Error != nil:
call.done <- resp.Error
close(call.done)
default:
call.done <- nil
close(call.done)
}
}
}
}
c.close(err)
}
func (c *Conn) send(_ context.Context, m *anyMessage, wait bool) (cc *call, err error) {
c.sending.Lock()
defer c.sending.Unlock()
// m.request.ID could be changed, so we store a copy to correctly
// clean up pending
var id ID
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return nil, ErrClosed
}
// Assign a default id if not set
if m.request != nil && wait {
cc = &call{request: m.request, seq: c.seq, done: make(chan error, 1)}
isIDUnset := len(m.request.ID.Str) == 0 && m.request.ID.Num == 0
if isIDUnset {
if m.request.ID.IsString {
m.request.ID.Str = strconv.FormatUint(c.seq, 10)
} else {
m.request.ID.Num = c.seq
}
}
c.seq++
}
c.mu.Unlock()
if len(c.onSend) > 0 {
var (
req *Request
resp *Response
)
switch {
case m.request != nil:
req = m.request
case m.response != nil:
resp = m.response
}
for _, onSend := range c.onSend {
onSend(req, resp)
}
}
// Store requests so we can later associate them with incoming
// responses.
if m.request != nil && wait {
c.mu.Lock()
id = m.request.ID
c.pending[id] = cc
c.mu.Unlock()
}
// From here on, if we fail to send this, then we need to remove
// this from the pending map so we don't block on it or pile up
// pending entries for unsent messages.
defer func() {
if err != nil {
if cc != nil {
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
}
}
}()
if err := c.stream.WriteObject(m); err != nil {
return nil, err
}
return cc, nil
}
// Waiter proxies an ongoing JSON-RPC call.
type Waiter struct {
*call
}
// Wait for the result of an ongoing JSON-RPC call. If the response
// is successful, its result is stored in result (a pointer to a
// value that can be JSON-unmarshaled into); otherwise, a non-nil
// error is returned.
func (w Waiter) Wait(ctx context.Context, result interface{}) error {
select {
case err, ok := <-w.call.done:
if !ok {
err = ErrClosed
}
if err != nil {
return err
}
if result != nil {
if w.call.response.Result == nil {
w.call.response.Result = &jsonNull
}
if err := json.Unmarshal(*w.call.response.Result, result); err != nil {
return err
}
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// call represents a JSON-RPC call over its entire lifecycle.
type call struct {
request *Request
response *Response
seq uint64 // the seq of the request
done chan error
}
// anyMessage represents either a JSON Request or Response.
type anyMessage struct {
request *Request
response *Response
}
func (m anyMessage) MarshalJSON() ([]byte, error) {
var v interface{}
switch {
case m.request != nil && m.response == nil:
v = m.request
case m.request == nil && m.response != nil:
v = m.response
}
if v != nil {
return json.Marshal(v)
}
return nil, errors.New("jsonrpc2: message must have exactly one of the request or response fields set")
}
func (m *anyMessage) UnmarshalJSON(data []byte) error {
// The presence of these fields distinguishes between the 2
// message types.
type msg struct {
ID interface{} `json:"id"`
Method *string `json:"method"`
Result anyValueWithExplicitNull `json:"result"`
Error interface{} `json:"error"`
}
var isRequest, isResponse bool
checkType := func(m *msg) error {
mIsRequest := m.Method != nil
mIsResponse := m.Result.null || m.Result.value != nil || m.Error != nil
if (!mIsRequest && !mIsResponse) || (mIsRequest && mIsResponse) {
return errors.New("jsonrpc2: unable to determine message type (request or response)")
}
if (mIsRequest && isResponse) || (mIsResponse && isRequest) {
return errors.New("jsonrpc2: batch message type mismatch (must be all requests or all responses)")
}
isRequest = mIsRequest
isResponse = mIsResponse
return nil
}
if isArray := len(data) > 0 && data[0] == '['; isArray {
var msgs []msg
if err := json.Unmarshal(data, &msgs); err != nil {
return err
}
if len(msgs) == 0 {
return errors.New("jsonrpc2: invalid empty batch")
}
for i := range msgs {
if err := checkType(&msg{
ID: msgs[i].ID,
Method: msgs[i].Method,
Result: msgs[i].Result,
Error: msgs[i].Error,
}); err != nil {
return err
}
}
} else {
var m msg
if err := json.Unmarshal(data, &m); err != nil {
return err
}
if err := checkType(&m); err != nil {
return err
}
}
var v interface{}
switch {
case isRequest && !isResponse:
v = &m.request
case !isRequest && isResponse:
v = &m.response
}
if err := json.Unmarshal(data, v); err != nil {
return err
}
if !isRequest && isResponse && m.response.Error == nil && m.response.Result == nil {
m.response.Result = &jsonNull
}
return nil
}
// anyValueWithExplicitNull is used to distinguish {} from
// {"result":null} by anyMessage's JSON unmarshaler.
type anyValueWithExplicitNull struct {
null bool // JSON "null"
value interface{}
}
func (v anyValueWithExplicitNull) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *anyValueWithExplicitNull) UnmarshalJSON(data []byte) error {
data = bytes.TrimSpace(data)
if string(data) == "null" {
*v = anyValueWithExplicitNull{null: true}
return nil
}
*v = anyValueWithExplicitNull{}
return json.Unmarshal(data, &v.value)
}

View File

@ -1,111 +0,0 @@
package jsonrpc2
import (
"encoding/json"
"sync"
)
// Logger interface implements one method - Printf.
// You can use the stdlib logger *log.Logger
type Logger interface {
Printf(format string, v ...interface{})
}
// ConnOpt is the type of function that can be passed to NewConn to
// customize the Conn before it is created.
type ConnOpt func(*Conn)
// OnRecv causes all requests received on conn to invoke f(req, nil)
// and all responses to invoke f(req, resp),
func OnRecv(f func(*Request, *Response)) ConnOpt {
return func(c *Conn) { c.onRecv = append(c.onRecv, f) }
}
// OnSend causes all requests sent on conn to invoke f(req, nil) and
// all responses to invoke f(nil, resp),
func OnSend(f func(*Request, *Response)) ConnOpt {
return func(c *Conn) { c.onSend = append(c.onSend, f) }
}
// LogMessages causes all messages sent and received on conn to be
// logged using the provided logger.
func LogMessages(logger Logger) ConnOpt {
return func(c *Conn) {
// Remember reqs we have received so we can helpfully show the
// request method in OnSend for responses.
var (
mu sync.Mutex
reqMethods = map[ID]string{}
)
// Set custom logger from provided input
c.logger = logger
OnRecv(func(req *Request, resp *Response) {
switch {
case req != nil:
mu.Lock()
reqMethods[req.ID] = req.Method
mu.Unlock()
params, _ := json.Marshal(req.Params)
if req.Notif {
logger.Printf("jsonrpc2: --> notif: %s: %s\n", req.Method, params)
} else {
logger.Printf("jsonrpc2: --> request #%s: %s: %s\n", req.ID, req.Method, params)
}
case resp != nil:
var method string
if req != nil {
method = req.Method
} else {
method = "(no matching request)"
}
switch {
case resp.Result != nil:
result, _ := json.Marshal(resp.Result)
logger.Printf("jsonrpc2: --> result #%s: %s: %s\n", resp.ID, method, result)
case resp.Error != nil:
err, _ := json.Marshal(resp.Error)
logger.Printf("jsonrpc2: --> error #%s: %s: %s\n", resp.ID, method, err)
}
}
})(c)
OnSend(func(req *Request, resp *Response) {
switch {
case req != nil:
params, _ := json.Marshal(req.Params)
if req.Notif {
logger.Printf("jsonrpc2: <-- notif: %s: %s\n", req.Method, params)
} else {
logger.Printf("jsonrpc2: <-- request #%s: %s: %s\n", req.ID, req.Method, params)
}
case resp != nil:
mu.Lock()
method := reqMethods[resp.ID]
delete(reqMethods, resp.ID)
mu.Unlock()
if method == "" {
method = "(no previous request)"
}
if resp.Result != nil {
result, _ := json.Marshal(resp.Result)
logger.Printf("jsonrpc2: <-- result #%s: %s: %s\n", resp.ID, method, result)
} else {
err, _ := json.Marshal(resp.Error)
logger.Printf("jsonrpc2: <-- error #%s: %s: %s\n", resp.ID, method, err)
}
}
})(c)
}
}
// SetLogger sets the logger for the connection.
func SetLogger(logger Logger) ConnOpt {
return func(c *Conn) {
c.logger = logger
}
}

View File

@ -1,64 +0,0 @@
package jsonrpc2
import (
"context"
)
// HandlerWithError implements Handler by calling the func for each
// request and handling returned errors and results.
func HandlerWithError(handleFunc func(context.Context, *Conn, *Request) (result interface{}, err error)) *HandlerWithErrorConfigurer {
return &HandlerWithErrorConfigurer{handleFunc: handleFunc}
}
// HandlerWithErrorConfigurer is a handler created by HandlerWithError.
type HandlerWithErrorConfigurer struct {
handleFunc func(context.Context, *Conn, *Request) (result interface{}, err error)
suppressErrClosed bool
}
// Handle implements Handler.
func (h *HandlerWithErrorConfigurer) Handle(ctx context.Context, conn *Conn, req *Request) {
result, err := h.handleFunc(ctx, conn, req)
if req.Notif {
if err != nil {
conn.logger.Printf("jsonrpc2 handler: notification %q handling error: %v\n", req.Method, err)
}
return
}
resp := &Response{ID: req.ID}
if err == nil {
err = resp.SetResult(result)
}
if err != nil {
if e, ok := err.(*Error); ok {
resp.Error = e
} else {
resp.Error = &Error{Message: err.Error()}
}
}
if !req.Notif {
if err := conn.SendResponse(ctx, resp); err != nil {
if err != ErrClosed || !h.suppressErrClosed {
conn.logger.Printf("jsonrpc2 handler: sending response %s: %v\n", resp.ID, err)
}
}
}
}
// SuppressErrClosed makes the handler suppress jsonrpc2.ErrClosed errors from
// being logged. The original handler `h` is returned.
//
// This is optional because only in some cases is this behavior desired. For
// example, a handler that serves end-user connections may not want to log
// ErrClosed because it just indicates the end-user connection has gone away
// for any reason (they could have lost wifi connection, are no longer
// interested in the request and closed the connection, etc) and as such it
// would be log spam, whereas a handler that serves internal connections would
// never expect connections to go away unexpectedly (which could indicate
// service degradation, etc) and as such ErrClosed should always be logged.
func (h *HandlerWithErrorConfigurer) SuppressErrClosed() Handler {
h.suppressErrClosed = true
return h
}

View File

@ -1,119 +0,0 @@
// Package jsonrpc2 provides a client and server implementation of
// [JSON-RPC 2.0](http://www.jsonrpc.org/specification).
package jsonrpc2
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
)
// JSONRPC2 describes an interface for issuing requests that speak the
// JSON-RPC 2 protocol. It isn't really necessary for this package
// itself, but is useful for external users that use the interface as
// an API boundary.
type JSONRPC2 interface {
// Call issues a standard request (http://www.jsonrpc.org/specification#request_object).
Call(ctx context.Context, method string, params, result interface{}, opt ...CallOption) error
// Notify issues a notification request (http://www.jsonrpc.org/specification#notification).
Notify(ctx context.Context, method string, params interface{}, opt ...CallOption) error
// Close closes the underlying connection, if it exists.
Close() error
}
// Error represents a JSON-RPC response error.
type Error struct {
Code int64 `json:"code"`
Message string `json:"message"`
Data *json.RawMessage `json:"data,omitempty"`
}
// SetError sets e.Data to the JSON encoding of v. If JSON
// marshaling fails, it panics.
func (e *Error) SetError(v interface{}) {
b, err := json.Marshal(v)
if err != nil {
panic("Error.SetData: " + err.Error())
}
e.Data = (*json.RawMessage)(&b)
}
// Error implements the Go error interface.
func (e *Error) Error() string {
return fmt.Sprintf("jsonrpc2: code %v message: %s", e.Code, e.Message)
}
// Errors defined in the JSON-RPC spec. See
// http://www.jsonrpc.org/specification#error_object.
const (
CodeParseError = -32700
CodeInvalidRequest = -32600
CodeMethodNotFound = -32601
CodeInvalidParams = -32602
CodeInternalError = -32603
)
// Handler handles JSON-RPC requests and notifications.
type Handler interface {
// Handle is called to handle a request. No other requests are handled
// until it returns. If you do not require strict ordering behavior
// of received RPCs, it is suggested to wrap your handler in
// AsyncHandler.
Handle(context.Context, *Conn, *Request)
}
// ID represents a JSON-RPC 2.0 request ID, which may be either a
// string or number (or null, which is unsupported).
type ID struct {
// At most one of Num or Str may be nonzero. If both are zero
// valued, then IsNum specifies which field's value is to be used
// as the ID.
Num uint64
Str string
// IsString controls whether the Num or Str field's value should be
// used as the ID, when both are zero valued. It must always be
// set to true if the request ID is a string.
IsString bool
}
func (id ID) String() string {
if id.IsString {
return strconv.Quote(id.Str)
}
return strconv.FormatUint(id.Num, 10)
}
// MarshalJSON implements json.Marshaler.
func (id ID) MarshalJSON() ([]byte, error) {
if id.IsString {
return json.Marshal(id.Str)
}
return json.Marshal(id.Num)
}
// UnmarshalJSON implements json.Unmarshaler.
func (id *ID) UnmarshalJSON(data []byte) error {
// Support both uint64 and string IDs.
var v uint64
if err := json.Unmarshal(data, &v); err == nil {
*id = ID{Num: v}
return nil
}
var v2 string
if err := json.Unmarshal(data, &v2); err != nil {
return err
}
*id = ID{Str: v2, IsString: true}
return nil
}
// ErrClosed indicates that the JSON-RPC connection is closed (or in
// the process of closing).
var ErrClosed = errors.New("jsonrpc2: connection is closed")
var jsonNull = json.RawMessage("null")

View File

@ -1,174 +0,0 @@
package jsonrpc2
import (
"bytes"
"encoding/json"
"errors"
"fmt"
)
// Request represents a JSON-RPC request or
// notification. See
// http://www.jsonrpc.org/specification#request_object and
// http://www.jsonrpc.org/specification#notification.
type Request struct {
Method string `json:"method"`
Params *json.RawMessage `json:"params,omitempty"`
ID ID `json:"id"`
Notif bool `json:"-"`
// Meta optionally provides metadata to include in the request.
//
// NOTE: It is not part of spec. However, it is useful for propagating
// tracing context, etc.
Meta *json.RawMessage `json:"meta,omitempty"`
// ExtraFields optionally adds fields to the root of the JSON-RPC request.
//
// NOTE: It is not part of the spec, but there are other protocols based on
// JSON-RPC 2 that require it.
ExtraFields []RequestField `json:"-"`
}
// MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0"
// property.
func (r Request) MarshalJSON() ([]byte, error) {
r2 := map[string]interface{}{
"jsonrpc": "2.0",
"method": r.Method,
}
for _, field := range r.ExtraFields {
r2[field.Name] = field.Value
}
if !r.Notif {
r2["id"] = &r.ID
}
if r.Params != nil {
r2["params"] = r.Params
}
if r.Meta != nil {
r2["meta"] = r.Meta
}
return json.Marshal(r2)
}
// UnmarshalJSON implements json.Unmarshaler.
func (r *Request) UnmarshalJSON(data []byte) error {
r2 := make(map[string]interface{})
// Detect if the "params" or "meta" fields are JSON "null" or just not
// present by seeing if the field gets overwritten to nil.
emptyParams := &json.RawMessage{}
r2["params"] = emptyParams
emptyMeta := &json.RawMessage{}
r2["meta"] = emptyMeta
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
if err := decoder.Decode(&r2); err != nil {
return err
}
var ok bool
r.Method, ok = r2["method"].(string)
if !ok {
return errors.New("missing method field")
}
switch {
case r2["params"] == nil:
r.Params = &jsonNull
case r2["params"] == emptyParams:
r.Params = nil
default:
b, err := json.Marshal(r2["params"])
if err != nil {
return fmt.Errorf("failed to marshal params: %w", err)
}
r.Params = (*json.RawMessage)(&b)
}
switch {
case r2["meta"] == nil:
r.Meta = &jsonNull
case r2["meta"] == emptyMeta:
r.Meta = nil
default:
b, err := json.Marshal(r2["meta"])
if err != nil {
return fmt.Errorf("failed to marshal Meta: %w", err)
}
r.Meta = (*json.RawMessage)(&b)
}
switch rawID := r2["id"].(type) {
case nil:
r.ID = ID{}
r.Notif = true
case string:
r.ID = ID{Str: rawID, IsString: true}
r.Notif = false
case json.Number:
id, err := rawID.Int64()
if err != nil {
return fmt.Errorf("failed to unmarshal ID: %w", err)
}
r.ID = ID{Num: uint64(id)}
r.Notif = false
default:
return fmt.Errorf("unexpected ID type: %T", rawID)
}
// Clear the extra fields before populating them again.
r.ExtraFields = nil
for name, value := range r2 {
switch name {
case "id", "jsonrpc", "meta", "method", "params":
continue
}
r.ExtraFields = append(r.ExtraFields, RequestField{
Name: name,
Value: value,
})
}
return nil
}
// SetParams sets r.Params to the JSON encoding of v. If JSON
// marshaling fails, it returns an error.
func (r *Request) SetParams(v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
r.Params = (*json.RawMessage)(&b)
return nil
}
// SetMeta sets r.Meta to the JSON encoding of v. If JSON
// marshaling fails, it returns an error.
func (r *Request) SetMeta(v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
r.Meta = (*json.RawMessage)(&b)
return nil
}
// SetExtraField adds an entry to r.ExtraFields, so that it is added to the
// JSON encoding of the request, as a way to add arbitrary extensions to
// JSON RPC 2.0. If JSON marshaling fails, it returns an error.
func (r *Request) SetExtraField(name string, v interface{}) error {
switch name {
case "id", "jsonrpc", "meta", "method", "params":
return fmt.Errorf("invalid extra field %q", name)
}
r.ExtraFields = append(r.ExtraFields, RequestField{
Name: name,
Value: v,
})
return nil
}
// RequestField is a top-level field that can be added to the JSON-RPC request.
type RequestField struct {
Name string
Value interface{}
}

View File

@ -1,72 +0,0 @@
package jsonrpc2
import (
"encoding/json"
"errors"
)
// Response represents a JSON-RPC response. See
// http://www.jsonrpc.org/specification#response_object.
type Response struct {
ID ID `json:"id"`
Result *json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
// Meta optionally provides metadata to include in the response.
//
// NOTE: It is not part of spec. However, it is useful for propagating
// tracing context, etc.
Meta *json.RawMessage `json:"meta,omitempty"`
// SPEC NOTE: The spec says "If there was an error in detecting
// the id in the Request object (e.g. Parse error/Invalid
// Request), it MUST be Null." If we made the ID field nullable,
// then we'd have to make it a pointer type. For simplicity, we're
// ignoring the case where there was an error in detecting the ID
// in the Request object.
}
// MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0"
// property.
func (r Response) MarshalJSON() ([]byte, error) {
if (r.Result == nil || len(*r.Result) == 0) && r.Error == nil {
return nil, errors.New("can't marshal *jsonrpc2.Response (must have result or error)")
}
type tmpType Response // avoid infinite MarshalJSON recursion
b, err := json.Marshal(tmpType(r))
if err != nil {
return nil, err
}
b = append(b[:len(b)-1], []byte(`,"jsonrpc":"2.0"}`)...)
return b, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (r *Response) UnmarshalJSON(data []byte) error {
type tmpType Response
// Detect if the "result" field is JSON "null" or just not present
// by seeing if the field gets overwritten to nil.
*r = Response{Result: &json.RawMessage{}}
if err := json.Unmarshal(data, (*tmpType)(r)); err != nil {
return err
}
if r.Result == nil { // JSON "null"
r.Result = &jsonNull
} else if len(*r.Result) == 0 {
r.Result = nil
}
return nil
}
// SetResult sets r.Result to the JSON representation of v. If JSON
// marshaling fails, it returns an error.
func (r *Response) SetResult(v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
r.Result = (*json.RawMessage)(&b)
return nil
}

View File

@ -1,226 +0,0 @@
package jsonrpc2
import (
"bufio"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"sync"
)
// An ObjectStream is a bidirectional stream of JSON-RPC 2.0 objects.
type ObjectStream interface {
// WriteObject writes a JSON-RPC 2.0 object to the stream.
WriteObject(obj interface{}) error
// ReadObject reads the next JSON-RPC 2.0 object from the stream
// and stores it in the value pointed to by v.
ReadObject(v interface{}) error
io.Closer
}
// A bufferedObjectStream is an ObjectStream that uses a buffered
// io.ReadWriteCloser to send and receive objects.
type bufferedObjectStream struct {
conn io.Closer // all writes should go through w, all reads through r
w *bufio.Writer
r *bufio.Reader
codec ObjectCodec
mu sync.Mutex
}
// NewBufferedStream creates a buffered stream from a network
// connection (or other similar interface). The underlying
// objectStream is used to produce the bytes to write to the stream
// for the JSON-RPC 2.0 objects.
func NewBufferedStream(conn io.ReadWriteCloser, codec ObjectCodec) ObjectStream {
switch v := codec.(type) {
case PlainObjectCodec:
v.decoder = json.NewDecoder(conn)
v.encoder = json.NewEncoder(conn)
codec = v
}
return &bufferedObjectStream{
conn: conn,
w: bufio.NewWriter(conn),
r: bufio.NewReader(conn),
codec: codec,
}
}
// WriteObject implements ObjectStream.
func (t *bufferedObjectStream) WriteObject(obj interface{}) error {
t.mu.Lock()
defer t.mu.Unlock()
if err := t.codec.WriteObject(t.w, obj); err != nil {
return err
}
return t.w.Flush()
}
// ReadObject implements ObjectStream.
func (t *bufferedObjectStream) ReadObject(v interface{}) error {
return t.codec.ReadObject(t.r, v)
}
// Close implements ObjectStream.
func (t *bufferedObjectStream) Close() error {
return t.conn.Close()
}
// An ObjectCodec specifies how to encode and decode a JSON-RPC 2.0
// object in a stream.
type ObjectCodec interface {
// WriteObject writes a JSON-RPC 2.0 object to the stream.
WriteObject(stream io.Writer, obj interface{}) error
// ReadObject reads the next JSON-RPC 2.0 object from the stream
// and stores it in the value pointed to by v.
ReadObject(stream *bufio.Reader, v interface{}) error
}
// VarintObjectCodec reads/writes JSON-RPC 2.0 objects with a varint
// header that encodes the byte length.
type VarintObjectCodec struct{}
// WriteObject implements ObjectCodec.
func (VarintObjectCodec) WriteObject(stream io.Writer, obj interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
var buf [binary.MaxVarintLen64]byte
b := binary.PutUvarint(buf[:], uint64(len(data)))
if _, err := stream.Write(buf[:b]); err != nil {
return err
}
if _, err := stream.Write(data); err != nil {
return err
}
return nil
}
// ReadObject implements ObjectCodec.
func (VarintObjectCodec) ReadObject(stream *bufio.Reader, v interface{}) error {
b, err := binary.ReadUvarint(stream)
if err != nil {
return err
}
return json.NewDecoder(io.LimitReader(stream, int64(b))).Decode(v)
}
// VSCodeObjectCodec reads/writes JSON-RPC 2.0 objects with
// Content-Length and Content-Type headers, as specified by
// https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#base-protocol.
type VSCodeObjectCodec struct{}
// WriteObject implements ObjectCodec.
func (VSCodeObjectCodec) WriteObject(stream io.Writer, obj interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
if _, err := fmt.Fprintf(stream, "Content-Length: %d\r\n\r\n", len(data)); err != nil {
return err
}
if _, err := stream.Write(data); err != nil {
return err
}
return nil
}
// ReadObject implements ObjectCodec.
func (VSCodeObjectCodec) ReadObject(stream *bufio.Reader, v interface{}) error {
var contentLength uint64
for {
line, err := stream.ReadString('\r')
if err != nil {
return err
}
b, err := stream.ReadByte()
if err != nil {
return err
}
if b != '\n' {
return fmt.Errorf(`jsonrpc2: line endings must be \r\n`)
}
if line == "\r" {
break
}
if strings.HasPrefix(line, "Content-Length: ") {
line = strings.TrimPrefix(line, "Content-Length: ")
line = strings.TrimSpace(line)
var err error
contentLength, err = strconv.ParseUint(line, 10, 32)
if err != nil {
return err
}
}
}
if contentLength == 0 {
return fmt.Errorf("jsonrpc2: no Content-Length header found")
}
return json.NewDecoder(io.LimitReader(stream, int64(contentLength))).Decode(v)
}
// PlainObjectCodec reads/writes plain JSON-RPC 2.0 objects without a header.
//
// Deprecated: use NewPlainObjectStream
type PlainObjectCodec struct {
decoder *json.Decoder
encoder *json.Encoder
}
// WriteObject implements ObjectCodec.
func (c PlainObjectCodec) WriteObject(stream io.Writer, v interface{}) error {
if c.encoder != nil {
return c.encoder.Encode(v)
}
return json.NewEncoder(stream).Encode(v)
}
// ReadObject implements ObjectCodec.
func (c PlainObjectCodec) ReadObject(stream *bufio.Reader, v interface{}) error {
if c.decoder != nil {
return c.decoder.Decode(v)
}
return json.NewDecoder(stream).Decode(v)
}
// plainObjectStream reads/writes plain JSON-RPC 2.0 objects without a header.
type plainObjectStream struct {
conn io.Closer
decoder *json.Decoder
encoder *json.Encoder
}
// NewPlainObjectStream creates a buffered stream from a network
// connection (or other similar interface). The underlying
// objectStream produces plain JSON-RPC 2.0 objects without a header.
func NewPlainObjectStream(conn io.ReadWriteCloser) ObjectStream {
return &plainObjectStream{
conn: conn,
encoder: json.NewEncoder(conn),
decoder: json.NewDecoder(conn),
}
}
func (os *plainObjectStream) ReadObject(v interface{}) error {
return os.decoder.Decode(v)
}
// WriteObject serializes a value to JSON and writes it to a stream.
// Not thread-safe, a user must synchronize writes in a multithreaded environment.
func (os *plainObjectStream) WriteObject(v interface{}) error {
return os.encoder.Encode(v)
}
func (os *plainObjectStream) Close() error {
return os.conn.Close()
}

View File

@ -1,56 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appast
import (
"fmt"
"os"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/ast"
"wa-lang.org/wa/internal/parser"
"wa-lang.org/wa/internal/token"
)
var CmdAst = &cli.Command{
Hidden: true,
Name: "ast",
Usage: "parse Wa source code and print ast",
Action: CmdAstAction,
}
func CmdAstAction(c *cli.Context) error {
if c.NArg() == 0 {
fmt.Fprintf(os.Stderr, "no input file")
os.Exit(1)
}
err := PrintAST(c.Args().First())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
}
func PrintAST(filename string) error {
if !appbase.HasExt(filename, ".wa", ".wz") {
return fmt.Errorf("%q is not Wa file", filename)
}
if !appbase.PathExists(filename) {
return fmt.Errorf("%q not found", filename)
}
if !appbase.IsNativeFile(filename) {
return fmt.Errorf("%q must be file", filename)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(nil, fset, filename, nil, 0)
if err != nil {
return err
}
return ast.Print(fset, f)
}

View File

@ -1,50 +0,0 @@
package appbase
import (
"fmt"
"strings"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/config"
)
// 输出路径
func MakeFlag_output() *cli.StringFlag {
return &cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "set output file",
Value: "",
}
}
// 构建的目标
func MakeFlag_target() *cli.StringFlag {
return &cli.StringFlag{
Name: "target",
Usage: fmt.Sprintf("set target os (%s)", strings.Join(config.WaOS_List, "|")),
Value: config.WaOS_Default,
}
}
// 构建的 Tags
func MakeFlag_tags() *cli.StringFlag {
return &cli.StringFlag{
Name: "tags",
Usage: "set build tags",
}
}
func MakeFlag_ld_stack_size() *cli.IntFlag {
return &cli.IntFlag{
Name: "ld-stack-size",
Usage: "set stack size",
}
}
func MakeFlag_ld_max_memory() *cli.IntFlag {
return &cli.IntFlag{
Name: "ld-max-memory",
Usage: "set max memory size",
}
}

View File

@ -1,146 +0,0 @@
// 版权 @2019 凹语言 作者。保留所有权利。
package appbase
import (
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/config"
)
// 命令行选项
type Option struct {
Debug bool
WaBackend string
BuilgTags []string
TargetArch string
TargetOS string
Clang string
Llc string
LD_StackSize int
LD_MaxMemory int
}
func (opt *Option) Config() *config.Config {
cfg := config.DefaultConfig()
if opt.Debug {
cfg.Debug = true
}
if opt.WaBackend != "" {
cfg.WaBackend = opt.WaBackend
}
if len(opt.BuilgTags) > 0 {
cfg.BuilgTags = append(cfg.BuilgTags, opt.BuilgTags...)
}
if opt.TargetArch != "" {
cfg.WaArch = opt.TargetArch
}
if opt.TargetOS != "" {
cfg.WaOS = opt.TargetOS
}
if opt.LD_StackSize != 0 {
cfg.LDFlags.StackSize = opt.LD_StackSize
}
if opt.LD_MaxMemory != 0 {
cfg.LDFlags.MaxMemory = opt.LD_MaxMemory
}
switch cfg.WaArch {
case "wasm":
cfg.WaSizes.MaxAlign = 8
cfg.WaSizes.WordSize = 4
case "wasm64":
cfg.WaSizes.MaxAlign = 8
cfg.WaSizes.WordSize = 8
case "amd64":
cfg.WaSizes.MaxAlign = 8
cfg.WaSizes.WordSize = 8
case "arm64":
cfg.WaSizes.MaxAlign = 8
cfg.WaSizes.WordSize = 8
case "native":
cfg.WaSizes.MaxAlign = 8
cfg.WaSizes.WordSize = 8
default:
panic("todo")
}
return cfg
}
// 构建命令行程序对象
func (opt *Option) Adjust() {
if opt.Clang == "" {
if runtime.GOOS == "windows" {
opt.Clang, _ = exec.LookPath("clang.exe")
} else {
opt.Clang, _ = exec.LookPath("clang")
}
if opt.Clang == "" {
opt.Clang = "clang"
}
}
if opt.Llc == "" {
if runtime.GOOS == "windows" {
opt.Llc, _ = exec.LookPath("llc.exe")
} else {
opt.Llc, _ = exec.LookPath("llc")
}
if opt.Llc == "" {
opt.Llc = "llc"
}
}
if opt.TargetOS == "" {
opt.TargetOS = config.WaOS_Default
}
if opt.TargetArch == "" {
opt.TargetArch = config.WaArch_Default
}
}
func BuildOptions(c *cli.Context, waBackend ...string) *Option {
opt := &Option{
Debug: c.Bool("debug"),
WaBackend: config.WaBackend_Default,
BuilgTags: strings.Fields(c.String("tags")),
Clang: c.String("clang"),
Llc: c.String("llc"),
LD_StackSize: c.Int("ld-stack-size"),
LD_MaxMemory: c.Int("ld-max-memory"),
}
opt.TargetArch = "wasm"
if len(waBackend) > 0 {
opt.WaBackend = waBackend[0]
}
if target := c.String("target"); !config.CheckWaOS(target) {
fmt.Printf("unknown target: %s\n", c.String("target"))
os.Exit(1)
}
switch c.String("target") {
case "", "wa", "walang":
opt.TargetOS = config.WaOS_Default
case config.WaOS_wasi:
opt.TargetOS = config.WaOS_wasi
case config.WaOS_arduino:
opt.TargetOS = config.WaOS_arduino
case config.WaOS_chrome:
opt.TargetOS = config.WaOS_chrome
case config.WaOS_mvp:
opt.TargetOS = config.WaOS_mvp
default:
fmt.Printf("unreachable: target: %s\n", c.String("target"))
os.Exit(1)
}
opt.Adjust()
return opt
}

View File

@ -1,98 +0,0 @@
// 版权 @2019 凹语言 作者。保留所有权利。
package appbase
import (
"os"
"strings"
"unicode"
)
// 路径名是否包含后缀, 忽略大小写区别
func HasExt(path string, exts ...string) bool {
if path == "" {
return false
}
if len(exts) == 0 {
return true
}
for _, ext := range exts {
if len(path) <= len(ext) {
continue
}
if strings.EqualFold(ext, path[len(path)-len(ext):]) {
return true
}
}
return false
}
// 本地路径存在
func PathExists(path string) bool {
_, err := os.Lstat(path)
return err == nil
}
// 是否为本地存在的文件, 并满足后缀名
func IsNativeFile(path string, exts ...string) bool {
if !HasExt(path, exts...) {
return false
}
fi, err := os.Lstat(path)
if err != nil {
return false
}
return !fi.IsDir()
}
// 是否为本地存在的目录
func IsNativeDir(path string) bool {
fi, err := os.Lstat(path)
if err != nil {
return false
}
return fi.IsDir()
}
// 替换后缀名
func ReplaceExt(path string, extOld, extNew string) string {
return path[:len(path)-len(extOld)] + extNew
}
// 为合法的 app 名字
func IsValidAppName(s string) bool {
if s == "" || s[0] == '_' || (s[0] >= '0' && s[0] <= '9') {
return false
}
for _, c := range []rune(s) {
if c == '_' || (c >= '0' && c <= '9') || unicode.IsLetter(c) {
continue
}
return false
}
return true
}
// 为合法的包路径
func IsValidPkgpath(s string) bool {
if s == "" || s[0] == '_' || (s[0] >= '0' && s[0] <= '9') {
return false
}
for _, c := range []rune(s) {
if c == '_' || c == '.' || c == '/' || (c >= '0' && c <= '9') {
continue
}
if unicode.IsLetter(c) {
continue
}
return false
}
var pkgname = s
if i := strings.LastIndex(s, "/"); i >= 0 {
pkgname = s[i+1:]
}
return IsValidAppName(pkgname)
}
// 是标准库路径

View File

@ -1,32 +0,0 @@
// 版权 @2019 凹语言 作者。保留所有权利。
package appbase
import "testing"
func TestHasExt(t *testing.T) {
var tests = []struct {
path string
exts []string
ok bool
}{
{"", nil, false},
{"a", nil, true},
{"a.wa", []string{".wa"}, true},
{"a.wa", []string{".WA"}, true},
{"a.Wa", []string{".wa"}, true},
{"a.wa", []string{".wa", ".wz"}, true},
{".wa", []string{".wa"}, false},
{".wa", []string{}, true},
}
for i, tt := range tests {
expect := tt.ok
got := HasExt(tt.path, tt.exts...)
if expect != got {
t.Fatalf("%d: expect = %v, got = %v; // %v", i, expect, got, tt)
}
}
}

View File

@ -1,208 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appbuild
import (
"fmt"
"os"
"path/filepath"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/backends/compiler_wat"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/loader"
"wa-lang.org/wa/internal/wabt"
)
var CmdBuild = &cli.Command{
Name: "build",
Usage: "compile Wa source code",
Flags: []cli.Flag{
appbase.MakeFlag_output(),
appbase.MakeFlag_target(),
appbase.MakeFlag_tags(),
appbase.MakeFlag_ld_stack_size(),
appbase.MakeFlag_ld_max_memory(),
},
Action: CmdBuildAction,
}
func CmdBuildAction(c *cli.Context) error {
input := c.Args().First()
outfile := ""
if input == "" {
input, _ = os.Getwd()
}
var opt = appbase.BuildOptions(c)
_, err := BuildApp(opt, input, outfile)
if err != nil {
return err
}
return err
}
func BuildApp(opt *appbase.Option, input, outfile string) (wasmBytes []byte, err error) {
// 路径是否存在
if !appbase.PathExists(input) {
fmt.Printf("%q not found\n", input)
os.Exit(1)
}
// 输出参数是否合法, 必须是 wasm
if outfile != "" && !appbase.HasExt(outfile, ".wasm") {
fmt.Printf("%q is not valid output path\n", outfile)
os.Exit(1)
}
// 已经是 wasm, 直接返回
if appbase.HasExt(input, ".wasm") {
return os.ReadFile(input)
}
// 只编译 wat 文件, 输出路径相同, 后缀名调整
if appbase.HasExt(input, ".wat") {
// 设置默认输出目标
if outfile == "" {
outfile = appbase.ReplaceExt(input, ".wat", ".wasm")
}
watData, err := os.ReadFile(input)
if err != nil {
fmt.Printf("read %s failed: %v\n", input, err)
os.Exit(1)
}
wasmBytes, err := wabt.Wat2Wasm(watData)
if err != nil {
fmt.Printf("wat2wasm %s failed: %v\n", input, err)
os.Exit(1)
}
// 写到文件
err = os.WriteFile(outfile, wasmBytes, 0666)
if err != nil {
fmt.Printf("write %s failed: %v\n", outfile, err)
os.Exit(1)
}
// OK
return wasmBytes, nil
}
// 只编译 wa/wz 文件, 输出路径相同, 后缀名调整
if appbase.HasExt(input, ".wa", ".wz") {
_, watOutput, err := buildWat(opt, input)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// 设置默认输出目标
if outfile == "" {
outfile = appbase.ReplaceExt(input, ".wa", ".wasm")
}
// wat 写到文件
watOutfile := appbase.ReplaceExt(outfile, ".wasm", ".wat")
err = os.WriteFile(watOutfile, watOutput, 0666)
if err != nil {
fmt.Printf("write %s failed: %v\n", outfile, err)
os.Exit(1)
}
// wat 编译为 wasm
wasmBytes, err := wabt.Wat2Wasm(watOutput)
if err != nil {
fmt.Printf("wat2wasm %s failed: %v\n", input, err)
os.Exit(1)
}
// wasm 写到文件
err = os.WriteFile(outfile, wasmBytes, 0666)
if err != nil {
fmt.Printf("write %s failed: %v\n", outfile, err)
os.Exit(1)
}
// OK
return wasmBytes, nil
}
// 构建目录
{
if !appbase.IsNativeDir(input) {
fmt.Printf("%q is not valid output path\n", outfile)
os.Exit(1)
}
// 尝试读取模块信息
manifest, err := config.LoadManifest(nil, input)
if err != nil {
fmt.Printf("%q is invalid wa moudle\n", input)
os.Exit(1)
}
if err := manifest.Valid(); err != nil {
fmt.Printf("%q is invalid wa module; %v\n", input, err)
os.Exit(1)
}
if outfile == "" {
if !manifest.IsStd {
outfile = filepath.Join(manifest.Root, "output", manifest.Pkg.Name) + ".wasm"
os.MkdirAll(filepath.Join(manifest.Root, "output"), 0777)
} else {
outfile = "a.out." + manifest.Pkg.Name + ".wasm"
}
}
// 编译出 wat 文件
_, watOutput, err := buildWat(opt, input)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// wat 写到文件
watOutfile := appbase.ReplaceExt(outfile, ".wasm", ".wat")
err = os.WriteFile(watOutfile, watOutput, 0666)
if err != nil {
fmt.Printf("write %s failed: %v\n", outfile, err)
os.Exit(1)
}
// wat 编译为 wasm
wasmBytes, err := wabt.Wat2Wasm(watOutput)
if err != nil {
fmt.Printf("wat2wasm %s failed: %v\n", input, err)
os.Exit(1)
}
// wasm 写到文件
err = os.WriteFile(outfile, wasmBytes, 0666)
if err != nil {
fmt.Printf("write %s failed: %v\n", outfile, err)
os.Exit(1)
}
// OK
return wasmBytes, nil
}
}
func buildWat(opt *appbase.Option, filename string) (*loader.Program, []byte, error) {
cfg := opt.Config()
prog, err := loader.LoadProgram(cfg, filename)
if err != nil {
return prog, nil, err
}
output, err := compiler_wat.New().Compile(prog, "main")
if err != nil {
return prog, nil, err
}
return prog, []byte(output), nil
}

View File

@ -1,52 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appcir
import (
"fmt"
"os"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/backends/compiler_c"
"wa-lang.org/wa/internal/loader"
)
var CmdCir = &cli.Command{
Hidden: true,
Name: "cir",
Usage: "print cir code",
Flags: []cli.Flag{
appbase.MakeFlag_output(),
appbase.MakeFlag_target(),
appbase.MakeFlag_tags(),
},
Action: func(c *cli.Context) error {
if c.NArg() == 0 {
fmt.Fprintf(os.Stderr, "no input file")
os.Exit(1)
}
opt := appbase.BuildOptions(c)
err := PrintCIR(opt, c.Args().First())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func PrintCIR(opt *appbase.Option, filename string) error {
cfg := opt.Config()
prog, err := loader.LoadProgram(cfg, filename)
if err != nil {
return err
}
var c compiler_c.CompilerC
c.CompilePackage(prog.SSAMainPkg)
fmt.Println(c.String())
return nil
}

View File

@ -1,113 +0,0 @@
package appdev
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"wa-lang.org/wa/api"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/config"
)
var CmdDev = &cli.Command{
Hidden: true,
Name: "debug",
Usage: "only for dev/debug",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "hello",
},
&cli.BoolFlag{
Name: "count-code-lines",
},
},
Action: func(c *cli.Context) error {
if c.Bool("count-code-lines") {
RunCountCodeLines()
os.Exit(0)
}
if c.Bool("hello") {
wat, err := api.BuildFile(
config.DefaultConfig(),
"hello.wa", "func main() { println(123) }",
)
if err != nil {
if len(wat) != 0 {
fmt.Println(string(wat))
}
fmt.Println(err)
os.Exit(1)
}
fmt.Println(string(wat))
os.Exit(0)
}
fmt.Println("...dev...")
return nil
},
}
func RunCountCodeLines() {
var dir = "."
if len(os.Args) > 1 {
dir = os.Args[1]
}
total := 0
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatal("filepath.Walk: ", err)
return err
}
if info.IsDir() {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("ioutil.ReadFile: ", err)
}
if needSkip(path, data) {
return nil
}
n := countLine(data)
fmt.Println(path, n)
total += n
return nil
})
fmt.Printf("total %d\n", total)
}
func needSkip(path string, data []byte) bool {
if !hasExt(path, ".wa", ".go", ".ws") {
return true
}
if strings.Contains(path, "3rdparty") {
return true
}
if bytes.Contains(data, []byte("The Go Authors")) {
return true
}
return false
}
func countLine(data []byte) int {
return bytes.Count(data, []byte("\n"))
}
func hasExt(name string, extensions ...string) bool {
for _, ext := range extensions {
if strings.HasSuffix(name, ext) {
return true
}
}
return false
}

View File

@ -1,49 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appdoc
import (
"fmt"
"os"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/loader"
)
var CmdDoc = &cli.Command{
Hidden: true,
Name: "doc",
Usage: "show documentation for package or symbol",
ArgsUsage: "name...",
Flags: []cli.Flag{
appbase.MakeFlag_target(),
appbase.MakeFlag_tags(),
},
Action: func(c *cli.Context) error {
opt := appbase.BuildOptions(c)
var pkgpath = "."
var names []string
if c.Args().Len() > 0 {
pkgpath = c.Args().First()
}
if c.Args().Len() > 1 {
names = c.Args().Slice()[1:]
}
RunDoc(opt.Config(), pkgpath, names...)
return nil
},
}
func RunDoc(cfg *config.Config, pkgpath string, names ...string) {
prog, err := loader.LoadProgram(cfg, pkgpath)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
doc := BuildPkgDoc(prog)
doc.Show(names...)
}

View File

@ -1,71 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appdoc
import (
"fmt"
"log"
"wa-lang.org/wa/internal/loader"
"wa-lang.org/wa/internal/types"
)
type PkgDoc struct {
Prog *loader.Program
Consts []*types.Const
Types []*types.TypeName
Globals []*types.Var
Funcs []*types.Func
}
func BuildPkgDoc(prog *loader.Program) (p *PkgDoc) {
p = &PkgDoc{Prog: prog}
p.buildDoc()
return p
}
func (p *PkgDoc) Show(names ...string) {
if len(names) != 0 {
fmt.Println("TODO:", names)
return
}
for _, c := range p.Consts {
// typ := c.Type().(*types.Basic)
fmt.Printf("const %s %v\n", c.Name(), c.Type())
}
for _, c := range p.Globals {
fmt.Printf("global %s %v\n", c.Name(), c.Type())
}
for _, fn := range p.Funcs {
sig := fn.Type().(*types.Signature)
if sig.Results().Len() > 0 {
fmt.Printf("func %s%v => %v\n", fn.Name(), sig.Params(), sig.Results())
} else {
fmt.Printf("func %s%v\n", fn.Name(), sig.Params())
}
}
}
func (p *PkgDoc) buildDoc() {
mainPkg := p.Prog.Pkgs[p.Prog.Manifest.MainPkg]
scope := mainPkg.Pkg.Scope()
for _, s := range scope.Names() {
if obj := scope.Lookup(s); obj.Exported() {
switch x := obj.(type) {
case *types.Const:
p.Consts = append(p.Consts, x)
case *types.TypeName:
p.Types = append(p.Types, x)
case *types.Var:
p.Globals = append(p.Globals, x)
case *types.Func:
p.Funcs = append(p.Funcs, x)
default:
log.Fatalf("unknown %[1]T %[1]v\n", obj)
}
}
}
}

View File

@ -1,138 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appfmt
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/format"
)
var CmdFmt = &cli.Command{
Name: "fmt",
Usage: "format Wa source code file",
ArgsUsage: "[<file.wa>|<path>|<path>/...]",
Action: func(c *cli.Context) error {
for _, path := range c.Args().Slice() {
if err := Fmt(path); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
return nil
},
}
func Fmt(path string) error {
if appbase.IsNativeFile(path, ".wa", ".wz") {
_, err := fmtFile(path)
return err
}
if path == "" {
if _, err := os.Lstat(config.WaModFile); err == nil {
path = "./..."
} else if _, err := os.Lstat(config.WaModFile + ".json"); err == nil {
path = "./..."
} else {
path = "."
}
}
if !filepath.IsAbs(path) && !strings.HasPrefix(path, ".") {
return fmt.Errorf("%q is not valid path", path)
}
var waFileList []string
switch {
case strings.HasSuffix(path, ".wa"):
waFileList = append(waFileList, path)
case strings.HasSuffix(path, ".wz"):
waFileList = append(waFileList, path)
case strings.HasSuffix(path, "/..."):
waFileList = getDirWaFileList(
strings.TrimSuffix(path, "..."),
true, ".wa", ".wz", // 包含子目录
)
default:
// 不包含子目录
waFileList = getDirWaFileList(
path, false, ".wa", ".wz",
)
}
var changedFileList []string
for _, s := range waFileList {
changed, err := fmtFile(s)
if err != nil {
return fmt.Errorf("%s: %w", s, err)
}
if changed {
changedFileList = append(changedFileList, s)
}
}
for _, s := range changedFileList {
fmt.Println(s)
}
return nil
}
func fmtFile(path string) (changed bool, err error) {
code, changed, err := format.File(nil, path, nil)
if err != nil {
return false, err
}
if changed {
if err = os.WriteFile(path, code, 0666); err != nil {
return false, err
}
}
return changed, nil
}
func getDirWaFileList(dir string, walkSubDir bool, extList ...string) []string {
var waFileList []string
if !walkSubDir {
files, err := os.ReadDir(".")
if err != nil {
return nil
}
for _, file := range files {
if file.IsDir() {
continue
}
for _, ext := range extList {
if strings.HasSuffix(file.Name(), ext) {
waFileList = append(waFileList, filepath.Join(dir, file.Name()))
}
}
}
sort.Strings(waFileList)
return waFileList
}
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
for _, ext := range extList {
if strings.HasSuffix(path, ext) {
waFileList = append(waFileList, path)
return nil
}
}
return nil
})
sort.Strings(waFileList)
return waFileList
}

View File

@ -1,158 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package appinit
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"text/template"
"time"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/waroot"
)
var CmdInit = &cli.Command{
Name: "init",
Usage: "init a sketch Wa module",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "set app name",
Value: "hello",
},
&cli.StringFlag{
Name: "pkgpath",
Aliases: []string{"p"},
Usage: "set pkgpath file",
Value: "myapp",
},
&cli.BoolFlag{
Name: "update",
Aliases: []string{"u"},
Usage: "update example",
},
},
Action: func(c *cli.Context) error {
err := InitApp(c.String("name"), c.String("pkgpath"), c.Bool("update"))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func InitApp(name, pkgpath string, update bool) error {
if name == "" {
return fmt.Errorf("init failed: <%s> is empty", name)
}
if !appbase.IsValidAppName(name) {
return fmt.Errorf("init failed: <%s> is invalid name", name)
}
if !appbase.IsValidPkgpath(pkgpath) {
return fmt.Errorf("init failed: <%s> is invalid pkgpath", pkgpath)
}
if !update {
if _, err := os.Lstat(name); err == nil {
return fmt.Errorf("init failed: <%s> exists", name)
}
}
var info = struct {
Name string
Pkgpath string
Year int
}{
Name: name,
Pkgpath: pkgpath,
Year: time.Now().Year(),
}
appFS := waroot.GetExampleAppFS()
err := fs.WalkDir(appFS, ".", func(path string, d fs.DirEntry, err error) error {
if d == nil || d.IsDir() {
return nil
}
if err != nil {
return err
}
data, err := fs.ReadFile(appFS, path)
if err != nil {
return err
}
tmpl, err := template.New(path).Parse(string(data))
if err != nil {
return err
}
dstpath := filepath.Join(name, path)
os.MkdirAll(filepath.Dir(dstpath), 0777)
f, err := os.Create(dstpath)
if err != nil {
return err
}
defer f.Close()
err = tmpl.Execute(f, &info)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
vendorFS := waroot.GetExampleVendorFS()
err = fs.WalkDir(vendorFS, ".", func(path string, d fs.DirEntry, err error) error {
if d == nil || d.IsDir() {
return nil
}
if err != nil {
return err
}
data, err := fs.ReadFile(vendorFS, path)
if err != nil {
return err
}
tmpl, err := template.New(path).Parse(string(data))
if err != nil {
return err
}
dstpath := filepath.Join(name, "vendor", path)
os.MkdirAll(filepath.Dir(dstpath), 0777)
f, err := os.Create(dstpath)
if err != nil {
return err
}
defer f.Close()
err = tmpl.Execute(f, &info)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
}

View File

@ -1,58 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package applex
import (
"fmt"
"os"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/scanner"
"wa-lang.org/wa/internal/token"
)
var CmdLex = &cli.Command{
Hidden: true,
Name: "lex",
Usage: "lex Wa source code and print token list",
Action: func(c *cli.Context) error {
if c.NArg() == 0 {
fmt.Fprintf(os.Stderr, "no input file")
os.Exit(1)
}
err := Lex(c.Args().First())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func Lex(filename string) error {
if !appbase.IsNativeFile(filename, ".wa", ".wz") {
return fmt.Errorf("%q is not valid path", filename)
}
src, err := os.ReadFile(filename)
if err != nil {
return err
}
var s scanner.Scanner
fset := token.NewFileSet()
file := fset.AddFile(filename, fset.Base(), len(src))
s.Init(file, src, nil, scanner.ScanComments)
for {
pos, tok, lit := s.Scan()
if tok == token.EOF {
break
}
fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit)
}
return nil
}

View File

@ -1,178 +0,0 @@
// 版权 @2019 凹语言 作者。保留所有权利。
package appllvm
import (
"fmt"
"os"
"os/exec"
"path"
"strings"
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/app/appbase"
"wa-lang.org/wa/internal/backends/compiler_llvm"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/loader"
)
var CmdNative = &cli.Command{
Hidden: true,
Name: "native",
Usage: "compile Wa source code to native executable",
Flags: []cli.Flag{
appbase.MakeFlag_output(),
appbase.MakeFlag_target(),
appbase.MakeFlag_tags(),
&cli.BoolFlag{
Name: "debug",
Usage: "dump orginal intermediate representation",
},
&cli.StringFlag{
Name: "clang",
Usage: "set llvm/clang path",
},
&cli.StringFlag{
Name: "llc",
Usage: "set llvm/llc path",
},
},
Action: func(c *cli.Context) error {
outfile := c.String("output")
target := c.String("target")
debug := c.Bool("debug")
infile := ""
if c.NArg() == 0 {
fmt.Fprintf(os.Stderr, "no input file")
os.Exit(1)
}
infile = c.Args().First()
opt := appbase.BuildOptions(c, config.WaBackend_llvm)
if err := LLVMRun(opt, infile, outfile, target, debug); err != nil {
fmt.Println(err)
os.Exit(1)
}
return nil
},
}
func LLVMRun(opt *appbase.Option, infile string, outfile string, target string, debug bool) error {
cfg := opt.Config()
instat, err := os.Stat(infile)
if err != nil {
return err
}
// Calculate the outfile path if not given.
if len(outfile) == 0 {
if instat.IsDir() {
dir := path.Base(infile)
outfile = infile + dir + ".exe"
} else {
ext := path.Ext(infile)
if len(ext) == 0 {
outfile = infile + ".exe"
} else {
pos := strings.Index(infile, ext)
outfile = infile[0:pos] + ".exe"
}
}
}
// Calculate the outfile LLVM-IR file path and the output assembly file path.
llfile, asmfile := "", ""
ext := path.Ext(outfile)
if len(ext) == 0 {
llfile = outfile + ".ll"
asmfile = outfile + ".s"
} else {
pos := strings.Index(outfile, ext)
llfile = outfile[0:pos] + ".ll"
asmfile = outfile[0:pos] + ".s"
}
// Do the real compile work.
prog, err := loader.LoadProgram(cfg, infile)
if err != nil {
return err
}
output, err := compiler_llvm.New(target, debug).Compile(prog)
if err != nil {
return err
}
// Write the outfile LLVM-IR to an intermediate .ll file.
if err := os.WriteFile(llfile, []byte(output), 0644); err != nil {
return err
}
// Invoke command `llc xxx.ll -mtriple=xxx`.
llc := []string{llfile}
if target != "" {
llc = append(llc, "-mtriple", target)
}
// Add target specific options.
switch target {
case "avr":
llc = append(llc, "-mcpu=atmega328")
default:
}
cmd0 := exec.Command(opt.Llc, llc...)
cmd0.Stderr = os.Stderr
if err := cmd0.Run(); err != nil {
fmt.Fprintf(os.Stderr, "**** failed to invoke LLVM ****\n")
return err
}
// TODO: This is a temporary solution for AVR-Arduino. We generate
// an Arduino project instead of an ELF.
if target == "avr" {
// Create a new directory for the output Arduino project.
ext, outdir := path.Ext(outfile), ""
if len(ext) > 0 {
pos := strings.Index(outfile, ext)
outdir = outfile[0:pos]
}
if err := os.RemoveAll(outdir); err != nil {
return err
}
if err := os.Mkdir(outdir, 0755); err != nil {
return err
}
// Move the assembly file to the project directory.
newAsmFile := strings.ReplaceAll(asmfile, ".s", ".S")
if err := os.Rename(asmfile, path.Join(outdir, newAsmFile)); err != nil {
return err
}
// Create the project main '.ino' file.
inoFile := path.Join(outdir, path.Base(outdir)+".ino")
inoStr := "void setup(void) {}\nextern \"C\" { extern void wa_main(void); }\nvoid loop(void) { wa_main(); }\n"
if err := os.WriteFile(inoFile, []byte(inoStr), 0644); err != nil {
return err
}
return nil
}
// Invoke command `clang xxx.s -o outfile --target=xxx`.
clangArgs := []string{asmfile, "-static", "-o", outfile}
if target != "" {
clangArgs = append(clangArgs, "-target", target)
}
if opt.Debug {
clangArgs = append(clangArgs, "-v")
}
cmd1 := exec.Command(opt.Clang, clangArgs...)
cmd1.Stderr = os.Stderr
cmd1.Stdout = os.Stdout
if err := cmd1.Run(); err != nil {
fmt.Fprintf(os.Stderr, "**** failed to invoke CLANG ****\n")
return err
}
return nil
}

View File

@ -1,29 +0,0 @@
// 版权 @2023 凹语言 作者。保留所有权利。
package applogo
import "wa-lang.org/wa/internal/3rdparty/cli"
var CmdLogo = &cli.Command{
Name: "logo",
Usage: "print Wa text format logo",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "more",
Aliases: []string{"m"},
Usage: "print more text logos",
},
&cli.BoolFlag{
Name: "svg",
Usage: "print svg logo",
},
},
Action: func(c *cli.Context) error {
if c.Bool("svg") {
PrintLogoSvg()
return nil
}
PrintLogo(c.Bool("more"))
return nil
},
}

View File

@ -1,264 +0,0 @@
// 版权 @2019 凹语言 作者。保留所有权利。
package applogo
import (
"fmt"
"time"
)
func PrintLogoSvg() {
fmt.Print(logoSvg)
}
func PrintLogo(more bool) {
if is1024Day() {
fmt.Print(logo1024)
} else {
fmt.Print(logo)
}
if more {
fmt.Print(moreLogos)
}
fmt.Println()
}
func is1024Day() bool {
_, month, day := time.Now().Date()
return month == 10 && day == 24
}
const logo = `
+---+ +---+
| o | | o |
| +----+ |
| |
| Wa |
| |
+------------+
`
const logo1024 = `
+---+ +---+
| o | | o |
| +----+ |
| |
| 1024 |
| |
+------------+
`
const logoSvg = `<!--
// 版权 @2019 凹语言 作者。保留所有权利。
// https://wa-lang.org
-->
<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 400 400" width="400" height="400"
style="border: 0px solid red"
>
<path
stroke="none" fill="LightSeaGreen"
d="M60,50 h90 v100 h100 v-100 h90 l10,10 v280 l-10,10 h-280 l-10,-10 v-280"
/>
<path
stroke="none" fill="white"
d="M100,100 m-5,-5 h10 v10 h-10"
/>
<path
stroke="none" fill="white"
d="M400,100 m-100,0 m-5,-5 h10 v10 h-10"
/>
<path
stroke="white" fill="none" stroke-width="8" stroke-linecap="round"
d="M200,230 l34,34 l34,-34 M200,230 l-34,34 l-34,-34"
/>
</svg>
`
const moreLogos = `
+---+ +---+
| * | | * |
| +----+ |
| |
| \/\/ |
| |
+------------+
+---+ +---+
| - | | 0 |
| +----+ |
| |
| \/\/ |
| |
+------------+
+---+ +---+
| + | | + |
| +----+ |
| |
| +--+ |
| |
+------------+
+---+ +---+
| & | | % |
| +----+ |
| |
| ^^^^ |
| |
+------------+
+---+ +---+
| ~ | | ~ |
| +----+ |
| |
| 7777 |
| |
+------------+
+-----------+
| 0 |
+---+ |
| > |
| > |
+---+ |
| 0 |
+-----------+
+---++---+
/ * / \ * \
| +----+ |
| |
| \/\/ |
| |
+------------+
+---+ +---+
\ * \ / * /
| +----+ |
| |
| \/\/ |
| |
+------------+
+---+ +---+---+ +---+
\ * \ / * / \ * \ / * /
| +----+ | | +----+ |
| | | |
| \/\/ | | \/\/ |
| | | |
+------------+ +------------+
+---+ +---+---+ +---+
/ o / / o / \ ~ \ \ ~ \
/ +----+ / \ +----+ \
/ / \ \
/ \/\/ / \ /\/\ \
/ / \ \
+---+----+--- wa-lang.org ---+----+---+
\ - \ \ - \ / + / / + /
\ +----+ \ / +----+ /
\ \ / /
\ \<<\ \ / />>/ /
\ \ / /
+------------+------------+
+---+ +---+
| o | | o |
| +----+ |
| |
| \/\/ |
| |
+---+----+---+
\ - \ \ - \
\ +----+ \
\ \
\ \<<\ \
\ \
+---+----+---+
/ o / / o /
/ +----+ /
/ /
/ \/\/ /
/ /
+---+----+---+
\ - \ \ - \
\ +----+ \
\ \
\ \<<\ \
\ \
+---+----+---+
/ o / / o /
/ +----+ /
/ /
/ \/\/ /
/ /
+---+----+---+
| o | | o |
| +----+ |
| |
| \/\/ |
| |
+---+----+---+
| o | | o |
| +----+ |
\ \
\ \/\/ \
\ \
+---+----+---+
| o | | o |
| +----+ |
/ /
/ \/\/ /
/ /
+---+----+---+
| o | | o |
| +----+ |
\ \
\ \/\/ \
\ \
+---+----+---+
| o | | o |
| +----+ |
/ /
/ \/\/ /
/ /
+------------+
+---+----+---+
/ \ ~ \ \ ~ \
/ \ +----+ \
/ \ \
//. \ /\/\ \
///.. \ \
++++... +---+----+---+
\\\.. / + / / + /
\\. / +----+ /
\ / /
\ / />>/ /
\ / /
+------------+
____ ____
/ /\ / /\
/____/ /____/ \
\ \ \ \ 0 \
\ \ \ \ \
____ ____ __\ \
/ /\ / /\ / \
/____/ /____/ \ / 7 \
\ \ \ \ 0 \/ 7 /
\ <> \ \ <> \ 7 /
\ \/__\ \ 7 /
\ \ /
\ ~~~~ \ /
\ \ /
\_____________\/
`

View File

@ -1,23 +0,0 @@
package applsp
import (
"wa-lang.org/wa/internal/3rdparty/cli"
"wa-lang.org/wa/internal/lsp"
)
var CmdLsp = &cli.Command{
Hidden: true,
Name: "lsp",
Usage: "run Wa langugage server",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "log-file",
Usage: "set log file",
Value: "",
},
},
Action: func(c *cli.Context) error {
lsp.NewLSPServer(&lsp.Option{}).Run()
return nil
},
}

View File

@ -1,82 +0,0 @@
<!doctype html>
<html>
<head>
<link rel="icon" href="/static/logo.svg">
<title>凹语言游乐场</title>
<link rel="stylesheet" href="/static/playground/playground-full.css">
<script src="/static/playground/jquery/1.8.2/jquery.min.js"></script>
<script src="/static/playground/playground-full.js"></script>
<style>
.cm-tab {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
background-position: right;
background-repeat: no-repeat;
}
</style>
<script>
$(document).ready(function() {
playground({
'theme': 'default',
'codeEl': '#code',
'outputEl': '#output',
'runEl': '#run',
'fmtEl': '#fmt',
'enableHistory': true
});
// Avoid line wrapping.
var about = $('#about');
about.click(function(e) {
if ($(e.target).is('a')) {
return;
}
about.hide();
});
$('#homeButton').click(function() {
$(location).attr('href','/')
})
$('#aboutButton').click(function() {
if (about.is(':visible')) {
about.hide();
return;
}
about.show();
})
// Fire Google Analytics events for Run/Share button clicks.
if (window.trackEvent) {
$('#run').click(function() {
window.trackEvent('playground', 'click', 'run-button');
});
$('#fmt').click(function() {
window.trackEvent('playground', 'click', 'fmt-button');
});
}
});
</script>
</head>
<body itemscope itemtype="http://schema.org/CreativeWork">
<div id="banner">
<div id="head" itemprop="name">凹语言游乐场</div>
<div id="controls">
<input type="button" value="运行" id="run">
<input type="button" value="格式化" id="fmt">
</div>
<div id="aboutControls">
<input type="button" value="关于" id="aboutButton">
</div>
</div>
<div id="wrap">
<textarea itemprop="description" id="code" name="code" autocorrect="off" autocomplete="off" autocapitalize="off" spellcheck="false">{{printf "%s" .Snippet.Body}}</textarea>
</div>
<div id="output"></div>
<div id="about">
<p><b>凹语言 (The Wa Programming Language)</b></p>
<a target="_blank" href="https://wa-lang.org">https://wa-lang.org</a>
</div>
</body>
</html>

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