Compare commits

..

1 Commits

Author SHA1 Message Date
Onur Yilmaz
7fb8f2c709 Arguments from HTTP headers 2019-01-29 15:44:20 +01:00
189 changed files with 17900 additions and 11562 deletions

View File

@ -1,528 +0,0 @@
{
"projectName": "gotty",
"projectOwner": "sorenisanerd",
"repoType": "github",
"repoHost": "https://github.com",
"files": [
"README.md"
],
"imageSize": 100,
"commit": true,
"commitConvention": "none",
"contributors": [
{
"login": "yudai",
"name": "Iwasaki Yudai",
"avatar_url": "https://avatars.githubusercontent.com/u/33192?v=4",
"profile": "https://yudai.arielworks.com/",
"contributions": [
"code"
]
},
{
"login": "sorenisanerd",
"name": "Soren L. Hansen",
"avatar_url": "https://avatars.githubusercontent.com/u/160090?v=4",
"profile": "http://linux2go.dk/",
"contributions": [
"bug"
]
},
{
"login": "uovobw",
"name": "Andrea Lusuardi",
"avatar_url": "https://avatars.githubusercontent.com/u/1194751?v=4",
"profile": "https://github.com/uovobw",
"contributions": [
"code"
]
},
{
"login": "moul",
"name": "Manfred Touron",
"avatar_url": "https://avatars.githubusercontent.com/u/94029?v=4",
"profile": "https://github.com/moul",
"contributions": [
"code"
]
},
{
"login": "svanellewee",
"name": "Stephan",
"avatar_url": "https://avatars.githubusercontent.com/u/1567439?v=4",
"profile": "https://github.com/svanellewee",
"contributions": [
"code"
]
},
{
"login": "QuentinPerez",
"name": "Quentin Perez",
"avatar_url": "https://avatars.githubusercontent.com/u/3081204?v=4",
"profile": "https://fr.linkedin.com/in/quentinperez",
"contributions": [
"code"
]
},
{
"login": "jizhilong",
"name": "jzl",
"avatar_url": "https://avatars.githubusercontent.com/u/816618?v=4",
"profile": "https://github.com/jizhilong",
"contributions": [
"code"
]
},
{
"login": "fazalmajid",
"name": "Fazal Majid",
"avatar_url": "https://avatars.githubusercontent.com/u/331198?v=4",
"profile": "https://majid.info/",
"contributions": [
"code"
]
},
{
"login": "Immortalin",
"name": "Immortalin",
"avatar_url": "https://avatars.githubusercontent.com/u/7126128?v=4",
"profile": "https://narrationbox.com/",
"contributions": [
"code"
]
},
{
"login": "freakhill",
"name": "freakhill",
"avatar_url": "https://avatars.githubusercontent.com/u/916582?v=4",
"profile": "https://github.com/freakhill",
"contributions": [
"code"
]
},
{
"login": "0xflotus",
"name": "0xflotus",
"avatar_url": "https://avatars.githubusercontent.com/u/26602940?v=4",
"profile": "https://github.com/0xflotus",
"contributions": [
"code"
]
},
{
"login": "skeltoac",
"name": "Andy Skelton",
"avatar_url": "https://avatars.githubusercontent.com/u/52292?v=4",
"profile": "https://andy.blog/",
"contributions": [
"code"
]
},
{
"login": "artdevjs",
"name": "Artem Medvedev",
"avatar_url": "https://avatars.githubusercontent.com/u/7567983?v=4",
"profile": "https://twitter.com/artdevjs",
"contributions": [
"code"
]
},
{
"login": "blakejennings",
"name": "Blake Jennings",
"avatar_url": "https://avatars.githubusercontent.com/u/1976331?v=4",
"profile": "https://github.com/blakejennings",
"contributions": [
"code"
]
},
{
"login": "jensenbox",
"name": "Christian Jensen",
"avatar_url": "https://avatars.githubusercontent.com/u/189265?v=4",
"profile": "https://github.com/jensenbox",
"contributions": [
"code"
]
},
{
"login": "TechWilk",
"name": "Christopher Wilkinson",
"avatar_url": "https://avatars.githubusercontent.com/u/9367803?v=4",
"profile": "https://wilk.tech/",
"contributions": [
"code"
]
},
{
"login": "RealCyGuy",
"name": "Cyrus",
"avatar_url": "https://avatars.githubusercontent.com/u/54488650?v=4",
"profile": "https://github.com/RealCyGuy",
"contributions": [
"code"
]
},
{
"login": "dehorsley",
"name": "David Horsley",
"avatar_url": "https://avatars.githubusercontent.com/u/3401668?v=4",
"profile": "https://github.com/dehorsley",
"contributions": [
"code"
]
},
{
"login": "Jason-Cooke",
"name": "Jason Cooke",
"avatar_url": "https://avatars.githubusercontent.com/u/5185660?v=4",
"profile": "https://jasoncooke.dev/",
"contributions": [
"code"
]
},
{
"login": "DenKoren",
"name": "Denis Korenevskiy",
"avatar_url": "https://avatars.githubusercontent.com/u/3419381?v=4",
"profile": "https://github.com/DenKoren",
"contributions": [
"code"
]
},
{
"login": "stucchimax",
"name": "Massimiliano Stucchi",
"avatar_url": "https://avatars.githubusercontent.com/u/1331438?v=4",
"profile": "https://www.stucchi.ch/",
"contributions": [
"code"
]
},
{
"login": "Felixoid",
"name": "Mikhail f. Shiryaev",
"avatar_url": "https://avatars.githubusercontent.com/u/3025537?v=4",
"profile": "https://www.linkedin.com/in/felixoid/",
"contributions": [
"code"
]
},
{
"login": "guywithnose",
"name": "Robert Bittle",
"avatar_url": "https://avatars.githubusercontent.com/u/1059169?v=4",
"profile": "https://github.com/guywithnose",
"contributions": [
"code"
]
},
{
"login": "sehaas",
"name": "sebastian haas",
"avatar_url": "https://avatars.githubusercontent.com/u/283482?v=4",
"profile": "https://deebas.com/",
"contributions": [
"code"
]
},
{
"login": "shoz",
"name": "shoji",
"avatar_url": "https://avatars.githubusercontent.com/u/225194?v=4",
"profile": "https://github.com/shoz",
"contributions": [
"code"
]
},
{
"login": "tsl0922",
"name": "Shuanglei Tao",
"avatar_url": "https://avatars.githubusercontent.com/u/1680515?v=4",
"profile": "https://github.com/tsl0922",
"contributions": [
"code"
]
},
{
"login": "gitter-badger",
"name": "The Gitter Badger",
"avatar_url": "https://avatars.githubusercontent.com/u/8518239?v=4",
"profile": "https://gitter.im/",
"contributions": [
"code"
]
},
{
"login": "xinsnake",
"name": "Jacob Zhou",
"avatar_url": "https://avatars.githubusercontent.com/u/1287677?v=4",
"profile": "https://github.com/xinsnake",
"contributions": [
"code"
]
},
{
"login": "zyfdegh",
"name": "zyfdegh",
"avatar_url": "https://avatars.githubusercontent.com/u/7880217?v=4",
"profile": "https://github.com/zyfdegh",
"contributions": [
"code"
]
},
{
"login": "fredster33",
"name": "fredster33",
"avatar_url": "https://avatars.githubusercontent.com/u/64927044?v=4",
"profile": "https://github.com/fredster33",
"contributions": [
"code"
]
},
{
"login": "mattn",
"name": "mattn",
"avatar_url": "https://avatars.githubusercontent.com/u/10111?v=4",
"profile": "https://mattn.kaoriya.net/",
"contributions": [
"code"
]
},
{
"login": "shingt",
"name": "Shinichi Goto",
"avatar_url": "https://avatars.githubusercontent.com/u/1391330?v=4",
"profile": "https://www.shingt.com/",
"contributions": [
"code"
]
},
{
"login": "ygit",
"name": "ygit",
"avatar_url": "https://avatars.githubusercontent.com/u/8512357?v=4",
"profile": "https://twitter.com/_yogeshsingh",
"contributions": [
"code"
]
},
{
"login": "nephaste",
"name": "Stéphane",
"avatar_url": "https://avatars.githubusercontent.com/u/3392684?v=4",
"profile": "http://forum.cachem.fr/viewforum.php?f=21",
"contributions": [
"bug"
]
},
{
"login": "prusnak",
"name": "Pavol Rusnak",
"avatar_url": "https://avatars.githubusercontent.com/u/42201?v=4",
"profile": "https://rusnak.io/",
"contributions": [
"bug"
]
},
{
"login": "devanlai",
"name": "Devan Lai",
"avatar_url": "https://avatars.githubusercontent.com/u/1348448?v=4",
"profile": "https://github.com/devanlai",
"contributions": [
"code"
]
},
{
"login": "jkandasa",
"name": "Jeeva Kandasamy",
"avatar_url": "https://avatars.githubusercontent.com/u/1004403?v=4",
"profile": "https://github.com/jkandasa",
"contributions": [
"code"
]
},
{
"login": "hardliner66",
"name": "Steve Biedermann",
"avatar_url": "https://avatars.githubusercontent.com/u/2937272?v=4",
"profile": "https://twitch.tv/iamhardliner",
"contributions": [
"code"
]
},
{
"login": "xgdgsc",
"name": "xgdgsc",
"avatar_url": "https://avatars.githubusercontent.com/u/1189869?v=4",
"profile": "https://github.com/xgdgsc",
"contributions": [
"bug"
]
},
{
"login": "flechaig",
"name": "flechaig",
"avatar_url": "https://avatars.githubusercontent.com/u/10887132?v=4",
"profile": "https://github.com/flechaig",
"contributions": [
"bug"
]
},
{
"login": "Fan-SJ",
"name": "Fan-SJ",
"avatar_url": "https://avatars.githubusercontent.com/u/49977708?v=4",
"profile": "https://github.com/Fan-SJ",
"contributions": [
"bug"
]
},
{
"login": "dmartin",
"name": "Dustin Martin",
"avatar_url": "https://avatars.githubusercontent.com/u/1657652?v=4",
"profile": "https://github.com/dmartin",
"contributions": [
"bug"
]
},
{
"login": "ahmetb",
"name": "Ahmet Alp Balkan",
"avatar_url": "https://avatars.githubusercontent.com/u/159209?v=4",
"profile": "https://ahmet.dev/",
"contributions": [
"bug"
]
},
{
"login": "CoconutMacaroon",
"name": "CoconutMacaroon",
"avatar_url": "https://avatars.githubusercontent.com/u/45187468?v=4",
"profile": "https://github.com/CoconutMacaroon",
"contributions": [
"bug"
]
},
{
"login": "DannyBen",
"name": "Danny Ben Shitrit",
"avatar_url": "https://avatars.githubusercontent.com/u/2405099?v=4",
"profile": "https://github.dannyben.com/",
"contributions": [
"bug"
]
},
{
"login": "George-NG",
"name": "George-NG",
"avatar_url": "https://avatars.githubusercontent.com/u/28577165?v=4",
"profile": "https://github.com/George-NG",
"contributions": [
"bug"
]
},
{
"login": "ghthor",
"name": "Will Owens",
"avatar_url": "https://avatars.githubusercontent.com/u/160298?v=4",
"profile": "https://github.com/ghthor",
"contributions": [
"bug"
]
},
{
"login": "jpillora",
"name": "Jaime Pillora",
"avatar_url": "https://avatars.githubusercontent.com/u/633843?v=4",
"profile": "https://jpillora.com/",
"contributions": [
"bug"
]
},
{
"login": "kaisawind",
"name": "kaisawind",
"avatar_url": "https://avatars.githubusercontent.com/u/4010613?v=4",
"profile": "https://github.com/kaisawind",
"contributions": [
"bug"
]
},
{
"login": "linyinli",
"name": "linyinli",
"avatar_url": "https://avatars.githubusercontent.com/u/42955482?v=4",
"profile": "https://github.com/linyinli",
"contributions": [
"bug"
]
},
{
"login": "LucaMarconato",
"name": "LucaMarconato",
"avatar_url": "https://avatars.githubusercontent.com/u/2664412?v=4",
"profile": "https://github.com/LucaMarconato",
"contributions": [
"bug"
]
},
{
"login": "masterkain",
"name": "Kain",
"avatar_url": "https://avatars.githubusercontent.com/u/12844?v=4",
"profile": "https://audiobox.fm/",
"contributions": [
"bug"
]
},
{
"login": "Nexuist",
"name": "Andi Andreas",
"avatar_url": "https://avatars.githubusercontent.com/u/1498061?v=4",
"profile": "http://duro.me/",
"contributions": [
"bug"
]
},
{
"login": "qigj",
"name": "qigj",
"avatar_url": "https://avatars.githubusercontent.com/u/56585735?v=4",
"profile": "https://github.com/qigj",
"contributions": [
"bug"
]
},
{
"login": "shuaiyy",
"name": "shuaiyy",
"avatar_url": "https://avatars.githubusercontent.com/u/19821321?v=4",
"profile": "https://github.com/shuaiyy",
"contributions": [
"bug"
]
},
{
"login": "v20z",
"name": "v20z",
"avatar_url": "https://avatars.githubusercontent.com/u/2884824?v=4",
"profile": "https://github.com/v20z",
"contributions": [
"bug"
]
},
{
"login": "Yann-Qiu",
"name": "Yanfeng Qiu",
"avatar_url": "https://avatars.githubusercontent.com/u/56961747?v=4",
"profile": "https://github.com/Yann-Qiu",
"contributions": [
"bug"
]
}
],
"contributorsPerLine": 7
}

View File

@ -1,49 +0,0 @@
name: "Unit and Build Tests"
on:
push:
pull_request:
branches: [ master ]
jobs:
bundle-up-to-date:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-go@v3
with:
go-version: 1.19
- uses: actions/setup-node@v3
with:
node-version: 16
- run: "make clean"
- run: "make assets"
- name: "Make sure gotty.js bundle is up-to-date"
run: "diffsize=$(git diff bindata/static/js/gotty.js | wc -l); test $diffsize == 0"
cross-compile-test:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build & test"
run: "make tools test cross_compile"
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: binaries
path: builds/pkg/*/gotty

View File

@ -1,42 +0,0 @@
---
name: "pre-release"
on: [push]
env:
IMAGE_NAME: ${{ github.repository }}
jobs:
pre-release-docker:
name: "Pre Release Docker"
runs-on: "ubuntu-latest"
steps:
-
name: Docker meta
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.IMAGE_NAME }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=sha,format=long
type=sha
type=semver,pattern=v{{major}}.{{minor}}.{{patch}}
type=semver,pattern=v{{major}}.{{minor}}
type=semver,pattern=v{{major}}
type=ref,event=tag
type=ref,event=branch
- uses: docker/setup-qemu-action@v2
- uses: docker/setup-buildx-action@v2
- uses: docker/login-action@v2
with:
username: "${{ secrets.DOCKER_HUB_USER }}"
password: "${{ secrets.DOCKER_HUB_TOKEN }}"
- name: "Build and push docker image"
uses: docker/build-push-action@v4
with:
platforms: linux/amd64,linux/arm/v7,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

View File

@ -1,30 +0,0 @@
name: "Quick build test"
on:
push:
pull_request:
branches: [ master ]
jobs:
quick-build-test:
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build"
run: "touch bindata/* bindata/*/* ; make"
- name: Upload linux/amd64 artifact
uses: actions/upload-artifact@v3
with:
name: gotty-linux-amd64
path: gotty

View File

@ -1,40 +0,0 @@
---
name: "tagged-release"
on:
push:
tags:
- "v*"
jobs:
tagged-release:
name: "Tagged Release"
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.19
- name: "Build & test"
run: "make tools test release-artifacts"
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: binaries
path: builds/pkg/*/gotty
- uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false
draft: true
files: |
LICENSE
builds/dist/*

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
gotty
bindata
builds
js/dist
js/node_modules/*

View File

@ -1,9 +0,0 @@
# 'git shortlog --help' and look for mailmap for the format of each line
# Email consolidation:
# <Preferred address in AUTHORS> <other alias used by same author>
# Name consolidation:
# Preferred author spelling <preferred email>
Søren L. Hansen <sorenisanerd@gmail.com>

View File

@ -1,5 +0,0 @@
{
"recommendations": [
"amodio.tsl-problem-matcher"
]
}

27
.vscode/launch.json vendored
View File

@ -1,27 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch GoTTY",
"type": "go",
"buildFlags": "-tags=dev",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"args": ["-a", "127.0.0.1", "-w", "${env:SHELL}"]
},
{
"name": "Launch Chrome",
"type": "chrome",
"url": "http://127.0.0.1:8080",
"webRoot": "${workspaceFolder}/js",
"outFiles": [
"${workspaceFolder}/**/*.js",
"!**/node_modules/**"
],
},
]
}

16
.vscode/tasks.json vendored
View File

@ -1,16 +0,0 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "webpack watch",
"type": "shell",
"command": "cd ${workspaceFolder}/js;DEV=1 npx webpack --watch --mode=development",
"problemMatcher": [
"$ts-webpack-watch"
],
"isBackground": true
}
]
}

View File

@ -41,4 +41,4 @@ When your pull request is to add a new feature, we recommend add an actual useca
## Contact
If you have a trivial question about GoTTY for a bug or new feature, you can contact @sorenisanerd on Twitter (unfortunately, I cannot provide support on GoTTY though).
If you have a trivial question about GoTTY for a bug or new feature, you can contact @i_yudai on Twitter (unfortunately, I cannot provide support on GoTTY though).

View File

@ -1,20 +0,0 @@
FROM node:16 as js-build
WORKDIR /gotty
COPY js /gotty/js
COPY Makefile /gotty/
RUN make bindata/static/js/gotty.js.map
FROM golang:1.20 as go-build
WORKDIR /gotty
COPY . /gotty
COPY --from=js-build /gotty/js/node_modules /gotty/js/node_modules
COPY --from=js-build /gotty/bindata/static/js /gotty/bindata/static/js
RUN CGO_ENABLED=0 make
FROM alpine:latest
RUN apk update && \
apk upgrade && \
apk --no-cache add ca-certificates bash
WORKDIR /root
COPY --from=go-build /gotty/gotty /usr/bin/
CMD ["gotty", "-w", "bash"]

54
Godeps/Godeps.json generated Normal file
View File

@ -0,0 +1,54 @@
{
"ImportPath": "github.com/yudai/gotty",
"GoVersion": "go1.9",
"GodepVersion": "v79",
"Deps": [
{
"ImportPath": "github.com/NYTimes/gziphandler",
"Rev": "967539e5e271a2bc9b3dcb1285078a1b1df105ae"
},
{
"ImportPath": "github.com/codegangsta/cli",
"Comment": "v1.19.1",
"Rev": "0bdeddeeb0f650497d603c4ad7b20cfe685682f6"
},
{
"ImportPath": "github.com/elazarl/go-bindata-assetfs",
"Rev": "d5cac425555ca5cf00694df246e04f05e6a55150"
},
{
"ImportPath": "github.com/fatih/structs",
"Rev": "a9f7daa9c2729e97450c2da2feda19130a367d8f"
},
{
"ImportPath": "github.com/gorilla/websocket",
"Rev": "b6ab76f1fe9803ee1d59e7e5b2a797c1fe897ce5"
},
{
"ImportPath": "github.com/hashicorp/go-multierror",
"Rev": "56912fb08d85084aa318edcf2bba735b97cf35c5"
},
{
"ImportPath": "github.com/kr/pty",
"Comment": "release.r56-28-g5cf931e",
"Rev": "5cf931ef8f76dccd0910001d74a58a7fca84a83d"
},
{
"ImportPath": "github.com/pkg/errors",
"Comment": "v0.8.0-2-g248dadf",
"Rev": "248dadf4e9068a0b3e79f02ed0a610d935de5302"
},
{
"ImportPath": "github.com/yudai/hcl",
"Rev": "5fa2393b3552119bf33a69adb1402a1160cba23d"
},
{
"ImportPath": "github.com/yudai/hcl/hcl",
"Rev": "5fa2393b3552119bf33a69adb1402a1160cba23d"
},
{
"ImportPath": "github.com/yudai/hcl/json",
"Rev": "5fa2393b3552119bf33a69adb1402a1160cba23d"
}
]
}

5
Godeps/Readme generated Normal file
View File

@ -0,0 +1,5 @@
This directory tree is generated automatically by godep.
Please do not edit.
See https://github.com/tools/godep for more information.

View File

@ -1,7 +1,6 @@
The MIT License (MIT)
Copyright (c) 2015-2017 Iwasaki Yudai
Copyright (c) 2021-2022 Søren L. Hansen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,76 +1,73 @@
OUTPUT_DIR = ./builds
GIT_COMMIT = `git rev-parse HEAD | cut -c1-7`
VERSION = $(shell git describe --tags)
BUILD_OPTIONS = -ldflags "-X main.Version=$(VERSION)"
VERSION = 2.0.0-alpha.3
BUILD_OPTIONS = -ldflags "-X main.Version=$(VERSION) -X main.CommitID=$(GIT_COMMIT)"
ifeq ($(DEV), 1)
BUILD_OPTIONS += -tags dev
WEBPACK_MODE = development
else
WEBPACK_MODE = production
endif
gotty: main.go server/*.go webtty/*.go backend/*.go Makefile
godep go build ${BUILD_OPTIONS}
export CGO_ENABLED=0
.PHONY: asset
asset: bindata/static/js/gotty-bundle.js bindata/static/index.html bindata/static/favicon.png bindata/static/css/index.css bindata/static/css/xterm.css bindata/static/css/xterm_customize.css
go-bindata -prefix bindata -pkg server -ignore=\\.gitkeep -o server/asset.go bindata/...
gofmt -w server/asset.go
gotty: main.go assets server/*.go webtty/*.go backend/*.go Makefile
go build ${BUILD_OPTIONS}
.PHONY: all
all: asset gotty
docker:
docker build . -t gotty-bash:$(VERSION)
bindata:
mkdir bindata
.PHONY: all docker assets
assets: bindata/static/js/gotty.js.map \
bindata/static/js/gotty.js \
bindata/static/index.html \
bindata/static/icon.svg \
bindata/static/favicon.ico \
bindata/static/css/index.css \
bindata/static/css/xterm.css \
bindata/static/css/xterm_customize.css \
bindata/static/manifest.json \
bindata/static/icon_192.png
bindata/static: bindata
mkdir bindata/static
all: gotty
bindata/static/index.html: bindata/static resources/index.html
cp resources/index.html bindata/static/index.html
bindata/static bindata/static/css bindata/static/js:
mkdir -p $@
bindata/static/favicon.png: bindata/static resources/favicon.png
cp resources/favicon.png bindata/static/favicon.png
bindata/static/%: resources/% | bindata/static/css
cp "$<" "$@"
bindata/static/js: bindata/static
mkdir -p bindata/static/js
bindata/static/css/%.css: resources/%.css | bindata/static
cp "$<" "$@"
bindata/static/css/xterm.css: js/node_modules/xterm/css/xterm.css | bindata/static
cp "$<" "$@"
bindata/static/js/gotty-bundle.js: bindata/static/js js/dist/gotty-bundle.js
cp js/dist/gotty-bundle.js bindata/static/js/gotty-bundle.js
bindata/static/css: bindata/static
mkdir -p bindata/static/css
bindata/static/css/index.css: bindata/static/css resources/index.css
cp resources/index.css bindata/static/css/index.css
bindata/static/css/xterm_customize.css: bindata/static/css resources/xterm_customize.css
cp resources/xterm_customize.css bindata/static/css/xterm_customize.css
bindata/static/css/xterm.css: bindata/static/css js/node_modules/xterm/dist/xterm.css
cp js/node_modules/xterm/dist/xterm.css bindata/static/css/xterm.css
js/node_modules/xterm/dist/xterm.css:
cd js && \
npm install
bindata/static/js/gotty.js.map bindata/static/js/gotty.js: js/src/* | js/node_modules/webpack
js/dist/gotty-bundle.js: js/src/* js/node_modules/webpack
cd js && \
npx webpack --mode=$(WEBPACK_MODE)
`npm bin`/webpack
js/node_modules/webpack:
cd js && \
npm install
README-options:
./gotty --help | sed '1,/GLOBAL OPTIONS/ d' > options.txt.tmp
sed -f README.md.sed -i README.md
rm options.txt.tmp
tools:
go install github.com/mitchellh/gox@latest
go install github.com/tcnksm/ghr@latest
go get github.com/tools/godep
go get github.com/mitchellh/gox
go get github.com/tcnksm/ghr
go get github.com/jteeuwen/go-bindata/...
test:
if [ `go fmt $(go list ./... | grep -v /vendor/) | wc -l` -gt 0 ]; then echo "go fmt error"; exit 1; fi
go test ./...
cross_compile:
GOARM=5 gox -os="darwin linux freebsd netbsd openbsd solaris" -arch="386 amd64 arm arm64" -osarch="!darwin/386" -osarch="!darwin/arm" $(BUILD_OPTIONS) -output "${OUTPUT_DIR}/pkg/{{.OS}}_{{.Arch}}/{{.Dir}}"
GOARM=5 gox -os="darwin linux freebsd netbsd openbsd" -arch="386 amd64 arm" -osarch="!darwin/arm" -output "${OUTPUT_DIR}/pkg/{{.OS}}_{{.Arch}}/{{.Dir}}"
targz:
mkdir -p ${OUTPUT_DIR}/dist
@ -79,14 +76,5 @@ targz:
shasums:
cd ${OUTPUT_DIR}/dist; sha256sum * > ./SHA256SUMS
release-artifacts: gotty cross_compile targz shasums
release:
ghr -draft ${VERSION} ${OUTPUT_DIR}/dist # -c ${GIT_COMMIT} --delete --prerelease -u sorenisanerd -r gotty ${VERSION}
clean:
rm -fr gotty builds js/dist bindata/static js/node_modules
addcontributors:
gh issue list -s all -L 1000 --json author -t "$$(echo '{{ range . }}{{ .author.login }}\n{{ end }}')" | sort | uniq | xargs -Ifoo all-contributors add foo bug --commitTemplate '<%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor'
gh pr list -s all -L 1000 --json author -t "$$(echo '{{ range . }}{{ .author.login }}\n{{ end }}')" | sort | uniq | xargs -Ifoo all-contributors add foo code --commitTemplate '<%= (newContributor ? "Add" : "Update") %> @<%= username %> as a contributor'
ghr -c ${GIT_COMMIT} --delete --prerelease -u yudai -r gotty pre-release ${OUTPUT_DIR}/dist

102
NEWS.md
View File

@ -1,102 +0,0 @@
## 1.5.0 (2022-09-01)
* Add @ahmetb as a contributor ([276767a](https://github.com/sorenisanerd/gotty/commit/276767a))
* Add @CoconutMacaroon as a contributor ([74c1318](https://github.com/sorenisanerd/gotty/commit/74c1318))
* Add @DannyBen as a contributor ([fcfa161](https://github.com/sorenisanerd/gotty/commit/fcfa161))
* Add @dmartin as a contributor ([6b2ae89](https://github.com/sorenisanerd/gotty/commit/6b2ae89))
* Add @Fan-SJ as a contributor ([c2428c8](https://github.com/sorenisanerd/gotty/commit/c2428c8))
* Add @flechaig as a contributor ([2c4004d](https://github.com/sorenisanerd/gotty/commit/2c4004d))
* Add @George-NG as a contributor ([270ae45](https://github.com/sorenisanerd/gotty/commit/270ae45))
* Add @ghthor as a contributor ([1a6bccd](https://github.com/sorenisanerd/gotty/commit/1a6bccd))
* Add @jpillora as a contributor ([f52fbd7](https://github.com/sorenisanerd/gotty/commit/f52fbd7))
* Add @kaisawind as a contributor ([accff3a](https://github.com/sorenisanerd/gotty/commit/accff3a))
* Add @linyinli as a contributor ([8014af3](https://github.com/sorenisanerd/gotty/commit/8014af3))
* Add @LucaMarconato as a contributor ([3bd9836](https://github.com/sorenisanerd/gotty/commit/3bd9836))
* Add @masterkain as a contributor ([369e2f7](https://github.com/sorenisanerd/gotty/commit/369e2f7))
* Add @Nexuist as a contributor ([ca691bc](https://github.com/sorenisanerd/gotty/commit/ca691bc))
* Add @qigj as a contributor ([5a052e7](https://github.com/sorenisanerd/gotty/commit/5a052e7))
* Add @shuaiyy as a contributor ([95e1bbd](https://github.com/sorenisanerd/gotty/commit/95e1bbd))
* Add @v20z as a contributor ([d594bef](https://github.com/sorenisanerd/gotty/commit/d594bef))
* Add @xgdgsc as a contributor ([c197990](https://github.com/sorenisanerd/gotty/commit/c197990))
* Add @Yann-Qiu as a contributor ([7b994ec](https://github.com/sorenisanerd/gotty/commit/7b994ec))
* Update @flechaig as a contributor ([9877e9c](https://github.com/sorenisanerd/gotty/commit/9877e9c))
* Update @flechaig as a contributor ([e03ea9c](https://github.com/sorenisanerd/gotty/commit/e03ea9c))
* Update @prusnak as a contributor ([3c45888](https://github.com/sorenisanerd/gotty/commit/3c45888))
* Update @prusnak as a contributor ([8d7f5fc](https://github.com/sorenisanerd/gotty/commit/8d7f5fc))
* Update @sorenisanerd as a contributor ([34f516b](https://github.com/sorenisanerd/gotty/commit/34f516b))
* Update @sorenisanerd as a contributor ([89a04d1](https://github.com/sorenisanerd/gotty/commit/89a04d1))
* Update @xgdgsc as a contributor ([b3c5d03](https://github.com/sorenisanerd/gotty/commit/b3c5d03))
* Update @xgdgsc as a contributor ([09f7e95](https://github.com/sorenisanerd/gotty/commit/09f7e95))
* Add make target to add contributors ([1bbfd5e](https://github.com/sorenisanerd/gotty/commit/1bbfd5e))
* Add missing import "strings" ([d0e3ffb](https://github.com/sorenisanerd/gotty/commit/d0e3ffb))
* add slash ([7706bf2](https://github.com/sorenisanerd/gotty/commit/7706bf2))
* Always disable CGO ([7a96f37](https://github.com/sorenisanerd/gotty/commit/7a96f37)), closes [#39](https://github.com/sorenisanerd/gotty/issues/39)
* Bump terser from 5.12.1 to 5.14.2 in /js ([3ae13e0](https://github.com/sorenisanerd/gotty/commit/3ae13e0))
* Create a release when a new tag is pushed ([d8fe975](https://github.com/sorenisanerd/gotty/commit/d8fe975))
* Ensure --quiet flag is honored ([7d431a7](https://github.com/sorenisanerd/gotty/commit/7d431a7)), closes [#45](https://github.com/sorenisanerd/gotty/issues/45)
* Refresh dependencies, drop node-sass ([94e5873](https://github.com/sorenisanerd/gotty/commit/94e5873))
* Run tests on pull requests ([316d5ff](https://github.com/sorenisanerd/gotty/commit/316d5ff))
## 1.4.0 (2022-05-30)
* Add @hardliner66 as a contributor ([1ca998e](https://github.com/sorenisanerd/gotty/commit/1ca998e))
* Add @jkandasa as a contributor ([cd23910](https://github.com/sorenisanerd/gotty/commit/cd23910))
* Add backend tests ([603c650](https://github.com/sorenisanerd/gotty/commit/603c650))
* Add generated data to git ([a9fbc07](https://github.com/sorenisanerd/gotty/commit/a9fbc07))
* add quiet flag to disable logging ([4109b11](https://github.com/sorenisanerd/gotty/commit/4109b11))
* Add references to @yudai ([bffd821](https://github.com/sorenisanerd/gotty/commit/bffd821)), closes [#8](https://github.com/sorenisanerd/gotty/issues/8)
* Add rule to build gotty.js.map ([82c3acf](https://github.com/sorenisanerd/gotty/commit/82c3acf))
* Apply font size and family in xterm ([f157dbe](https://github.com/sorenisanerd/gotty/commit/f157dbe)), closes [#21](https://github.com/sorenisanerd/gotty/issues/21)
* Avoid HTTP 401 error on manifest.json due to CORS ([817b5c8](https://github.com/sorenisanerd/gotty/commit/817b5c8))
* Bump browserslist from 4.16.4 to 4.16.6 in /js ([8deba62](https://github.com/sorenisanerd/gotty/commit/8deba62))
* Disable arg passing by default ([5c8eb10](https://github.com/sorenisanerd/gotty/commit/5c8eb10)), closes [#17](https://github.com/sorenisanerd/gotty/issues/17)
* Do not include ALL of bootstrap ([b63ea16](https://github.com/sorenisanerd/gotty/commit/b63ea16))
* Ensure defaults for booleans is set correctly ([28f8e61](https://github.com/sorenisanerd/gotty/commit/28f8e61)), closes [#16](https://github.com/sorenisanerd/gotty/issues/16)
* Fix existing tests ([d674aa1](https://github.com/sorenisanerd/gotty/commit/d674aa1)), closes [#13](https://github.com/sorenisanerd/gotty/issues/13)
* Fix warnings from Markdown linter ([aa86a34](https://github.com/sorenisanerd/gotty/commit/aa86a34))
* go fmt ([dcb153c](https://github.com/sorenisanerd/gotty/commit/dcb153c))
* Improve webtty test coverage ([f61763f](https://github.com/sorenisanerd/gotty/commit/f61763f))
* Make client request base64 encoding ([dd3603c](https://github.com/sorenisanerd/gotty/commit/dd3603c))
* Make sure we read the full message ([1eed97f](https://github.com/sorenisanerd/gotty/commit/1eed97f))
* Publish artifacts on push to master ([6c62ab7](https://github.com/sorenisanerd/gotty/commit/6c62ab7))
* Remove hterm ([163fd05](https://github.com/sorenisanerd/gotty/commit/163fd05))
* Run tests on push ([55674f1](https://github.com/sorenisanerd/gotty/commit/55674f1))
* Run tests on push to all branches ([679a324](https://github.com/sorenisanerd/gotty/commit/679a324))
* update go version in Dockerfile ([fd2fb99](https://github.com/sorenisanerd/gotty/commit/fd2fb99))
* Update js dependencies ([26fc412](https://github.com/sorenisanerd/gotty/commit/26fc412))
* Update xterm.js and other js libs ([81afdc7](https://github.com/sorenisanerd/gotty/commit/81afdc7)), closes [#18](https://github.com/sorenisanerd/gotty/issues/18)
* Use bootstrap components for up- and downloads ([7f05f2f](https://github.com/sorenisanerd/gotty/commit/7f05f2f))
* Use Go's built-in embed mechanism ([f66f0d0](https://github.com/sorenisanerd/gotty/commit/f66f0d0)), closes [#7](https://github.com/sorenisanerd/gotty/issues/7)
* feat(zmodem): Allow file uploads/downloads ([782991c](https://github.com/sorenisanerd/gotty/commit/782991c))
## v1.3.0
* Links in the tty are now clickable.
* Use WebGL for rendering by default.
* Ensure authentication (TLS or Basic auth) remain enabled even if some of the options are only given in config files Thanks, @devanlai!
* Fix typo in README.md Thanks, @prusnak!
* Add arm64/Linux build. Thanks for the suggestion, @nephaste!
## v1.2.0
* Pass BUILD\_OPTIONS to gox, too, so release artifacts have version info included.
* Update xterm.js 2.7.0 => 4.11.0
* Lots of clean up.
## v1.1.0
* Today I learned about Go's handling of versions, so re-releasing 2.1.0 as 1.1.0.
* Added path option. Thanks, @apatil!
## v2.1.0 (whoops)
* Use Go modules and update cli module import path. Thanks, @svanellewee!
* Fix typos. Thanks, @0xflotus, @RealCyGuy, @ygit, @Jason-Cooke and @fredster33!
* Fix printing of ipv6 addresses. Thanks, @Felixoid!
* Add Progressive Web App support. Thanks, @sehaas!
* Add instructions for GNU screen. Thanks, @Immortalin!
* Add Solaris support. Thanks, @fazalmajid!
* New maintainer: @sorenisanerd

210
README.md
View File

@ -1,27 +1,20 @@
# ![](https://raw.githubusercontent.com/sorenisanerd/gotty/master/resources/favicon.ico) GoTTY - Share your terminal as a web application
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-57-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
# ![](https://raw.githubusercontent.com/yudai/gotty/master/resources/favicon.png) GoTTY - Share your terminal as a web application
[![GitHub release](http://img.shields.io/github/release/sorenisanerd/gotty.svg?style=flat-square)][release]
[![GitHub release](http://img.shields.io/github/release/yudai/gotty.svg?style=flat-square)][release]
[![Wercker](http://img.shields.io/wercker/ci/55d0eeff7331453f0801982c.svg?style=flat-square)][wercker]
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)][license]
[![Maintainer streaming](https://twitch-status.soren.tools/sorencodes)][twitch]
[release]: https://github.com/sorenisanerd/gotty/releases
[license]: https://github.com/sorenisanerd/gotty/blob/master/LICENSE
[twitch]: https://twitch.tv/sorencodes
[release]: https://github.com/yudai/gotty/releases
[wercker]: https://app.wercker.com/project/bykey/03b91f441bebeda34f80e09a9f14126f
[license]: https://github.com/yudai/gotty/blob/master/LICENSE
GoTTY is a simple command line tool that turns your CLI tools into web applications.
[Original work](https://github.com/yudai/gotty) by [Iwasaki Yudai](https://github.com/yudai). There would be no GoTTY without him. ❤️
![Screenshot](https://raw.githubusercontent.com/sorenisanerd/gotty/master/screenshot.gif)
![Screenshot](https://raw.githubusercontent.com/yudai/gotty/master/screenshot.gif)
# Installation
## From release page
You can download the latest stable binary file from the [Releases](https://github.com/sorenisanerd/gotty/releases) page. Note that the release marked `Pre-release` is built for testing purpose, which can include unstable or breaking changes. Download a release marked [Latest release](https://github.com/sorenisanerd/gotty/releases/latest) for a stable build.
Download the latest stable binary file from the [Releases](https://github.com/yudai/gotty/releases) page. Note that the release marked `Pre-release` is built for testing purpose, which can include unstable or breaking changes. Download a release marked [Latest release](https://github.com/yudai/gotty/releases/latest) for a stabale build.
(Files named with `darwin_amd64` are for Mac OS X users)
@ -30,7 +23,7 @@ You can download the latest stable binary file from the [Releases](https://githu
You can install GoTTY with [Homebrew](http://brew.sh/) as well.
```sh
$ brew install sorenisanerd/gotty/gotty
$ brew install yudai/gotty/gotty
```
## `go get` Installation (Development)
@ -38,7 +31,7 @@ $ brew install sorenisanerd/gotty/gotty
If you have a Go language environment, you can install GoTTY with the `go get` command. However, this command builds a binary file from the latest master branch, which can include unstable or breaking changes. GoTTY requires go1.9 or later.
```sh
$ go get github.com/sorenisanerd/gotty
$ go get github.com/yudai/gotty
```
# Usage
@ -52,39 +45,39 @@ Run `gotty` with your preferred command as its arguments (e.g. `gotty top`).
By default, GoTTY starts a web server at port 8080. Open the URL on your web browser and you can see the running command as if it were running on your terminal.
## Options
```sh
--address value, -a value IP address to listen (default: "0.0.0.0") [$GOTTY_ADDRESS]
--port value, -p value Port number to liten (default: "8080") [$GOTTY_PORT]
--path value, -m value Base path (default: "/") [$GOTTY_PATH]
--permit-write, -w Permit clients to write to the TTY (BE CAREFUL) (default: false) [$GOTTY_PERMIT_WRITE]
--credential value, -c value Credential for Basic Authentication (ex: user:pass, default disabled) [$GOTTY_CREDENTIAL]
--random-url, -r Add a random string to the URL (default: false) [$GOTTY_RANDOM_URL]
--random-url-length value Random URL length (default: 8) [$GOTTY_RANDOM_URL_LENGTH]
--tls, -t Enable TLS/SSL (default: false) [$GOTTY_TLS]
--tls-crt value TLS/SSL certificate file path (default: "~/.gotty.crt") [$GOTTY_TLS_CRT]
--tls-key value TLS/SSL key file path (default: "~/.gotty.key") [$GOTTY_TLS_KEY]
--tls-ca-crt value TLS/SSL CA certificate file for client certifications (default: "~/.gotty.ca.crt") [$GOTTY_TLS_CA_CRT]
--index value Custom index.html file [$GOTTY_INDEX]
--title-format value Title format of browser window (default: "{{ .command }}@{{ .hostname }}") [$GOTTY_TITLE_FORMAT]
--reconnect Enable reconnection (default: false) [$GOTTY_RECONNECT]
--reconnect-time value Time to reconnect (default: 10) [$GOTTY_RECONNECT_TIME]
--max-connection value Maximum connection to gotty (default: 0) [$GOTTY_MAX_CONNECTION]
--once Accept only one client and exit on disconnection (default: false) [$GOTTY_ONCE]
--timeout value Timeout seconds for waiting a client(0 to disable) (default: 0) [$GOTTY_TIMEOUT]
--permit-arguments Permit clients to send command line arguments in URL (e.g. http://example.com:8080/?arg=AAA&arg=BBB) (default: false) [$GOTTY_PERMIT_ARGUMENTS]
--width value Static width of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_WIDTH]
--height value Static height of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_HEIGHT]
--ws-origin value A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default [$GOTTY_WS_ORIGIN]
--ws-query-args value Querystring arguments to append to the websocket instantiation [$GOTTY_WS_QUERY_ARGS]
--enable-webgl Enable WebGL renderer (default: true) [$GOTTY_ENABLE_WEBGL]
--close-signal value Signal sent to the command process when gotty close it (default: SIGHUP) (default: 1) [$GOTTY_CLOSE_SIGNAL]
--close-timeout value Time in seconds to force kill process after client is disconnected (default: -1) (default: -1) [$GOTTY_CLOSE_TIMEOUT]
--config value Config file path (default: "~/.gotty") [$GOTTY_CONFIG]
--help, -h show help (default: false)
--version, -v print the version (default: false)
```
--address value, -a value IP address to listen (default: "0.0.0.0") [$GOTTY_ADDRESS]
--port value, -p value Port number to liten (default: "8080") [$GOTTY_PORT]
--permit-write, -w Permit clients to write to the TTY (BE CAREFUL) [$GOTTY_PERMIT_WRITE]
--credential value, -c value Credential for Basic Authentication (ex: user:pass, default disabled) [$GOTTY_CREDENTIAL]
--random-url, -r Add a random string to the URL [$GOTTY_RANDOM_URL]
--random-url-length value Random URL length (default: 8) [$GOTTY_RANDOM_URL_LENGTH]
--tls, -t Enable TLS/SSL [$GOTTY_TLS]
--tls-crt value TLS/SSL certificate file path (default: "~/.gotty.crt") [$GOTTY_TLS_CRT]
--tls-key value TLS/SSL key file path (default: "~/.gotty.key") [$GOTTY_TLS_KEY]
--tls-ca-crt value TLS/SSL CA certificate file for client certifications (default: "~/.gotty.ca.crt") [$GOTTY_TLS_CA_CRT]
--index value Custom index.html file [$GOTTY_INDEX]
--title-format value Title format of browser window (default: "{{ .command }}@{{ .hostname }}") [$GOTTY_TITLE_FORMAT]
--reconnect Enable reconnection [$GOTTY_RECONNECT]
--reconnect-time value Time to reconnect (default: 10) [$GOTTY_RECONNECT_TIME]
--max-connection value Maximum connection to gotty (default: 0) [$GOTTY_MAX_CONNECTION]
--once Accept only one client and exit on disconnection [$GOTTY_ONCE]
--timeout value Timeout seconds for waiting a client(0 to disable) (default: 0) [$GOTTY_TIMEOUT]
--permit-arguments Permit clients to send command line arguments in URL or in Arguments HTTP header (e.g. http://example.com:8080/?arg=AAA&arg=BBB) [$GOTTY_PERMIT_ARGUMENTS]
--width value Static width of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_WIDTH]
--height value Static height of the screen, 0(default) means dynamically resize (default: 0) [$GOTTY_HEIGHT]
--ws-origin value A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default [$GOTTY_WS_ORIGIN]
--term value Terminal name to use on the browser, one of xterm or hterm. (default: "xterm") [$GOTTY_TERM]
--close-signal value Signal sent to the command process when gotty close it (default: SIGHUP) (default: 1) [$GOTTY_CLOSE_SIGNAL]
--close-timeout value Time in seconds to force kill process after client is disconnected (default: -1) (default: -1) [$GOTTY_CLOSE_TIMEOUT]
--config value Config file path (default: "~/.gotty") [$GOTTY_CONFIG]
--version, -v print the version
```
### Config File
You can customize default options and your terminal by providing a config file to the `gotty` command. GoTTY loads a profile file at `~/.gotty` by default when it exists.
You can customize default options and your terminal (hterm) by providing a config file to the `gotty` command. GoTTY loads a profile file at `~/.gotty` by default when it exists.
```
// Listen at port 9000 by default
@ -93,17 +86,23 @@ port = "9000"
// Enable TSL/SSL by default
enable_tls = true
// hterm preferences
// Smaller font and a little bit bluer background color
preferences {
font_size = 5
background_color = "rgb(16, 16, 32)"
}
```
See the [`.gotty`](https://github.com/sorenisanerd/gotty/blob/master/.gotty) file in this repository for the list of configuration options.
See the [`.gotty`](https://github.com/yudai/gotty/blob/master/.gotty) file in this repository for the list of configuration options.
### Security Options
By default, GoTTY doesn't allow clients to send any keystrokes or commands except terminal window resizing. When you want to permit clients to write input to the TTY, add the `-w` option. However, accepting input from remote clients is dangerous for most commands. When you need interaction with the TTY for some reasons, consider starting GoTTY with tmux or GNU Screen and run your command on it (see "Sharing with Multiple Clients" section for detail).
To restrict client access, you can use the `-c` option to enable the basic authentication. With this option, clients need to input the specified username and password to connect to the GoTTY server. Note that the credentials will be transmitted between the server and clients in plain text. For more strict authentication, consider the SSL/TLS client certificate authentication described below.
To restrict client access, you can use the `-c` option to enable the basic authentication. With this option, clients need to input the specified username and password to connect to the GoTTY server. Note that the credentical will be transmitted between the server and clients in plain text. For more strict authentication, consider the SSL/TLS client certificate authentication described below.
The `-r` option is a little bit more casual way to restrict access. With this option, GoTTY generates a random URL so that only people who know the URL can get access to the server.
The `-r` option is a little bit casualer way to restrict access. With this option, GoTTY generates a random URL so that only people who know the URL can get access to the server.
All traffic between the server and clients are NOT encrypted by default. When you send secret information through GoTTY, we strongly recommend you use the `-t` option which enables TLS/SSL on the session. By default, GoTTY loads the crt and key files placed at `~/.gotty.crt` and `~/.gotty.key`. You can overwrite these file paths with the `--tls-crt` and `--tls-key` options. When you need to generate a self-signed certification file, you can use the `openssl` command.
@ -118,9 +117,7 @@ For additional security, you can use the SSL/TLS client certificate authenticati
## Sharing with Multiple Clients
GoTTY starts a new process with the given command when a new client connects to the server. This means users cannot share a single terminal with others by default. However, you can use terminal multiplexers for sharing a single process with multiple clients.
### Screen
After installing GNU screen, start a new session with `screen -S name-for-session` and connect to it with gotty in another terminal window/tab through `screen -x name-for-session`. All commands and activities being done in the first terminal tab/window will now be broadcasted by gotty.
### Tmux
For example, you can start a new tmux session named `gotty` with `top` command by the command below.
```sh
@ -154,13 +151,22 @@ $ gotty -w docker run -it --rm busybox
## Development
You can build a binary by simply running `make`. go1.16 is required.
You can build a binary using the following commands. Windows is not supported now. go1.9 is required.
```sh
# Install tools
go get github.com/jteeuwen/go-bindata/...
go get github.com/tools/godep
# Build
make
```
To build the frontend part (JS files and other static files), you need `npm`.
## Architecture
GoTTY uses [xterm.js](https://xtermjs.org/) to run a JavaScript based terminal on web browsers. GoTTY itself provides a websocket server that simply relays output from the TTY to clients and receives input from clients and forwards it to the TTY. This xterm + websocket idea is inspired by [Wetty](https://github.com/krishnasrinivas/wetty).
GoTTY uses [xterm.js](https://xtermjs.org/) and [hterm](https://groups.google.com/a/chromium.org/forum/#!forum/chromium-hterm) to run a JavaScript based terminal on web browsers. GoTTY itself provides a websocket server that simply relays output from the TTY to clients and receives input from clients and forwards it to the TTY. This hterm + websocket idea is inspired by [Wetty](https://github.com/krishnasrinivas/wetty).
## Alternatives
@ -183,95 +189,3 @@ GoTTY uses [xterm.js](https://xtermjs.org/) to run a JavaScript based terminal o
# License
The MIT License
# Contributors
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://yudai.arielworks.com/"><img src="https://avatars.githubusercontent.com/u/33192?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Iwasaki Yudai</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=yudai" title="Code">💻</a></td>
<td align="center"><a href="http://linux2go.dk/"><img src="https://avatars.githubusercontent.com/u/160090?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Soren L. Hansen</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Asorenisanerd" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/uovobw"><img src="https://avatars.githubusercontent.com/u/1194751?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andrea Lusuardi</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=uovobw" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/moul"><img src="https://avatars.githubusercontent.com/u/94029?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Manfred Touron</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=moul" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/svanellewee"><img src="https://avatars.githubusercontent.com/u/1567439?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stephan</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=svanellewee" title="Code">💻</a></td>
<td align="center"><a href="https://fr.linkedin.com/in/quentinperez"><img src="https://avatars.githubusercontent.com/u/3081204?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Quentin Perez</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=QuentinPerez" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jizhilong"><img src="https://avatars.githubusercontent.com/u/816618?v=4?s=100" width="100px;" alt=""/><br /><sub><b>jzl</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jizhilong" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://majid.info/"><img src="https://avatars.githubusercontent.com/u/331198?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fazal Majid</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=fazalmajid" title="Code">💻</a></td>
<td align="center"><a href="https://narrationbox.com/"><img src="https://avatars.githubusercontent.com/u/7126128?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Immortalin</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Immortalin" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/freakhill"><img src="https://avatars.githubusercontent.com/u/916582?v=4?s=100" width="100px;" alt=""/><br /><sub><b>freakhill</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=freakhill" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/0xflotus"><img src="https://avatars.githubusercontent.com/u/26602940?v=4?s=100" width="100px;" alt=""/><br /><sub><b>0xflotus</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=0xflotus" title="Code">💻</a></td>
<td align="center"><a href="https://andy.blog/"><img src="https://avatars.githubusercontent.com/u/52292?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andy Skelton</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=skeltoac" title="Code">💻</a></td>
<td align="center"><a href="https://twitter.com/artdevjs"><img src="https://avatars.githubusercontent.com/u/7567983?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Artem Medvedev</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=artdevjs" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/blakejennings"><img src="https://avatars.githubusercontent.com/u/1976331?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Blake Jennings</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=blakejennings" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/jensenbox"><img src="https://avatars.githubusercontent.com/u/189265?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christian Jensen</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jensenbox" title="Code">💻</a></td>
<td align="center"><a href="https://wilk.tech/"><img src="https://avatars.githubusercontent.com/u/9367803?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Christopher Wilkinson</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=TechWilk" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/RealCyGuy"><img src="https://avatars.githubusercontent.com/u/54488650?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Cyrus</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=RealCyGuy" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/dehorsley"><img src="https://avatars.githubusercontent.com/u/3401668?v=4?s=100" width="100px;" alt=""/><br /><sub><b>David Horsley</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=dehorsley" title="Code">💻</a></td>
<td align="center"><a href="https://jasoncooke.dev/"><img src="https://avatars.githubusercontent.com/u/5185660?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jason Cooke</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Jason-Cooke" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/DenKoren"><img src="https://avatars.githubusercontent.com/u/3419381?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Denis Korenevskiy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=DenKoren" title="Code">💻</a></td>
<td align="center"><a href="https://www.stucchi.ch/"><img src="https://avatars.githubusercontent.com/u/1331438?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Massimiliano Stucchi</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=stucchimax" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://www.linkedin.com/in/felixoid/"><img src="https://avatars.githubusercontent.com/u/3025537?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Mikhail f. Shiryaev</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=Felixoid" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/guywithnose"><img src="https://avatars.githubusercontent.com/u/1059169?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Robert Bittle</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=guywithnose" title="Code">💻</a></td>
<td align="center"><a href="https://deebas.com/"><img src="https://avatars.githubusercontent.com/u/283482?v=4?s=100" width="100px;" alt=""/><br /><sub><b>sebastian haas</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=sehaas" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/shoz"><img src="https://avatars.githubusercontent.com/u/225194?v=4?s=100" width="100px;" alt=""/><br /><sub><b>shoji</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=shoz" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/tsl0922"><img src="https://avatars.githubusercontent.com/u/1680515?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shuanglei Tao</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=tsl0922" title="Code">💻</a></td>
<td align="center"><a href="https://gitter.im/"><img src="https://avatars.githubusercontent.com/u/8518239?v=4?s=100" width="100px;" alt=""/><br /><sub><b>The Gitter Badger</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=gitter-badger" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/xinsnake"><img src="https://avatars.githubusercontent.com/u/1287677?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jacob Zhou</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=xinsnake" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/zyfdegh"><img src="https://avatars.githubusercontent.com/u/7880217?v=4?s=100" width="100px;" alt=""/><br /><sub><b>zyfdegh</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=zyfdegh" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/fredster33"><img src="https://avatars.githubusercontent.com/u/64927044?v=4?s=100" width="100px;" alt=""/><br /><sub><b>fredster33</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=fredster33" title="Code">💻</a></td>
<td align="center"><a href="https://mattn.kaoriya.net/"><img src="https://avatars.githubusercontent.com/u/10111?v=4?s=100" width="100px;" alt=""/><br /><sub><b>mattn</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=mattn" title="Code">💻</a></td>
<td align="center"><a href="https://www.shingt.com/"><img src="https://avatars.githubusercontent.com/u/1391330?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Shinichi Goto</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=shingt" title="Code">💻</a></td>
<td align="center"><a href="https://twitter.com/_yogeshsingh"><img src="https://avatars.githubusercontent.com/u/8512357?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ygit</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=ygit" title="Code">💻</a></td>
<td align="center"><a href="http://forum.cachem.fr/viewforum.php?f=21"><img src="https://avatars.githubusercontent.com/u/3392684?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Stéphane</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Anephaste" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://rusnak.io/"><img src="https://avatars.githubusercontent.com/u/42201?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Pavol Rusnak</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aprusnak" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/devanlai"><img src="https://avatars.githubusercontent.com/u/1348448?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Devan Lai</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=devanlai" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jkandasa"><img src="https://avatars.githubusercontent.com/u/1004403?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jeeva Kandasamy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=jkandasa" title="Code">💻</a></td>
<td align="center"><a href="https://twitch.tv/iamhardliner"><img src="https://avatars.githubusercontent.com/u/2937272?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Steve Biedermann</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/commits?author=hardliner66" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/xgdgsc"><img src="https://avatars.githubusercontent.com/u/1189869?v=4?s=100" width="100px;" alt=""/><br /><sub><b>xgdgsc</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Axgdgsc" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/flechaig"><img src="https://avatars.githubusercontent.com/u/10887132?v=4?s=100" width="100px;" alt=""/><br /><sub><b>flechaig</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aflechaig" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/Fan-SJ"><img src="https://avatars.githubusercontent.com/u/49977708?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Fan-SJ</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AFan-SJ" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/dmartin"><img src="https://avatars.githubusercontent.com/u/1657652?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Dustin Martin</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Admartin" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://ahmet.dev/"><img src="https://avatars.githubusercontent.com/u/159209?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ahmet Alp Balkan</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aahmetb" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/CoconutMacaroon"><img src="https://avatars.githubusercontent.com/u/45187468?v=4?s=100" width="100px;" alt=""/><br /><sub><b>CoconutMacaroon</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ACoconutMacaroon" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.dannyben.com/"><img src="https://avatars.githubusercontent.com/u/2405099?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Danny Ben Shitrit</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ADannyBen" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/George-NG"><img src="https://avatars.githubusercontent.com/u/28577165?v=4?s=100" width="100px;" alt=""/><br /><sub><b>George-NG</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AGeorge-NG" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/ghthor"><img src="https://avatars.githubusercontent.com/u/160298?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Will Owens</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aghthor" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://jpillora.com/"><img src="https://avatars.githubusercontent.com/u/633843?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jaime Pillora</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Ajpillora" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/kaisawind"><img src="https://avatars.githubusercontent.com/u/4010613?v=4?s=100" width="100px;" alt=""/><br /><sub><b>kaisawind</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Akaisawind" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/linyinli"><img src="https://avatars.githubusercontent.com/u/42955482?v=4?s=100" width="100px;" alt=""/><br /><sub><b>linyinli</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Alinyinli" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/LucaMarconato"><img src="https://avatars.githubusercontent.com/u/2664412?v=4?s=100" width="100px;" alt=""/><br /><sub><b>LucaMarconato</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ALucaMarconato" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://audiobox.fm/"><img src="https://avatars.githubusercontent.com/u/12844?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kain</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Amasterkain" title="Bug reports">🐛</a></td>
<td align="center"><a href="http://duro.me/"><img src="https://avatars.githubusercontent.com/u/1498061?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Andi Andreas</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3ANexuist" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/qigj"><img src="https://avatars.githubusercontent.com/u/56585735?v=4?s=100" width="100px;" alt=""/><br /><sub><b>qigj</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Aqigj" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/shuaiyy"><img src="https://avatars.githubusercontent.com/u/19821321?v=4?s=100" width="100px;" alt=""/><br /><sub><b>shuaiyy</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Ashuaiyy" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/v20z"><img src="https://avatars.githubusercontent.com/u/2884824?v=4?s=100" width="100px;" alt=""/><br /><sub><b>v20z</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3Av20z" title="Bug reports">🐛</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/Yann-Qiu"><img src="https://avatars.githubusercontent.com/u/56961747?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Yanfeng Qiu</b></sub></a><br /><a href="https://github.com/sorenisanerd/gotty/issues?q=author%3AYann-Qiu" title="Bug reports">🐛</a></td>
</tr>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!

View File

@ -1,6 +0,0 @@
/^## Options/,/^### Config File/ {
/^\(`\|#\)/!d # Delete any line not beginning with ` or #
/```sh/ { # Shove options.txt.tmp in after ```sh
r options.txt.tmp
}
}

View File

@ -4,7 +4,7 @@ import (
"syscall"
"time"
"github.com/sorenisanerd/gotty/server"
"github.com/yudai/gotty/server"
)
type Options struct {
@ -37,12 +37,12 @@ func (factory *Factory) Name() string {
return "local command"
}
func (factory *Factory) New(params map[string][]string, headers map[string][]string) (server.Slave, error) {
func (factory *Factory) New(params map[string][]string) (server.Slave, error) {
argv := make([]string, len(factory.argv))
copy(argv, factory.argv)
if params["arg"] != nil && len(params["arg"]) > 0 {
argv = append(argv, params["arg"]...)
}
return New(factory.command, argv, headers, factory.opts...)
return New(factory.command, argv, factory.opts...)
}

View File

@ -3,11 +3,11 @@ package localcommand
import (
"os"
"os/exec"
"strings"
"syscall"
"time"
"unsafe"
"github.com/creack/pty"
"github.com/kr/pty"
"github.com/pkg/errors"
)
@ -28,22 +28,9 @@ type LocalCommand struct {
ptyClosed chan struct{}
}
func New(command string, argv []string, headers map[string][]string, options ...Option) (*LocalCommand, error) {
func New(command string, argv []string, options ...Option) (*LocalCommand, error) {
cmd := exec.Command(command, argv...)
cmd.Env = append(os.Environ(), "TERM=xterm-256color")
// Combine headers into key=value pairs to set as env vars
// Prefix the headers with "http_" so we don't overwrite any other env vars
// which potentially has the same name and to bring these closer to what
// a (F)CGI server would proxy to a backend service
// Replace hyphen with underscore and make them all upper case
for key, values := range headers {
h := "HTTP_" + strings.Replace(strings.ToUpper(key), "-", "_", -1) + "=" + strings.Join(values, ",")
// log.Printf("Adding header: %s", h)
cmd.Env = append(cmd.Env, h)
}
pty, err := pty.Start(cmd)
if err != nil {
// todo close cmd?
@ -112,15 +99,25 @@ func (lcmd *LocalCommand) WindowTitleVariables() map[string]interface{} {
}
func (lcmd *LocalCommand) ResizeTerminal(width int, height int) error {
window := pty.Winsize{
Rows: uint16(height),
Cols: uint16(width),
X: 0,
Y: 0,
window := struct {
row uint16
col uint16
x uint16
y uint16
}{
uint16(height),
uint16(width),
0,
0,
}
err := pty.Setsize(lcmd.pty, &window)
if err != nil {
return err
_, _, errno := syscall.Syscall(
syscall.SYS_IOCTL,
lcmd.pty.Fd(),
syscall.TIOCSWINSZ,
uintptr(unsafe.Pointer(&window)),
)
if errno != 0 {
return errno
} else {
return nil
}

View File

@ -1,88 +0,0 @@
package localcommand
import (
"bytes"
"reflect"
"testing"
"time"
)
func TestNewFactory(t *testing.T) {
factory, err := NewFactory("/bin/false", []string{}, &Options{CloseSignal: 123, CloseTimeout: 321})
if err != nil {
t.Errorf("NewFactory() returned error")
return
}
if factory.command != "/bin/false" {
t.Errorf("factory.command = %v, expected %v", factory.command, "/bin/false")
}
if !reflect.DeepEqual(factory.argv, []string{}) {
t.Errorf("factory.argv = %v, expected %v", factory.argv, []string{})
}
if !reflect.DeepEqual(factory.options, &Options{CloseSignal: 123, CloseTimeout: 321}) {
t.Errorf("factory.options = %v, expected %v", factory.options, &Options{})
}
slave, _ := factory.New(nil, nil)
lcmd := slave.(*LocalCommand)
if lcmd.closeSignal != 123 {
t.Errorf("lcmd.closeSignal = %v, expected %v", lcmd.closeSignal, 123)
}
if lcmd.closeTimeout != time.Second*321 {
t.Errorf("lcmd.closeTimeout = %v, expected %v", lcmd.closeTimeout, time.Second*321)
}
}
func TestFactoryNew(t *testing.T) {
factory, err := NewFactory("/bin/cat", []string{}, &Options{})
if err != nil {
t.Errorf("NewFactory() returned error")
return
}
slave, err := factory.New(nil, nil)
if err != nil {
t.Errorf("factory.New() returned error")
return
}
writeBuf := []byte("foobar\n")
n, err := slave.Write(writeBuf)
if err != nil {
t.Errorf("write() failed: %v", err)
return
}
if n != 7 {
t.Errorf("Unexpected write length. n = %d, expected n = %d", n, 7)
return
}
// Local echo is on, so we get the output twice:
// Once because we're "typing" it, and once more
// repeated back to us by `cat`. Also, \r\n
// because we're a terminal.
expectedBuf := []byte("foobar\r\nfoobar\r\n")
readBuf := make([]byte, 1024)
var totalRead int
for totalRead < 16 {
n, err = slave.Read(readBuf[totalRead:])
if err != nil {
t.Errorf("read() failed: %v", err)
return
}
totalRead += n
}
if totalRead != 16 {
t.Errorf("Unexpected read length. totalRead = %d, expected totalRead = %d", totalRead, 16)
return
}
if !bytes.Equal(readBuf[:totalRead], expectedBuf) {
t.Errorf("unexpected output from slave: got %v, expected %v", readBuf[:totalRead], expectedBuf)
}
err = slave.Close()
if err != nil {
t.Errorf("close() failed: %v", err)
return
}
}

View File

@ -1,8 +0,0 @@
//go:build !dev
package bindata
import "embed"
//go:embed static/*
var Fs embed.FS

View File

@ -1,28 +0,0 @@
//go:build dev
package bindata
import (
"io"
"io/fs"
"os"
)
type GottyFS struct {
fs.FS
}
var Fs GottyFS
func (gfs *GottyFS) ReadFile(name string) ([]byte, error) {
fp, err := gfs.Open(name)
if err != nil {
return nil, err
}
return io.ReadAll(fp)
}
func init() {
Fs = GottyFS{os.DirFS("bindata")}
}

View File

@ -1,13 +0,0 @@
html, body, #terminal {
background: black;
height: 100%;
width: 100%;
padding: 0%;
margin: 0%;
}
.progress .progress-bar {
transition: unset;
transition-duration: 0.1s;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

View File

@ -1,209 +0,0 @@
/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
* @license MIT
*
* 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.
*
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
*/
/**
* Default styles for xterm.js
*/
.xterm {
cursor: text;
position: relative;
user-select: none;
-ms-user-select: none;
-webkit-user-select: none;
}
.xterm.focus,
.xterm:focus {
outline: none;
}
.xterm .xterm-helpers {
position: absolute;
top: 0;
/**
* The z-index of the helpers must be higher than the canvases in order for
* IMEs to appear on top.
*/
z-index: 5;
}
.xterm .xterm-helper-textarea {
padding: 0;
border: 0;
margin: 0;
/* Move textarea out of the screen to the far left, so that the cursor is not visible */
position: absolute;
opacity: 0;
left: -9999em;
top: 0;
width: 0;
height: 0;
z-index: -5;
/** Prevent wrapping so the IME appears against the textarea at the correct position */
white-space: nowrap;
overflow: hidden;
resize: none;
}
.xterm .composition-view {
/* TODO: Composition position got messed up somewhere */
background: #000;
color: #FFF;
display: none;
position: absolute;
white-space: nowrap;
z-index: 1;
}
.xterm .composition-view.active {
display: block;
}
.xterm .xterm-viewport {
/* On OS X this is required in order for the scroll bar to appear fully opaque */
background-color: #000;
overflow-y: scroll;
cursor: default;
position: absolute;
right: 0;
left: 0;
top: 0;
bottom: 0;
}
.xterm .xterm-screen {
position: relative;
}
.xterm .xterm-screen canvas {
position: absolute;
left: 0;
top: 0;
}
.xterm .xterm-scroll-area {
visibility: hidden;
}
.xterm-char-measure-element {
display: inline-block;
visibility: hidden;
position: absolute;
top: 0;
left: -9999em;
line-height: normal;
}
.xterm.enable-mouse-events {
/* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */
cursor: default;
}
.xterm.xterm-cursor-pointer,
.xterm .xterm-cursor-pointer {
cursor: pointer;
}
.xterm.column-select.focus {
/* Column selection mode */
cursor: crosshair;
}
.xterm .xterm-accessibility,
.xterm .xterm-message {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 10;
color: transparent;
pointer-events: none;
}
.xterm .live-region {
position: absolute;
left: -9999px;
width: 1px;
height: 1px;
overflow: hidden;
}
.xterm-dim {
/* Dim should not apply to background, so the opacity of the foreground color is applied
* explicitly in the generated class and reset to 1 here */
opacity: 1 !important;
}
.xterm-underline-1 { text-decoration: underline; }
.xterm-underline-2 { text-decoration: double underline; }
.xterm-underline-3 { text-decoration: wavy underline; }
.xterm-underline-4 { text-decoration: dotted underline; }
.xterm-underline-5 { text-decoration: dashed underline; }
.xterm-overline {
text-decoration: overline;
}
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; }
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; }
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; }
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; }
.xterm-strikethrough {
text-decoration: line-through;
}
.xterm-screen .xterm-decoration-container .xterm-decoration {
z-index: 6;
position: absolute;
}
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer {
z-index: 7;
}
.xterm-decoration-overview-ruler {
z-index: 8;
position: absolute;
top: 0;
right: 0;
pointer-events: none;
}
.xterm-decoration-top {
z-index: 2;
position: relative;
}

View File

@ -1,19 +0,0 @@
.terminal {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
}
.xterm-overlay {
font-family: "DejaVu Sans Mono", "Everson Mono", FreeMono, Menlo, Terminal, monospace, "Apple Symbols";
border-radius: 15px;
font-size: xx-large;
color: black;
background: white;
opacity: 0.75;
padding: 0.2em 0.5em 0.2em 0.5em;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
user-select: none;
transition: opacity 180ms ease-in;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 708.4149 708.41411"
height="708.41412"
width="708.41492"
xml:space="preserve"
id="svg2"
version="1.1"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
id="clipPath18"
clipPathUnits="userSpaceOnUse"><path
id="path16"
d="M 0,2000 H 2000 V 0 H 0 Z" /></clipPath></defs><g
transform="matrix(1.3333333,0,0,-1.3333333,-979.12558,1687.5405)"
id="g10"><g
id="g12"><g
clip-path="url(#clipPath18)"
id="g14"><g
transform="translate(772.1414,1265.6554)"
id="g20"><path
id="path22"
style="fill:#de3c28;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -20.875,0 -37.797,-16.922 -37.797,-37.797 v -126.348 -25.917 -212.342 L 345.882,0 Z" /></g><g
transform="translate(956.8504,734.3448)"
id="g24"><path
id="path26"
style="fill:#af1419;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h 260.209 c 26.839,0 48.596,21.757 48.596,48.596 v 275.281 z" /></g><g
transform="translate(1265.6552,1075.5929)"
id="g28"><path
id="path30"
style="fill:#db0918;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 25.918 126.348 c 0,20.875 -16.922,37.796 -37.796,37.796 h -109.836 l -383.679,-402.404 v -80.31 c 0,-26.839 21.757,-48.596 48.596,-48.596 h 173.91 L 0,-17.371 Z" /></g><g
transform="translate(1169.2147,909.6954)"
id="g32"><path
id="path34"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h -138.227 c -9.129,0 -16.528,7.4 -16.528,16.529 0,9.128 7.399,16.529 16.528,16.529 H 0 c 9.129,0 16.528,-7.401 16.528,-16.529 C 16.528,7.4 9.129,0 0,0" /></g><g
transform="translate(898.8318,1033.5314)"
id="g36"><path
id="path38"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c 2.86,-0.72 5.65,-1.45 8.37,-2.2 -0.63,-8.56 -7.76,-15.3 -16.479,-15.3 -9.13,0 -16.531,7.4 -16.531,16.53 v 8.54 c 1.861,-0.83 3.72,-1.549 5.601,-2.15 C -15.199,4.18 -8.85,2.37 0,0" /></g><g
transform="translate(907.2527,1150.7814)"
id="g40"><path
id="path42"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v -65.81 c -4.45,1.59 -9.98,2.38 -16.601,2.38 -6.21,0 -11.7,-0.88 -16.46,-2.64 V 0 c 0,9.13 7.401,16.53 16.531,16.53 C -7.4,16.53 0,9.13 0,0" /></g><g
transform="translate(874.1922,868.8272)"
id="g44"><path
id="path46"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 65.811 c 4.45,-1.59 9.98,-2.38 16.601,-2.38 6.21,0 11.699,0.88 16.46,2.639 V 0 C 33.061,-9.13 25.66,-16.529 16.53,-16.529 7.4,-16.529 0,-9.13 0,0" /></g><g
transform="translate(966.6326,994.1915)"
id="g48"><path
id="path50"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -3.53,7.28 -8.45,13.3 -14.75,18.06 -6.301,4.76 -13.95,8.8 -22.94,12.14 -6.661,2.47 -13.911,4.78 -21.741,6.94 -2.719,0.75 -5.509,1.48 -8.37,2.2 -8.849,2.37 -15.199,4.18 -19.039,5.42 -1.881,0.6 -3.74,1.32 -5.6,2.15 -1.951,0.87 -3.88,1.87 -5.8,2.99 -3.76,2.19 -6.71,4.81 -8.861,7.85 -2.139,3.05 -3.219,6.67 -3.219,10.86 0,6.75 3.16,12.54 9.46,17.34 2.49,1.9 5.299,3.43 8.42,4.57 4.759,1.76 10.25,2.64 16.46,2.64 6.62,0 12.15,-0.79 16.6,-2.38 3.01,-1.05 5.52,-2.48 7.54,-4.26 5.01,-4.42 9.3,-10.59 12.88,-18.49 2.77,-5.52 5.34,-9.49 7.71,-11.92 2.37,-2.43 5.84,-3.64 10.399,-3.64 5.011,0 9.191,2.02 12.54,6.07 3.351,4.04 5.031,8.59 5.031,13.63 0,5.52 -1.34,11.19 -4.021,17 -2.689,5.8 -6.939,11.35 -12.75,16.63 -5.809,5.28 -13.119,9.52 -21.929,12.71 -5.23,1.89 -11.031,3.22 -17.4,3.99 -4.37,0.53 -9.011,0.79 -13.921,0.79 -6.779,0 -13.159,-0.48 -19.139,-1.45 -7.361,-1.19 -14.121,-3.11 -20.29,-5.76 -11.18,-4.81 -19.72,-11.69 -25.621,-20.63 -5.899,-8.95 -8.849,-19.18 -8.849,-30.7 0,-12.09 2.79,-22.2 8.38,-30.34 5.59,-8.14 13.15,-14.56 22.67,-19.28 9.52,-4.71 21.349,-8.83 35.48,-12.35 10.55,-2.57 18.98,-4.99 25.279,-7.28 6.301,-2.28 11.441,-5.59 15.42,-9.92 3.981,-4.33 5.971,-9.97 5.971,-16.92 0,-8.76 -3.69,-16.06 -11.061,-21.92 -7.379,-5.85 -16.969,-8.78 -28.769,-8.78 -8.59,0 -15.521,1.45 -20.79,4.36 -5.28,2.9 -9.37,6.59 -12.28,11.06 -2.901,4.47 -5.611,10.04 -8.111,16.71 -2.059,5.61 -4.54,9.85 -7.449,12.7 -2.9,2.86 -6.46,4.29 -10.66,4.29 -5.181,0 -9.45,-1.84 -12.811,-5.5 -3.349,-3.66 -5.029,-8.07 -5.029,-13.21 0,-8.85 2.8,-17.96 8.39,-27.34 5.58,-9.38 12.849,-16.87 21.79,-22.49 12.61,-7.8 28.61,-11.7 48.019,-11.7 16.181,0 30.181,2.85 41.981,8.56 11.809,5.71 20.769,13.61 26.9,23.7 6.119,10.09 9.18,21.47 9.18,34.129 C 5.3,-16.21 3.54,-7.28 0,0" /></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -1,22 +0,0 @@
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" href="favicon.ico">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/xterm.css" />
<link rel="stylesheet" href="./css/xterm_customize.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="terminal"></div>
<script src="./auth_token.js"></script>
<script src="./config.js"></script>
<script src="./js/gotty.js"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -1,7 +0,0 @@
/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */

File diff suppressed because one or more lines are too long

View File

@ -1,649 +0,0 @@
@popperjs/core
MIT
The MIT License (MIT)
Copyright (c) 2019 Federico Zivolo
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.
bootstrap
MIT
The MIT License (MIT)
Copyright (c) 2011-2023 The Bootstrap Authors
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.
crc-32
Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (C) 2014-present SheetJS LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
css-loader
MIT
Copyright JS Foundation and other 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.
jsx-runtime
MIT
The MIT License (MIT)
Copyright (c) 2015-present Jason Miller
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.
preact
MIT
The MIT License (MIT)
Copyright (c) 2015-present Jason Miller
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.
style-loader
MIT
Copyright JS Foundation and other 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.
xterm
MIT
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
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.
xterm-addon-fit
MIT
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
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.
xterm-addon-web-links
MIT
Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js)
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.
xterm-addon-webgl
MIT
Copyright (c) 2018, The xterm.js authors (https://github.com/xtermjs/xterm.js)
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.
zmodem.js
Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,15 +0,0 @@
{
"short_name": "{{ .title }}",
"name": "{{ .title }}",
"start_url": "./",
"icons": [
{
"src": "./icon_192.png",
"type": "image/png",
"sizes": "192x192"
}
],
"display": "minimal-ui",
"theme_color": "#000000",
"background_color": "#000000"
}

3623
favicon.ai

File diff suppressed because one or more lines are too long

BIN
favicon.psd Executable file

Binary file not shown.

22
go.mod
View File

@ -1,22 +0,0 @@
module github.com/sorenisanerd/gotty
go 1.20
require (
github.com/NYTimes/gziphandler v1.1.1
github.com/creack/pty v1.1.11
github.com/fatih/structs v1.1.0
github.com/gorilla/websocket v1.4.2
github.com/pkg/errors v0.9.1
github.com/urfave/cli/v2 v2.3.0
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552
)
require (
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/russross/blackfriday/v2 v2.0.1 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
golang.org/x/sys v0.1.0 // indirect
)

36
go.sum
View File

@ -1,36 +0,0 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552 h1:tjsK9T2IA3d2FFNxzDP7AJf+EXhyuPd7PB4Z2HrtAoc=
github.com/yudai/hcl v0.0.0-20151013225006-5fa2393b3552/go.mod h1:hg0ZaCmQL3rze1cH8Fh2g0a9q8vQs0uN8ESpePEwSEw=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

19
help.go Normal file
View File

@ -0,0 +1,19 @@
package main
var helpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} [options] <command> [<arguments...>]
VERSION:
{{.Version}}{{if or .Author .Email}}
AUTHOR:{{if .Author}}
{{.Author}}{{if .Email}} - <{{.Email}}>{{end}}{{else}}
{{.Email}}{{end}}{{end}}
OPTIONS:
{{range .Flags}}{{.}}
{{end}}
`

88
js/dist/gotty-bundle.js vendored Normal file

File diff suppressed because one or more lines are too long

24
js/dist/hterm.d.ts vendored Normal file
View File

@ -0,0 +1,24 @@
import * as bare from "libapps";
export declare class Hterm {
elem: HTMLElement;
term: bare.hterm.Terminal;
io: bare.hterm.IO;
columns: number;
rows: number;
message: string;
constructor(elem: HTMLElement);
info(): {
columns: number;
rows: number;
};
output(data: string): void;
showMessage(message: string, timeout: number): void;
removeMessage(): void;
setWindowTitle(title: string): void;
setPreferences(value: object): void;
onInput(callback: (input: string) => void): void;
onResize(callback: (colmuns: number, rows: number) => void): void;
deactivate(): void;
reset(): void;
close(): void;
}

0
js/dist/main.d.ts vendored Normal file
View File

17
js/dist/websocket.d.ts vendored Normal file
View File

@ -0,0 +1,17 @@
export declare class ConnectionFactory {
url: string;
protocols: string[];
constructor(url: string, protocols: string[]);
create(): Connection;
}
export declare class Connection {
bare: WebSocket;
constructor(url: string, protocols: string[]);
open(): void;
close(): void;
send(data: string): void;
isOpen(): boolean;
onOpen(callback: () => void): void;
onReceive(callback: (data: string) => void): void;
onClose(callback: () => void): void;
}

48
js/dist/webtty.d.ts vendored Normal file
View File

@ -0,0 +1,48 @@
export declare const protocols: string[];
export declare const msgInputUnknown = "0";
export declare const msgInput = "1";
export declare const msgPing = "2";
export declare const msgResizeTerminal = "3";
export declare const msgUnknownOutput = "0";
export declare const msgOutput = "1";
export declare const msgPong = "2";
export declare const msgSetWindowTitle = "3";
export declare const msgSetPreferences = "4";
export declare const msgSetReconnect = "5";
export interface Terminal {
info(): {
columns: number;
rows: number;
};
output(data: string): void;
showMessage(message: string, timeout: number): void;
removeMessage(): void;
setWindowTitle(title: string): void;
setPreferences(value: object): void;
onInput(callback: (input: string) => void): void;
onResize(callback: (colmuns: number, rows: number) => void): void;
reset(): void;
deactivate(): void;
close(): void;
}
export interface Connection {
open(): void;
close(): void;
send(data: string): void;
isOpen(): boolean;
onOpen(callback: () => void): void;
onReceive(callback: (data: string) => void): void;
onClose(callback: () => void): void;
}
export interface ConnectionFactory {
create(): Connection;
}
export declare class WebTTY {
term: Terminal;
connectionFactory: ConnectionFactory;
args: string;
authToken: string;
reconnect: number;
constructor(term: Terminal, connectionFactory: ConnectionFactory, args: string, authToken: string);
open(): () => void;
}

26
js/dist/xterm.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
import * as bare from "xterm";
import { lib } from "libapps";
export declare class Xterm {
elem: HTMLElement;
term: bare;
resizeListener: () => void;
decoder: lib.UTF8Decoder;
message: HTMLElement;
messageTimeout: number;
messageTimer: number;
constructor(elem: HTMLElement);
info(): {
columns: number;
rows: number;
};
output(data: string): void;
showMessage(message: string, timeout: number): void;
removeMessage(): void;
setWindowTitle(title: string): void;
setPreferences(value: object): void;
onInput(callback: (input: string) => void): void;
onResize(callback: (colmuns: number, rows: number) => void): void;
deactivate(): void;
reset(): void;
close(): void;
}

6308
js/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,13 @@
{
"name": "gotty",
"version": "1.4.0",
"private": true,
"devDependencies": {
"@types/bootstrap": "^5.2.10",
"compression-webpack-plugin": "^9.2.0",
"license-loader": "^0.5.0",
"license-webpack-plugin": "^4.0.2",
"purgecss": "^4.1.3",
"sass": "^1.70.0",
"sass-loader": "^12.6.0",
"terser-webpack-plugin": "^5.3.10",
"ts-loader": "^8.4.0",
"typescript": "^4.9.5",
"webpack": "^5.90.1",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.15.1"
"ts-loader": "^2.0.3",
"typescript": "^2.3.2",
"uglifyjs-webpack-plugin": "^1.0.0-beta.2",
"webpack": "^2.5.1"
},
"dependencies": {
"@popperjs/core": "^2.11.8",
"bootstrap": "^5.3.2",
"css-loader": "^5.2.7",
"debounce": "^1.2.1",
"preact": "^10.19.4",
"react-bootstrap": "^2.10.1",
"style-loader": "^2.0.0",
"xterm": "^5.3.0",
"xterm-addon-fit": "^0.8.0",
"xterm-addon-web-links": "^0.9.0",
"xterm-addon-webgl": "^0.16.0",
"zmodem.js": "^0.1.10"
"libapps": "github:yudai/libapps#release-hterm-1.70",
"xterm": "^2.7.0"
}
}

View File

@ -1,63 +0,0 @@
import { createRef, Component, ComponentChildren } from "preact";
import { Modal } from "bootstrap";
import './bootstrap.scss';
interface ModalProps {
children: ComponentChildren;
buttons?: ComponentChildren;
title: string;
dismissHandler?: (hideModal?: () => void) => void;
}
export class MyModal extends Component<ModalProps, {}> {
ref = createRef<HTMLDivElement>();
constructor() {
super();
}
componentDidMount() {
Modal.getOrCreateInstance(this.ref.current!).show();
this.ref.current?.addEventListener('hide.bs.modal', () => { this.props.dismissHandler && this.props.dismissHandler(); });
}
componentWillUnmount() {
this.hide()
}
hide(): void {
Modal.getOrCreateInstance(this.ref.current!).hide();
}
render() {
return <div class="modal fade" ref={this.ref} tabIndex={-1} aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{this.props.title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
{this.props.children}
</div>
<div class="modal-footer">
{this.props.buttons}
</div>
</div>
</div>
</div>;
}
}
interface ButtonProps {
priority: "primary" | "secondary" | "danger"
clickHandler?: () => void
children: ComponentChildren
disabled?: boolean;
}
export function Button(props:ButtonProps) {
let classes: string = "btn btn-" + props.priority
return <button type="button" disabled={props.disabled} class={classes} onClick={ () => { props.clickHandler ? props.clickHandler() : null; }}>{ props.children}</button>
}

26
js/src/bootstrap.scss vendored
View File

@ -1,26 +0,0 @@
@import "mixins/banner";
@include bsBanner("");
// scss-docs-start import-stack
// Configuration
@import "functions";
@import "variables";
@import "variables-dark";
@import "maps";
@import "mixins";
@import "utilities";
// Layout & components
@import "root";
@import "reboot";
@import "type";
@import "images";
@import "containers";
@import "grid";
@import "buttons";
@import "transitions";
@import "progress";
@import "close";
@import "modal";
@import "spinners";

92
js/src/hterm.ts Normal file
View File

@ -0,0 +1,92 @@
import * as bare from "libapps";
export class Hterm {
elem: HTMLElement;
term: bare.hterm.Terminal;
io: bare.hterm.IO;
columns: number;
rows: number;
// to "show" the current message when removeMessage() is called
message: string;
constructor(elem: HTMLElement) {
this.elem = elem;
bare.hterm.defaultStorage = new bare.lib.Storage.Memory();
this.term = new bare.hterm.Terminal();
this.term.getPrefs().set("send-encoding", "raw");
this.term.decorate(this.elem);
this.io = this.term.io.push();
this.term.installKeyboard();
};
info(): { columns: number, rows: number } {
return { columns: this.columns, rows: this.rows };
};
output(data: string) {
if (this.term.io != null) {
this.term.io.writeUTF8(data);
}
};
showMessage(message: string, timeout: number) {
this.message = message;
if (timeout > 0) {
this.term.io.showOverlay(message, timeout);
} else {
this.term.io.showOverlay(message, null);
}
};
removeMessage(): void {
// there is no hideOverlay(), so show the same message with 0 sec
this.term.io.showOverlay(this.message, 0);
}
setWindowTitle(title: string) {
this.term.setWindowTitle(title);
};
setPreferences(value: object) {
Object.keys(value).forEach((key) => {
this.term.getPrefs().set(key, value[key]);
});
};
onInput(callback: (input: string) => void) {
this.io.onVTKeystroke = (data) => {
callback(data);
};
this.io.sendString = (data) => {
callback(data);
};
};
onResize(callback: (colmuns: number, rows: number) => void) {
this.io.onTerminalResize = (columns: number, rows: number) => {
this.columns = columns;
this.rows = rows;
callback(columns, rows);
};
};
deactivate(): void {
this.io.onVTKeystroke = function(){};
this.io.sendString = function(){};
this.io.onTerminalResize = function(){};
this.term.uninstallKeyboard();
}
reset(): void {
this.removeMessage();
this.term.installKeyboard();
}
close(): void {
this.term.uninstallKeyboard();
}
}

View File

@ -1,29 +1,28 @@
import { ConnectionFactory } from "./websocket";
import { Hterm } from "./hterm";
import { Xterm } from "./xterm";
import { Terminal, WebTTY, protocols } from "./webtty";
import { OurXterm } from "./xterm";
import { ConnectionFactory } from "./websocket";
// @TODO remove these
declare var gotty_auth_token: string;
declare var gotty_term: string;
declare var gotty_ws_query_args: string;
const elem = document.getElementById("terminal")
if (elem !== null) {
var term: Terminal;
term = new OurXterm(elem);
if (gotty_term == "hterm") {
term = new Hterm(elem);
} else {
term = new Xterm(elem);
}
const httpsEnabled = window.location.protocol == "https:";
const queryArgs = (gotty_ws_query_args === "") ? "" : "?" + gotty_ws_query_args;
const url = (httpsEnabled ? 'wss://' : 'ws://') + window.location.host + window.location.pathname + 'ws' + queryArgs;
const url = (httpsEnabled ? 'wss://' : 'ws://') + window.location.host + window.location.pathname + 'ws';
const args = window.location.search;
const factory = new ConnectionFactory(url, protocols);
const wt = new WebTTY(term, factory, args, gotty_auth_token);
const closer = wt.open();
// According to https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
// this event is unreliable and in some cases (Firefox is mentioned), having an
// "unload" event handler can have unwanted side effects. Consider commenting it out.
window.addEventListener("unload", () => {
closer();
term.close();

View File

@ -15,6 +15,7 @@ export class ConnectionFactory {
export class Connection {
bare: WebSocket;
constructor(url: string, protocols: string[]) {
this.bare = new WebSocket(url, protocols);
}

148
js/src/webtty.ts Normal file
View File

@ -0,0 +1,148 @@
export const protocols = ["webtty"];
export const msgInputUnknown = '0';
export const msgInput = '1';
export const msgPing = '2';
export const msgResizeTerminal = '3';
export const msgUnknownOutput = '0';
export const msgOutput = '1';
export const msgPong = '2';
export const msgSetWindowTitle = '3';
export const msgSetPreferences = '4';
export const msgSetReconnect = '5';
export interface Terminal {
info(): { columns: number, rows: number };
output(data: string): void;
showMessage(message: string, timeout: number): void;
removeMessage(): void;
setWindowTitle(title: string): void;
setPreferences(value: object): void;
onInput(callback: (input: string) => void): void;
onResize(callback: (colmuns: number, rows: number) => void): void;
reset(): void;
deactivate(): void;
close(): void;
}
export interface Connection {
open(): void;
close(): void;
send(data: string): void;
isOpen(): boolean;
onOpen(callback: () => void): void;
onReceive(callback: (data: string) => void): void;
onClose(callback: () => void): void;
}
export interface ConnectionFactory {
create(): Connection;
}
export class WebTTY {
term: Terminal;
connectionFactory: ConnectionFactory;
args: string;
authToken: string;
reconnect: number;
constructor(term: Terminal, connectionFactory: ConnectionFactory, args: string, authToken: string) {
this.term = term;
this.connectionFactory = connectionFactory;
this.args = args;
this.authToken = authToken;
this.reconnect = -1;
};
open() {
let connection = this.connectionFactory.create();
let pingTimer: number;
let reconnectTimeout: number;
const setup = () => {
connection.onOpen(() => {
const termInfo = this.term.info();
connection.send(JSON.stringify(
{
Arguments: this.args,
AuthToken: this.authToken,
}
));
const resizeHandler = (colmuns: number, rows: number) => {
connection.send(
msgResizeTerminal + JSON.stringify(
{
columns: colmuns,
rows: rows
}
)
);
};
this.term.onResize(resizeHandler);
resizeHandler(termInfo.columns, termInfo.rows);
this.term.onInput(
(input: string) => {
connection.send(msgInput + input);
}
);
pingTimer = setInterval(() => {
connection.send(msgPing)
}, 30 * 1000);
});
connection.onReceive((data) => {
const payload = data.slice(1);
switch (data[0]) {
case msgOutput:
this.term.output(atob(payload));
break;
case msgPong:
break;
case msgSetWindowTitle:
this.term.setWindowTitle(payload);
break;
case msgSetPreferences:
const preferences = JSON.parse(payload);
this.term.setPreferences(preferences);
break;
case msgSetReconnect:
const autoReconnect = JSON.parse(payload);
console.log("Enabling reconnect: " + autoReconnect + " seconds")
this.reconnect = autoReconnect;
break;
}
});
connection.onClose(() => {
clearInterval(pingTimer);
this.term.deactivate();
this.term.showMessage("Connection Closed", 0);
if (this.reconnect > 0) {
reconnectTimeout = setTimeout(() => {
connection = this.connectionFactory.create();
this.term.reset();
setup();
}, this.reconnect * 1000);
}
});
connection.open();
}
setup();
return () => {
clearTimeout(reconnectTimeout);
connection.close();
}
};
};

View File

@ -1,270 +0,0 @@
export const protocols = ["webtty"];
export const msgInputUnknown = '0';
export const msgInput = '1';
export const msgPing = '2';
export const msgResizeTerminal = '3';
export const msgSetEncoding = '4';
export const msgUnknownOutput = '0';
export const msgOutput = '1';
export const msgPong = '2';
export const msgSetWindowTitle = '3';
export const msgSetPreferences = '4';
export const msgSetReconnect = '5';
export const msgSetBufferSize = '6';
export interface Terminal {
/*
* Get dimensions of the terminal
*/
info(): { columns: number, rows: number };
/*
* Process output from the server side
*/
output(data: Uint8Array): void;
/*
* Display a message overlay on the terminal
*/
showMessage(message: string, timeout: number): void;
// Don't think we need this anymore
// getMessage(): HTMLElement;
/*
* Remove message shown by shoMessage. You only need to call
* this if you want to dismiss it sooner than the timeout.
*/
removeMessage(): void;
/*
* Set window title
*/
setWindowTitle(title: string): void;
/*
* Set preferences. TODO: Add typings
*/
setPreferences(value: object): void;
/*
* Sets an input (e.g. user types something) handler
*/
onInput(callback: (input: string) => void): void;
/*
* Sets a resize handler
*/
onResize(callback: (colmuns: number, rows: number) => void): void;
reset(): void;
deactivate(): void;
close(): void;
}
export interface Connection {
open(): void;
close(): void;
/*
* This takes fucking strings??
*/
send(s: string): void;
isOpen(): boolean;
onOpen(callback: () => void): void;
onReceive(callback: (data: string) => void): void;
onClose(callback: () => void): void;
}
export interface ConnectionFactory {
create(): Connection;
}
export class WebTTY {
/*
* A terminal instance that implements the Terminal interface.
* This made a lot of sense when we had both HTerm and xterm, but
* now I wonder if the abstraction makes sense. Keeping it for now,
* though.
*/
term: Terminal;
/*
* ConnectionFactory and connection instance. We pass the factory
* in instead of just a connection so that we can reconnect.
*/
connectionFactory: ConnectionFactory;
connection: Connection;
/*
* Arguments passed in by the user. We forward them to the backend
* where they are appended to the command line.
*/
args: string;
/*
* An authentication token. The client gets this from `/auth_token.js`.
*/
authToken: string;
/*
* If connection is dropped, reconnect after `reconnect` seconds.
* -1 means do not reconnect.
*/
reconnect: number;
/*
* The server's buffer size. If a single message exceeds this size, it will
* be truncated on the server, so we track it here so that we can split messages
* into chunks small enough that we don't hurt the server's feelings.
*/
bufSize: number;
constructor(term: Terminal, connectionFactory: ConnectionFactory, args: string, authToken: string) {
this.term = term;
this.connectionFactory = connectionFactory;
this.args = args;
this.authToken = authToken;
this.reconnect = -1;
this.bufSize = 1024;
};
open() {
let connection = this.connectionFactory.create();
let pingTimer: NodeJS.Timeout;
let reconnectTimeout: NodeJS.Timeout;
this.connection = connection;
const setup = () => {
connection.onOpen(() => {
const termInfo = this.term.info();
this.initializeConnection(this.args, this.authToken);
this.term.onResize((columns: number, rows: number) => {
this.sendResizeTerminal(columns, rows);
});
this.sendResizeTerminal(termInfo.columns, termInfo.rows);
this.sendSetEncoding("base64");
this.term.onInput(
(input: string | Uint8Array) => {
this.sendInput(input);
}
);
pingTimer = setInterval(() => {
this.sendPing()
}, 30 * 1000);
});
connection.onReceive((data) => {
const payload = data.slice(1);
switch (data[0]) {
case msgOutput:
this.term.output(Uint8Array.from(atob(payload), c => c.charCodeAt(0)));
break;
case msgPong:
break;
case msgSetWindowTitle:
this.term.setWindowTitle(payload);
break;
case msgSetPreferences:
const preferences = JSON.parse(payload);
this.term.setPreferences(preferences);
break;
case msgSetReconnect:
const autoReconnect = JSON.parse(payload);
console.log("Enabling reconnect: " + autoReconnect + " seconds")
this.reconnect = autoReconnect;
break;
case msgSetBufferSize:
const bufSize = JSON.parse(payload);
this.bufSize = bufSize;
break;
}
});
connection.onClose(() => {
clearInterval(pingTimer);
this.term.deactivate();
this.term.showMessage("Connection Closed", 0);
if (this.reconnect > 0) {
reconnectTimeout = setTimeout(() => {
connection = this.connectionFactory.create();
this.term.reset();
setup();
}, this.reconnect * 1000);
}
});
connection.open();
}
setup();
return () => {
clearTimeout(reconnectTimeout);
connection.close();
}
};
private initializeConnection(args, authToken) {
this.connection.send(JSON.stringify(
{
Arguments: args,
AuthToken: authToken,
}
));
}
/*
* sendInput sends data to the server. It accepts strings or Uint8Arrays.
* strings will be encoded as UTF-8. Uint8Arrays are passed along as-is.
*/
private sendInput(input: string | Uint8Array) {
let effectiveBufferSize = this.bufSize - 1;
let dataString: string;
if (typeof input === "string") {
dataString = input;
} else {
dataString = String.fromCharCode(...input)
}
// Account for base64 encoding
let maxChunkSize = Math.floor(effectiveBufferSize / 4) * 3;
for (let i = 0; i < Math.ceil(dataString.length / maxChunkSize); i++) {
let inputChunk = dataString.substring(i * maxChunkSize, Math.min((i + 1) * maxChunkSize, dataString.length))
this.connection.send(msgInput + btoa(inputChunk));
}
}
private sendPing(): void {
this.connection.send(msgPing);
}
private sendResizeTerminal(colmuns: number, rows: number) {
this.connection.send(
msgResizeTerminal + JSON.stringify(
{
columns: colmuns,
rows: rows
}
)
);
}
private sendSetEncoding(encoding: "base64" | "null") {
this.connection.send(msgSetEncoding + encoding)
}
};

105
js/src/xterm.ts Normal file
View File

@ -0,0 +1,105 @@
import * as bare from "xterm";
import { lib } from "libapps"
bare.loadAddon("fit");
export class Xterm {
elem: HTMLElement;
term: bare;
resizeListener: () => void;
decoder: lib.UTF8Decoder;
message: HTMLElement;
messageTimeout: number;
messageTimer: number;
constructor(elem: HTMLElement) {
this.elem = elem;
this.term = new bare();
this.message = elem.ownerDocument.createElement("div");
this.message.className = "xterm-overlay";
this.messageTimeout = 2000;
this.resizeListener = () => {
this.term.fit();
this.term.scrollToBottom();
this.showMessage(String(this.term.cols) + "x" + String(this.term.rows), this.messageTimeout);
};
this.term.on("open", () => {
this.resizeListener();
window.addEventListener("resize", () => { this.resizeListener(); });
});
this.term.open(elem, true);
this.decoder = new lib.UTF8Decoder()
};
info(): { columns: number, rows: number } {
return { columns: this.term.cols, rows: this.term.rows };
};
output(data: string) {
this.term.write(this.decoder.decode(data));
};
showMessage(message: string, timeout: number) {
this.message.textContent = message;
this.elem.appendChild(this.message);
if (this.messageTimer) {
clearTimeout(this.messageTimer);
}
if (timeout > 0) {
this.messageTimer = setTimeout(() => {
this.elem.removeChild(this.message);
}, timeout);
}
};
removeMessage(): void {
if (this.message.parentNode == this.elem) {
this.elem.removeChild(this.message);
}
}
setWindowTitle(title: string) {
document.title = title;
};
setPreferences(value: object) {
};
onInput(callback: (input: string) => void) {
this.term.on("data", (data) => {
callback(data);
});
};
onResize(callback: (colmuns: number, rows: number) => void) {
this.term.on("resize", (data) => {
callback(data.cols, data.rows);
});
};
deactivate(): void {
this.term.off("data");
this.term.off("resize");
this.term.blur();
}
reset(): void {
this.removeMessage();
this.term.clear();
}
close(): void {
window.removeEventListener("resize", this.resizeListener);
this.term.destroy();
}
}

View File

@ -1,166 +0,0 @@
import { IDisposable, Terminal } from "xterm";
import { FitAddon } from 'xterm-addon-fit';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { WebglAddon } from 'xterm-addon-webgl';
import { ZModemAddon } from "./zmodem";
export class OurXterm {
// The HTMLElement that contains our terminal
elem: HTMLElement;
// The xtermjs.XTerm
term: Terminal;
resizeListener: () => void;
message: HTMLElement;
messageTimeout: number;
messageTimer: NodeJS.Timeout;
onResizeHandler: IDisposable;
onDataHandler: IDisposable;
fitAddOn: FitAddon;
zmodemAddon: ZModemAddon;
toServer: (data: string | Uint8Array) => void;
encoder: TextEncoder
constructor(elem: HTMLElement) {
this.elem = elem;
this.term = new Terminal();
this.fitAddOn = new FitAddon();
this.zmodemAddon = new ZModemAddon({
toTerminal: (x: Uint8Array) => this.term.write(x),
toServer: (x: Uint8Array) => this.sendInput(x)
});
this.term.loadAddon(new WebLinksAddon());
this.term.loadAddon(this.fitAddOn);
this.term.loadAddon(this.zmodemAddon);
this.message = elem.ownerDocument.createElement("div");
this.message.className = "xterm-overlay";
this.messageTimeout = 2000;
this.resizeListener = () => {
this.fitAddOn.fit();
this.term.scrollToBottom();
this.showMessage(String(this.term.cols) + "x" + String(this.term.rows), this.messageTimeout);
};
this.term.open(elem);
this.term.focus();
this.resizeListener();
window.addEventListener("resize", () => { this.resizeListener(); });
};
info(): { columns: number, rows: number } {
return { columns: this.term.cols, rows: this.term.rows };
};
// This gets called from the Websocket's onReceive handler
output(data: Uint8Array) {
this.zmodemAddon.consume(data);
};
getMessage(): HTMLElement {
return this.message;
}
showMessage(message: string, timeout: number) {
this.message.innerHTML = message;
this.showMessageElem(timeout);
}
showMessageElem(timeout: number) {
this.elem.appendChild(this.message);
if (this.messageTimer) {
clearTimeout(this.messageTimer);
}
if (timeout > 0) {
this.messageTimer = setTimeout(() => {
try {
this.elem.removeChild(this.message);
} catch (error) {
console.error(error);
}
}, timeout);
}
};
removeMessage(): void {
if (this.message.parentNode == this.elem) {
this.elem.removeChild(this.message);
}
}
setWindowTitle(title: string) {
document.title = title;
};
setPreferences(value: object) {
Object.keys(value).forEach((key) => {
if (key == "EnableWebGL" && key) {
this.term.loadAddon(new WebglAddon());
} else if (key == "font-size") {
this.term.options.fontSize = value[key]
} else if (key == "font-family") {
this.term.options.fontFamily = value[key]
}
});
};
sendInput(data: Uint8Array) {
return this.toServer(data)
}
onInput(callback: (input: string) => void) {
this.encoder = new TextEncoder()
this.toServer = callback;
// I *think* we're ok like this, but if not, we can dispose
// of the previous handler and put the new one in place.
if (this.onDataHandler !== undefined) {
return
}
this.onDataHandler = this.term.onData((input) => {
this.toServer(this.encoder.encode(input));
});
};
onResize(callback: (colmuns: number, rows: number) => void) {
this.onResizeHandler = this.term.onResize(() => {
callback(this.term.cols, this.term.rows);
});
};
deactivate(): void {
this.onDataHandler.dispose();
this.onResizeHandler.dispose();
this.term.blur();
}
reset(): void {
this.removeMessage();
this.term.clear();
}
close(): void {
window.removeEventListener("resize", this.resizeListener);
this.term.dispose();
}
disableStdin(): void {
this.term.options.disableStdin = true;
}
enableStdin(): void {
this.term.options.disableStdin = false;
}
focus(): void {
this.term.focus();
}
}

View File

@ -1,245 +0,0 @@
import { Component, ComponentChildren, createRef, render } from "preact";
import { ITerminalAddon, Terminal } from "xterm";
import { Browser, Detection, Offer, Sentry, Session } from 'zmodem.js/src/zmodem_browser';
import { Button, MyModal } from "./MyModal";
export class ZModemAddon implements ITerminalAddon {
term: Terminal;
elem: HTMLDivElement;
sentry: Sentry;
toTerminal: (data: Uint8Array) => void;
toServer: (data: Uint8Array) => void;
constructor(props: {
toTerminal: (data: Uint8Array) => void,
toServer: (data: Uint8Array) => void
}) {
this.createElement();
this.toTerminal = props.toTerminal;
this.toServer = props.toServer;
this.init();
}
private createElement() {
this.elem = document.createElement("div");
document.body.prepend(this.elem);
}
consume(data: Uint8Array) {
this.sentry.consume(data)
}
activate(terminal: Terminal): void {
this.term = terminal
}
dispose() {
}
private init() {
render(<></>, this.elem);
this.sentry = new Sentry({
'to_terminal': (d: Uint8Array) => this.toTerminal(d),
'on_detect': (detection: Detection) => this.onDetect(detection),
'sender': (x: Uint8Array) => { this.toServer(x) },
'on_retract': () => this.reset(),
});
}
private reset() {
this.init();
this.term.options.disableStdin = false;
this.term.focus();
}
private onDetect(detection: Detection) {
var zsession = detection.confirm();
this.term.options.disableStdin = true;
zsession.on('session_end', () => { this.reset() });
if (zsession.type === "send") {
this.send(zsession);
}
else {
zsession.on("offer", (xfer: any) => this.onOffer(xfer));
zsession.start();
}
}
private send(zsession: Session) {
render(<SendFileModal session={zsession} />, this.elem)
}
private onOffer(xfer: Offer) {
render(<ReceiveFileModal xfer={xfer} onFinish={() => this.reset()} />, this.elem)
}
}
// Renders a bootstrap progress bar
function Progress(props: { min: number, max: number, now: number, children?: ComponentChildren }) {
let { min, max, now } = props;
let percentage = "0";
if ((typeof min === "number") &&
(typeof max === "number") &&
(typeof now === "number") &&
(min != max)) {
percentage = (100 * (now - min) / (max - min)).toFixed(0);
}
return <div class="progress">
<div class="progress-bar" role="progressbar" style={"width: " + percentage + "%"} aria-valuenow={now} aria-valuemin={min} aria-valuemax={max}>{props.children}</div>
</div>
}
interface ReceiveFileModalProps {
xfer: Offer;
onFinish?: () => void;
}
interface ReceiveFileModalState {
state: "notstarted" | "started" | "skipped" | "done"
}
export class ReceiveFileModal extends Component<ReceiveFileModalProps, ReceiveFileModalState> {
constructor(props) {
super(props)
this.setState({ state: "notstarted" })
}
accept() {
this.setState({ state: "started" });
let timerID = setInterval(
() => this.forceUpdate(),
100
);
this.props.xfer.accept().then((payloads: any) => {
// All done, so stop updating the progress bar
// and perform a final render.
clearInterval(timerID);
this.forceUpdate();
if (this.state.state != "skipped") {
Browser.save_to_disk(
payloads,
this.props.xfer.get_details().name
);
}
this.setState({ state: "done" })
})
}
finish() {
console.log('finished');
if (this.props.onFinish) this.props.onFinish();
}
progress() {
if (this.state.state !== "notstarted") {
return <Progress min={0} max={this.props.xfer.get_details().size} now={this.props.xfer.get_offset()} />
}
}
skip() {
this.props.xfer.skip()
this.setState({ state: "skipped" })
}
buttons() {
switch (this.state.state) {
case "notstarted":
return <>
<Button priority="primary" clickHandler={() => { this.accept(); }}>Accept</Button>
<Button priority="secondary" clickHandler={() => { this.skip(); }}>Decline</Button>
</>
case "started":
return <>
<Button priority="danger" clickHandler={() => { this.skip(); }}>Cancel</Button>
</>
case "skipped":
return <>
<Button priority="danger" disabled={true}>Skipping...</Button>
</>
}
}
render() {
if (this.state.state != "done")
return <MyModal title="Incoming file"
buttons={this.buttons()}>
Accept <code>{this.props.xfer.get_details().name}</code> ({this.props.xfer.get_details().size.toLocaleString(undefined, { maximumFractionDigits: 0 })} bytes)?
{this.progress()}
</MyModal>
}
}
export class SendFileModal extends Component<SendFileModalProps, SendFileModalState> {
filePickerRef = createRef<HTMLInputElement>();
constructor(props: SendFileModalProps) {
super(props)
this.setState({ state: "notstarted" })
}
buttons() {
switch (this.state.state) {
case "started":
return <>
<Button priority="primary" clickHandler={() => { this.send(); }} disabled={true}>
Sending...
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</Button>
</>
case "notstarted":
return <>
<Button priority="primary" clickHandler={() => { this.send(); }}>Send</Button>
</>
default:
return
}
}
send() {
Browser.send_files(this.props.session,
this.filePickerRef.current!.files, {
on_offer_response: (f, xfer) => { this.setState({ state: "started" }) },
}).then(() => {
this.setState({ state: "done" })
this.props.session.close()
if (this.props.onFinish !== undefined) {
this.props.onFinish();
}
})
.catch(e => console.log(e));
}
render() {
if (this.state.state != "done")
return <MyModal title="Send file(s)"
buttons={this.buttons()}>
<div class="mb-3">
<label for="formFileMultiple" class="form-label">
Remote requested file transfer
</label>
<input ref={this.filePickerRef} class="form-control form-control-sm" type="file" id="formFileMultiple" multiple />
</div>
</MyModal>
}
}
interface SendFileModalProps {
onFinish?: () => void;
session: Session;
}
interface SendFileModalState {
state: "notstarted" | "started" | "done"
currentFile: any
}

View File

@ -1,24 +1,20 @@
{
"compilerOptions": {
"outDir": "./dist/",
"jsx": "react-jsx",
"jsxImportSource": "preact",
"strictNullChecks": true,
"noUnusedLocals" : true,
"noImplicitThis": true,
"alwaysStrict": true,
"outDir": "./dist/",
"declaration": true,
"sourceMap": true,
"target": "esnext",
"target": "es5",
"module": "commonJS",
"baseUrl": ".",
"types": ["preact", "node"],
"paths": {
"*": ["./typings/*"]
}
},
"exclude": [
"node_modules",
"dist"
"node_modules"
]
}

51
js/typings/libapps/index.d.ts vendored Normal file
View File

@ -0,0 +1,51 @@
export declare namespace hterm {
export class Terminal {
io: IO;
onTerminalReady: () => void;
constructor();
getPrefs(): Prefs;
decorate(HTMLElement);
installKeyboard(): void;
uninstallKeyboard(): void;
setWindowTitle(title: string): void;
reset(): void;
softReset(): void;
}
export class IO {
writeUTF8: ((data: string) => void);
writeUTF16: ((data: string) => void);
onVTKeystroke: ((data: string) => void) | null;
sendString: ((data: string) => void) | null;
onTerminalResize: ((columns: number, rows: number) => void) | null;
push(): IO;
writeUTF(data: string);
showOverlay(message: string, timeout: number | null);
}
export class Prefs {
set(key: string, value: string): void;
}
export var defaultStorage: lib.Storage;
}
export declare namespace lib {
export interface Storage {
}
export interface Memory {
new (): Storage;
Memory(): Storage
}
export var Storage: {
Memory: Memory
}
export class UTF8Decoder {
decode(str: string)
}
}

View File

@ -1,30 +1,14 @@
const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin;
var devtool;
if (process.env.DEV === '1') {
devtool = 'inline-source-map';
} else {
devtool = 'source-map';
}
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: "./src/main.ts",
entry: {
"gotty": "./src/main.ts",
},
output: {
path: path.resolve(__dirname, '../bindata/static/js/'),
filename: "./dist/gotty-bundle.js"
},
devtool: devtool,
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
plugins: [
new LicenseWebpackPlugin()
],
module: {
rules: [
{
@ -33,25 +17,13 @@ module.exports = {
exclude: /node_modules/
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.scss$/i,
use: ["style-loader", "css-loader", {
loader: "sass-loader",
options: {
sassOptions: {
includePaths: ["node_modules/bootstrap/scss"]
}
}
}
],
},
],
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
test: /\.js$/,
include: /node_modules/,
loader: 'license-loader'
}
]
},
plugins: [
new UglifyJSPlugin()
]
};

54
main.go
View File

@ -3,29 +3,29 @@ package main
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"syscall"
cli "github.com/urfave/cli/v2"
"github.com/codegangsta/cli"
"github.com/sorenisanerd/gotty/backend/localcommand"
"github.com/sorenisanerd/gotty/pkg/homedir"
"github.com/sorenisanerd/gotty/server"
"github.com/sorenisanerd/gotty/utils"
"github.com/yudai/gotty/backend/localcommand"
"github.com/yudai/gotty/pkg/homedir"
"github.com/yudai/gotty/server"
"github.com/yudai/gotty/utils"
)
func main() {
app := cli.NewApp()
app.Name = "gotty"
app.Version = Version
app.Version = Version + "+" + CommitID
app.Usage = "Share your terminal as a web application"
app.HideHelpCommand = true
appOptions := &server.Options{}
app.HideHelp = true
cli.AppHelpTemplate = helpTemplate
appOptions := &server.Options{}
if err := utils.ApplyDefaultValues(appOptions); err != nil {
exit(err, 1)
}
@ -41,16 +41,16 @@ func main() {
app.Flags = append(
cliFlags,
&cli.StringFlag{
Name: "config",
Value: "~/.gotty",
Usage: "Config file path",
EnvVars: []string{"GOTTY_CONFIG"},
cli.StringFlag{
Name: "config",
Value: "~/.gotty",
Usage: "Config file path",
EnvVar: "GOTTY_CONFIG",
},
)
app.Action = func(c *cli.Context) error {
if c.NArg() == 0 {
app.Action = func(c *cli.Context) {
if len(c.Args()) == 0 {
msg := "Error: No command given."
cli.ShowAppHelp(c)
exit(fmt.Errorf(msg), 1)
@ -66,17 +66,8 @@ func main() {
utils.ApplyFlags(cliFlags, flagMappings, c, appOptions, backendOptions)
if appOptions.Quiet {
log.SetFlags(0)
log.SetOutput(io.Discard)
}
if c.IsSet("credential") {
appOptions.EnableBasicAuth = true
}
if c.IsSet("tls-ca-crt") {
appOptions.EnableTLSClientAuth = true
}
appOptions.EnableBasicAuth = c.IsSet("credential")
appOptions.EnableTLSClientAuth = c.IsSet("tls-ca-crt")
err = appOptions.Validate()
if err != nil {
@ -84,15 +75,15 @@ func main() {
}
args := c.Args()
factory, err := localcommand.NewFactory(args.First(), args.Tail(), backendOptions)
factory, err := localcommand.NewFactory(args[0], args[1:], backendOptions)
if err != nil {
exit(err, 3)
}
hostname, _ := os.Hostname()
appOptions.TitleVariables = map[string]interface{}{
"command": args.First(),
"argv": args.Tail(),
"command": args[0],
"argv": args[1:],
"hostname": hostname,
}
@ -104,7 +95,7 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
gCtx, gCancel := context.WithCancel(context.Background())
log.Printf("GoTTY is starting with command: %s", strings.Join(args.Slice(), " "))
log.Printf("GoTTY is starting with command: %s", strings.Join(args, " "))
errs := make(chan error, 1)
go func() {
@ -117,7 +108,6 @@ func main() {
exit(err, 8)
}
return nil
}
app.Run(os.Args)
}

View File

@ -1,8 +0,0 @@
* Check that the build works, duh.
* Check that "gotty bash" works and that it does not accept input.
* Check that "gotty -w bash" works and that it DOES accept input.
* Check that "gotty -w bash" works and that it DOES accept input.
* Check that cross-compilation works.
* Ensure NEWS is up-to-date
* Ensure contributor list is up-to-date
* Ensure usage is correct in Makefile

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

BIN
resources/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 863 B

View File

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 708.4149 708.41411"
height="708.41412"
width="708.41492"
xml:space="preserve"
id="svg2"
version="1.1"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
id="clipPath18"
clipPathUnits="userSpaceOnUse"><path
id="path16"
d="M 0,2000 H 2000 V 0 H 0 Z" /></clipPath></defs><g
transform="matrix(1.3333333,0,0,-1.3333333,-979.12558,1687.5405)"
id="g10"><g
id="g12"><g
clip-path="url(#clipPath18)"
id="g14"><g
transform="translate(772.1414,1265.6554)"
id="g20"><path
id="path22"
style="fill:#de3c28;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -20.875,0 -37.797,-16.922 -37.797,-37.797 v -126.348 -25.917 -212.342 L 345.882,0 Z" /></g><g
transform="translate(956.8504,734.3448)"
id="g24"><path
id="path26"
style="fill:#af1419;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h 260.209 c 26.839,0 48.596,21.757 48.596,48.596 v 275.281 z" /></g><g
transform="translate(1265.6552,1075.5929)"
id="g28"><path
id="path30"
style="fill:#db0918;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 25.918 126.348 c 0,20.875 -16.922,37.796 -37.796,37.796 h -109.836 l -383.679,-402.404 v -80.31 c 0,-26.839 21.757,-48.596 48.596,-48.596 h 173.91 L 0,-17.371 Z" /></g><g
transform="translate(1169.2147,909.6954)"
id="g32"><path
id="path34"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 h -138.227 c -9.129,0 -16.528,7.4 -16.528,16.529 0,9.128 7.399,16.529 16.528,16.529 H 0 c 9.129,0 16.528,-7.401 16.528,-16.529 C 16.528,7.4 9.129,0 0,0" /></g><g
transform="translate(898.8318,1033.5314)"
id="g36"><path
id="path38"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c 2.86,-0.72 5.65,-1.45 8.37,-2.2 -0.63,-8.56 -7.76,-15.3 -16.479,-15.3 -9.13,0 -16.531,7.4 -16.531,16.53 v 8.54 c 1.861,-0.83 3.72,-1.549 5.601,-2.15 C -15.199,4.18 -8.85,2.37 0,0" /></g><g
transform="translate(907.2527,1150.7814)"
id="g40"><path
id="path42"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v -65.81 c -4.45,1.59 -9.98,2.38 -16.601,2.38 -6.21,0 -11.7,-0.88 -16.46,-2.64 V 0 c 0,9.13 7.401,16.53 16.531,16.53 C -7.4,16.53 0,9.13 0,0" /></g><g
transform="translate(874.1922,868.8272)"
id="g44"><path
id="path46"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 v 65.811 c 4.45,-1.59 9.98,-2.38 16.601,-2.38 6.21,0 11.699,0.88 16.46,2.639 V 0 C 33.061,-9.13 25.66,-16.529 16.53,-16.529 7.4,-16.529 0,-9.13 0,0" /></g><g
transform="translate(966.6326,994.1915)"
id="g48"><path
id="path50"
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none"
d="m 0,0 c -3.53,7.28 -8.45,13.3 -14.75,18.06 -6.301,4.76 -13.95,8.8 -22.94,12.14 -6.661,2.47 -13.911,4.78 -21.741,6.94 -2.719,0.75 -5.509,1.48 -8.37,2.2 -8.849,2.37 -15.199,4.18 -19.039,5.42 -1.881,0.6 -3.74,1.32 -5.6,2.15 -1.951,0.87 -3.88,1.87 -5.8,2.99 -3.76,2.19 -6.71,4.81 -8.861,7.85 -2.139,3.05 -3.219,6.67 -3.219,10.86 0,6.75 3.16,12.54 9.46,17.34 2.49,1.9 5.299,3.43 8.42,4.57 4.759,1.76 10.25,2.64 16.46,2.64 6.62,0 12.15,-0.79 16.6,-2.38 3.01,-1.05 5.52,-2.48 7.54,-4.26 5.01,-4.42 9.3,-10.59 12.88,-18.49 2.77,-5.52 5.34,-9.49 7.71,-11.92 2.37,-2.43 5.84,-3.64 10.399,-3.64 5.011,0 9.191,2.02 12.54,6.07 3.351,4.04 5.031,8.59 5.031,13.63 0,5.52 -1.34,11.19 -4.021,17 -2.689,5.8 -6.939,11.35 -12.75,16.63 -5.809,5.28 -13.119,9.52 -21.929,12.71 -5.23,1.89 -11.031,3.22 -17.4,3.99 -4.37,0.53 -9.011,0.79 -13.921,0.79 -6.779,0 -13.159,-0.48 -19.139,-1.45 -7.361,-1.19 -14.121,-3.11 -20.29,-5.76 -11.18,-4.81 -19.72,-11.69 -25.621,-20.63 -5.899,-8.95 -8.849,-19.18 -8.849,-30.7 0,-12.09 2.79,-22.2 8.38,-30.34 5.59,-8.14 13.15,-14.56 22.67,-19.28 9.52,-4.71 21.349,-8.83 35.48,-12.35 10.55,-2.57 18.98,-4.99 25.279,-7.28 6.301,-2.28 11.441,-5.59 15.42,-9.92 3.981,-4.33 5.971,-9.97 5.971,-16.92 0,-8.76 -3.69,-16.06 -11.061,-21.92 -7.379,-5.85 -16.969,-8.78 -28.769,-8.78 -8.59,0 -15.521,1.45 -20.79,4.36 -5.28,2.9 -9.37,6.59 -12.28,11.06 -2.901,4.47 -5.611,10.04 -8.111,16.71 -2.059,5.61 -4.54,9.85 -7.449,12.7 -2.9,2.86 -6.46,4.29 -10.66,4.29 -5.181,0 -9.45,-1.84 -12.811,-5.5 -3.349,-3.66 -5.029,-8.07 -5.029,-13.21 0,-8.85 2.8,-17.96 8.39,-27.34 5.58,-9.38 12.849,-16.87 21.79,-22.49 12.61,-7.8 28.61,-11.7 48.019,-11.7 16.181,0 30.181,2.85 41.981,8.56 11.809,5.71 20.769,13.61 26.9,23.7 6.119,10.09 9.18,21.47 9.18,34.129 C 5.3,-16.21 3.54,-7.28 0,0" /></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

View File

@ -4,10 +4,4 @@ html, body, #terminal {
width: 100%;
padding: 0%;
margin: 0%;
}
.progress .progress-bar {
transition: unset;
transition-duration: 0.1s;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

View File

@ -1,22 +1,16 @@
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" href="favicon.ico">
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/xterm.css" />
<link rel="stylesheet" href="./css/xterm_customize.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="terminal"></div>
<script src="./auth_token.js"></script>
<script src="./config.js"></script>
<script src="./js/gotty.js"></script>
</body>
</html>
<head>
<title>{{ .title }}</title>
<link rel="icon" type="image/png" href="favicon.png">
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/xterm.css" />
<link rel="stylesheet" href="./css/xterm_customize.css" />
</head>
<body>
<div id="terminal"></div>
<script src="./auth_token.js"></script>
<script src="./config.js"></script>
<script src="./js/gotty-bundle.js"></script>
</body>
</html>

View File

@ -1,15 +0,0 @@
{
"short_name": "{{ .title }}",
"name": "{{ .title }}",
"start_url": "./",
"icons": [
{
"src": "./icon_192.png",
"type": "image/png",
"sizes": "192x192"
}
],
"display": "minimal-ui",
"theme_color": "#000000",
"background_color": "#000000"
}

379
server/asset.go Normal file

File diff suppressed because one or more lines are too long

View File

@ -8,13 +8,12 @@ import (
"log"
"net/http"
"net/url"
"strings"
"sync/atomic"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/sorenisanerd/gotty/webtty"
"github.com/yudai/gotty/webtty"
)
func (server *Server) generateHandleWS(ctx context.Context, cancel context.CancelFunc, counter *counter) http.HandlerFunc {
@ -73,11 +72,7 @@ func (server *Server) generateHandleWS(ctx context.Context, cancel context.Cance
}
defer conn.Close()
if server.options.PassHeaders {
err = server.processWSConn(ctx, conn, r.Header)
} else {
err = server.processWSConn(ctx, conn, nil)
}
err = server.processWSConn(ctx, conn, r.Header)
switch err {
case ctx.Err():
@ -92,7 +87,7 @@ func (server *Server) generateHandleWS(ctx context.Context, cancel context.Cance
}
}
func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, headers map[string][]string) error {
func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, header http.Header) error {
typ, initLine, err := conn.ReadMessage()
if err != nil {
return errors.Wrapf(err, "failed to authenticate websocket connection")
@ -114,14 +109,18 @@ func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, h
if server.options.PermitArguments && init.Arguments != "" {
queryPath = init.Arguments
}
headerArguments := header.Get("Arguments")
if server.options.PermitArguments && headerArguments != "" {
queryPath = queryPath + "&" + headerArguments
}
query, err := url.Parse(queryPath)
if err != nil {
return errors.Wrapf(err, "failed to parse arguments")
}
params := query.Query()
var slave Slave
slave, err = server.factory.New(params, headers)
slave, err = server.factory.New(params)
if err != nil {
return errors.Wrapf(err, "failed to create backend")
}
@ -159,6 +158,10 @@ func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, h
if server.options.Height > 0 {
opts = append(opts, webtty.WithFixedRows(server.options.Height))
}
if server.options.Preferences != nil {
opts = append(opts, webtty.WithMasterPreferences(server.options.Preferences))
}
tty, err := webtty.New(&wsWrapper{conn}, slave, opts...)
if err != nil {
return errors.Wrapf(err, "failed to create webtty")
@ -170,40 +173,6 @@ func (server *Server) processWSConn(ctx context.Context, conn *websocket.Conn, h
}
func (server *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
indexVars, err := server.indexVariables(r)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
indexBuf := new(bytes.Buffer)
err = server.indexTemplate.Execute(indexBuf, indexVars)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
w.Write(indexBuf.Bytes())
}
func (server *Server) handleManifest(w http.ResponseWriter, r *http.Request) {
indexVars, err := server.indexVariables(r)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
indexBuf := new(bytes.Buffer)
err = server.manifestTemplate.Execute(indexBuf, indexVars)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
w.Write(indexBuf.Bytes())
}
func (server *Server) indexVariables(r *http.Request) (map[string]interface{}, error) {
titleVars := server.titleVariables(
[]string{"server", "master"},
map[string]map[string]interface{}{
@ -217,13 +186,22 @@ func (server *Server) indexVariables(r *http.Request) (map[string]interface{}, e
titleBuf := new(bytes.Buffer)
err := server.titleTemplate.Execute(titleBuf, titleVars)
if err != nil {
return nil, err
http.Error(w, "Internal Server Error", 500)
return
}
indexVars := map[string]interface{}{
"title": titleBuf.String(),
}
return indexVars, err
indexBuf := new(bytes.Buffer)
err = server.indexTemplate.Execute(indexBuf, indexVars)
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
w.Write(indexBuf.Bytes())
}
func (server *Server) handleAuthToken(w http.ResponseWriter, r *http.Request) {
@ -234,12 +212,7 @@ func (server *Server) handleAuthToken(w http.ResponseWriter, r *http.Request) {
func (server *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
lines := []string{
"var gotty_term = 'xterm';",
"var gotty_ws_query_args = '" + server.options.WSQueryArgs + "';",
}
w.Write([]byte(strings.Join(lines, "\n")))
w.Write([]byte("var gotty_term = '" + server.options.Term + "';"))
}
// titleVariables merges maps in a specified order.

View File

@ -5,34 +5,31 @@ import (
)
type Options struct {
Address string `hcl:"address" flagName:"address" flagSName:"a" flagDescribe:"IP address to listen" default:"0.0.0.0"`
Port string `hcl:"port" flagName:"port" flagSName:"p" flagDescribe:"Port number to liten" default:"8080"`
Path string `hcl:"path" flagName:"path" flagSName:"m" flagDescribe:"Base path" default:"/"`
PermitWrite bool `hcl:"permit_write" flagName:"permit-write" flagSName:"w" flagDescribe:"Permit clients to write to the TTY (BE CAREFUL)" default:"false"`
EnableBasicAuth bool `hcl:"enable_basic_auth" default:"false"`
Credential string `hcl:"credential" flagName:"credential" flagSName:"c" flagDescribe:"Credential for Basic Authentication (ex: user:pass, default disabled)" default:""`
EnableRandomUrl bool `hcl:"enable_random_url" flagName:"random-url" flagSName:"r" flagDescribe:"Add a random string to the URL" default:"false"`
RandomUrlLength int `hcl:"random_url_length" flagName:"random-url-length" flagDescribe:"Random URL length" default:"8"`
EnableTLS bool `hcl:"enable_tls" flagName:"tls" flagSName:"t" flagDescribe:"Enable TLS/SSL" default:"false"`
TLSCrtFile string `hcl:"tls_crt_file" flagName:"tls-crt" flagDescribe:"TLS/SSL certificate file path" default:"~/.gotty.crt"`
TLSKeyFile string `hcl:"tls_key_file" flagName:"tls-key" flagDescribe:"TLS/SSL key file path" default:"~/.gotty.key"`
EnableTLSClientAuth bool `hcl:"enable_tls_client_auth" default:"false"`
TLSCACrtFile string `hcl:"tls_ca_crt_file" flagName:"tls-ca-crt" flagDescribe:"TLS/SSL CA certificate file for client certifications" default:"~/.gotty.ca.crt"`
IndexFile string `hcl:"index_file" flagName:"index" flagDescribe:"Custom index.html file" default:""`
TitleFormat string `hcl:"title_format" flagName:"title-format" flagSName:"" flagDescribe:"Title format of browser window" default:"{{ .command }}@{{ .hostname }}"`
EnableReconnect bool `hcl:"enable_reconnect" flagName:"reconnect" flagDescribe:"Enable reconnection" default:"false"`
ReconnectTime int `hcl:"reconnect_time" flagName:"reconnect-time" flagDescribe:"Time to reconnect" default:"10"`
MaxConnection int `hcl:"max_connection" flagName:"max-connection" flagDescribe:"Maximum connection to gotty" default:"0"`
Once bool `hcl:"once" flagName:"once" flagDescribe:"Accept only one client and exit on disconnection" default:"false"`
Timeout int `hcl:"timeout" flagName:"timeout" flagDescribe:"Timeout seconds for waiting a client(0 to disable)" default:"0"`
PermitArguments bool `hcl:"permit_arguments" flagName:"permit-arguments" flagDescribe:"Permit clients to send command line arguments in URL (e.g. http://example.com:8080/?arg=AAA&arg=BBB)" default:"false"`
PassHeaders bool `hcl:"pass_headers" flagName:"pass-headers" flagDescribe:"Pass HTTP request headers as environment variables (e.g. Cookie becomes HTTP_COOKIE)" default:"false"`
Width int `hcl:"width" flagName:"width" flagDescribe:"Static width of the screen, 0(default) means dynamically resize" default:"0"`
Height int `hcl:"height" flagName:"height" flagDescribe:"Static height of the screen, 0(default) means dynamically resize" default:"0"`
WSOrigin string `hcl:"ws_origin" flagName:"ws-origin" flagDescribe:"A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default" default:""`
WSQueryArgs string `hcl:"ws_query_args" flagName:"ws-query-args" flagDescribe:"Querystring arguments to append to the websocket instantiation" default:""`
EnableWebGL bool `hcl:"enable_webgl" flagName:"enable-webgl" flagDescribe:"Enable WebGL renderer" default:"true"`
Quiet bool `hcl:"quiet" flagName:"quiet" flagDescribe:"Don't log" default:"false"`
Address string `hcl:"address" flagName:"address" flagSName:"a" flagDescribe:"IP address to listen" default:"0.0.0.0"`
Port string `hcl:"port" flagName:"port" flagSName:"p" flagDescribe:"Port number to liten" default:"8080"`
PermitWrite bool `hcl:"permit_write" flagName:"permit-write" flagSName:"w" flagDescribe:"Permit clients to write to the TTY (BE CAREFUL)" default:"false"`
EnableBasicAuth bool `hcl:"enable_basic_auth" default:"false"`
Credential string `hcl:"credential" flagName:"credential" flagSName:"c" flagDescribe:"Credential for Basic Authentication (ex: user:pass, default disabled)" default:""`
EnableRandomUrl bool `hcl:"enable_random_url" flagName:"random-url" flagSName:"r" flagDescribe:"Add a random string to the URL" default:"false"`
RandomUrlLength int `hcl:"random_url_length" flagName:"random-url-length" flagDescribe:"Random URL length" default:"8"`
EnableTLS bool `hcl:"enable_tls" flagName:"tls" flagSName:"t" flagDescribe:"Enable TLS/SSL" default:"false"`
TLSCrtFile string `hcl:"tls_crt_file" flagName:"tls-crt" flagDescribe:"TLS/SSL certificate file path" default:"~/.gotty.crt"`
TLSKeyFile string `hcl:"tls_key_file" flagName:"tls-key" flagDescribe:"TLS/SSL key file path" default:"~/.gotty.key"`
EnableTLSClientAuth bool `hcl:"enable_tls_client_auth" default:"false"`
TLSCACrtFile string `hcl:"tls_ca_crt_file" flagName:"tls-ca-crt" flagDescribe:"TLS/SSL CA certificate file for client certifications" default:"~/.gotty.ca.crt"`
IndexFile string `hcl:"index_file" flagName:"index" flagDescribe:"Custom index.html file" default:""`
TitleFormat string `hcl:"title_format" flagName:"title-format" flagSName:"" flagDescribe:"Title format of browser window" default:"{{ .command }}@{{ .hostname }}"`
EnableReconnect bool `hcl:"enable_reconnect" flagName:"reconnect" flagDescribe:"Enable reconnection" default:"false"`
ReconnectTime int `hcl:"reconnect_time" flagName:"reconnect-time" flagDescribe:"Time to reconnect" default:"10"`
MaxConnection int `hcl:"max_connection" flagName:"max-connection" flagDescribe:"Maximum connection to gotty" default:"0"`
Once bool `hcl:"once" flagName:"once" flagDescribe:"Accept only one client and exit on disconnection" default:"false"`
Timeout int `hcl:"timeout" flagName:"timeout" flagDescribe:"Timeout seconds for waiting a client(0 to disable)" default:"0"`
PermitArguments bool `hcl:"permit_arguments" flagName:"permit-arguments" flagDescribe:"Permit clients to send command line arguments in URL (e.g. http://example.com:8080/?arg=AAA&arg=BBB)" default:"true"`
Preferences *HtermPrefernces `hcl:"preferences"`
Width int `hcl:"width" flagName:"width" flagDescribe:"Static width of the screen, 0(default) means dynamically resize" default:"0"`
Height int `hcl:"height" flagName:"height" flagDescribe:"Static height of the screen, 0(default) means dynamically resize" default:"0"`
WSOrigin string `hcl:"ws_origin" flagName:"ws-origin" flagDescribe:"A regular expression that matches origin URLs to be accepted by WebSocket. No cross origin requests are acceptable by default" default:""`
Term string `hcl:"term" flagName:"term" flagDescribe:"Terminal name to use on the browser, one of xterm or hterm." default:"xterm"`
TitleVariables map[string]interface{}
}
@ -43,3 +40,60 @@ func (options *Options) Validate() error {
}
return nil
}
type HtermPrefernces struct {
AltGrMode *string `hcl:"alt_gr_mode" json:"alt-gr-mode,omitempty"`
AltBackspaceIsMetaBackspace bool `hcl:"alt_backspace_is_meta_backspace" json:"alt-backspace-is-meta-backspace,omitempty"`
AltIsMeta bool `hcl:"alt_is_meta" json:"alt-is-meta,omitempty"`
AltSendsWhat string `hcl:"alt_sends_what" json:"alt-sends-what,omitempty"`
AudibleBellSound string `hcl:"audible_bell_sound" json:"audible-bell-sound,omitempty"`
DesktopNotificationBell bool `hcl:"desktop_notification_bell" json:"desktop-notification-bell,omitempty"`
BackgroundColor string `hcl:"background_color" json:"background-color,omitempty"`
BackgroundImage string `hcl:"background_image" json:"background-image,omitempty"`
BackgroundSize string `hcl:"background_size" json:"background-size,omitempty"`
BackgroundPosition string `hcl:"background_position" json:"background-position,omitempty"`
BackspaceSendsBackspace bool `hcl:"backspace_sends_backspace" json:"backspace-sends-backspace,omitempty"`
CharacterMapOverrides map[string]map[string]string `hcl:"character_map_overrides" json:"character-map-overrides,omitempty"`
CloseOnExit bool `hcl:"close_on_exit" json:"close-on-exit,omitempty"`
CursorBlink bool `hcl:"cursor_blink" json:"cursor-blink,omitempty"`
CursorBlinkCycle [2]int `hcl:"cursor_blink_cycle" json:"cursor-blink-cycle,omitempty"`
CursorColor string `hcl:"cursor_color" json:"cursor-color,omitempty"`
ColorPaletteOverrides []*string `hcl:"color_palette_overrides" json:"color-palette-overrides,omitempty"`
CopyOnSelect bool `hcl:"copy_on_select" json:"copy-on-select,omitempty"`
UseDefaultWindowCopy bool `hcl:"use_default_window_copy" json:"use-default-window-copy,omitempty"`
ClearSelectionAfterCopy bool `hcl:"clear_selection_after_copy" json:"clear-selection-after-copy,omitempty"`
CtrlPlusMinusZeroZoom bool `hcl:"ctrl_plus_minus_zero_zoom" json:"ctrl-plus-minus-zero-zoom,omitempty"`
CtrlCCopy bool `hcl:"ctrl_c_copy" json:"ctrl-c-copy,omitempty"`
CtrlVPaste bool `hcl:"ctrl_v_paste" json:"ctrl-v-paste,omitempty"`
EastAsianAmbiguousAsTwoColumn bool `hcl:"east_asian_ambiguous_as_two_column" json:"east-asian-ambiguous-as-two-column,omitempty"`
Enable8BitControl *bool `hcl:"enable_8_bit_control" json:"enable-8-bit-control,omitempty"`
EnableBold *bool `hcl:"enable_bold" json:"enable-bold,omitempty"`
EnableBoldAsBright bool `hcl:"enable_bold_as_bright" json:"enable-bold-as-bright,omitempty"`
EnableClipboardNotice bool `hcl:"enable_clipboard_notice" json:"enable-clipboard-notice,omitempty"`
EnableClipboardWrite bool `hcl:"enable_clipboard_write" json:"enable-clipboard-write,omitempty"`
EnableDec12 bool `hcl:"enable_dec12" json:"enable-dec12,omitempty"`
Environment map[string]string `hcl:"environment" json:"environment,omitempty"`
FontFamily string `hcl:"font_family" json:"font-family,omitempty"`
FontSize int `hcl:"font_size" json:"font-size,omitempty"`
FontSmoothing string `hcl:"font_smoothing" json:"font-smoothing,omitempty"`
ForegroundColor string `hcl:"foreground_color" json:"foreground-color,omitempty"`
HomeKeysScroll bool `hcl:"home_keys_scroll" json:"home-keys-scroll,omitempty"`
Keybindings map[string]string `hcl:"keybindings" json:"keybindings,omitempty"`
MaxStringSequence int `hcl:"max_string_sequence" json:"max-string-sequence,omitempty"`
MediaKeysAreFkeys bool `hcl:"media_keys_are_fkeys" json:"media-keys-are-fkeys,omitempty"`
MetaSendsEscape bool `hcl:"meta_sends_escape" json:"meta-sends-escape,omitempty"`
MousePasteButton *int `hcl:"mouse_paste_button" json:"mouse-paste-button,omitempty"`
PageKeysScroll bool `hcl:"page_keys_scroll" json:"page-keys-scroll,omitempty"`
PassAltNumber *bool `hcl:"pass_alt_number" json:"pass-alt-number,omitempty"`
PassCtrlNumber *bool `hcl:"pass_ctrl_number" json:"pass-ctrl-number,omitempty"`
PassMetaNumber *bool `hcl:"pass_meta_number" json:"pass-meta-number,omitempty"`
PassMetaV bool `hcl:"pass_meta_v" json:"pass-meta-v,omitempty"`
ReceiveEncoding string `hcl:"receive_encoding" json:"receive-encoding,omitempty"`
ScrollOnKeystroke bool `hcl:"scroll_on_keystroke" json:"scroll-on-keystroke,omitempty"`
ScrollOnOutput bool `hcl:"scroll_on_output" json:"scroll-on-output,omitempty"`
ScrollbarVisible bool `hcl:"scrollbar_visible" json:"scrollbar-visible,omitempty"`
ScrollWheelMoveMultiplier int `hcl:"scroll_wheel_move_multiplier" json:"scroll-wheel-move-multiplier,omitempty"`
SendEncoding string `hcl:"send_encoding" json:"send-encoding,omitempty"`
ShiftInsertPaste bool `hcl:"shift_insert_paste" json:"shift-insert-paste,omitempty"`
UserCss string `hcl:"user_css" json:"user-css,omitempty"`
}

View File

@ -5,24 +5,22 @@ import (
"crypto/tls"
"crypto/x509"
"html/template"
"io/fs"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"regexp"
"strings"
noesctmpl "text/template"
"time"
"github.com/NYTimes/gziphandler"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/sorenisanerd/gotty/bindata"
"github.com/sorenisanerd/gotty/pkg/homedir"
"github.com/sorenisanerd/gotty/pkg/randomstring"
"github.com/sorenisanerd/gotty/webtty"
"github.com/yudai/gotty/pkg/homedir"
"github.com/yudai/gotty/pkg/randomstring"
"github.com/yudai/gotty/webtty"
)
// Server provides a webtty HTTP endpoint.
@ -30,22 +28,21 @@ type Server struct {
factory Factory
options *Options
upgrader *websocket.Upgrader
indexTemplate *template.Template
titleTemplate *noesctmpl.Template
manifestTemplate *template.Template
upgrader *websocket.Upgrader
indexTemplate *template.Template
titleTemplate *noesctmpl.Template
}
// New creates a new instance of Server.
// Server will use the New() of the factory provided to handle each request.
func New(factory Factory, options *Options) (*Server, error) {
indexData, err := bindata.Fs.ReadFile("static/index.html")
indexData, err := Asset("static/index.html")
if err != nil {
panic("index not found") // must be in bindata
}
if options.IndexFile != "" {
path := homedir.Expand(options.IndexFile)
indexData, err = os.ReadFile(path)
indexData, err = ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "failed to read custom index file at `%s`", path)
}
@ -55,15 +52,6 @@ func New(factory Factory, options *Options) (*Server, error) {
panic("index template parse failed") // must be valid
}
manifestData, err := bindata.Fs.ReadFile("static/manifest.json")
if err != nil {
panic("manifest not found") // must be in bindata
}
manifestTemplate, err := template.New("manifest").Parse(string(manifestData))
if err != nil {
panic("manifest template parse failed") // must be valid
}
titleTemplate, err := noesctmpl.New("title").Parse(options.TitleFormat)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse window title format `%s`", options.TitleFormat)
@ -90,9 +78,8 @@ func New(factory Factory, options *Options) (*Server, error) {
Subprotocols: webtty.Protocols,
CheckOrigin: originChekcer,
},
indexTemplate: indexTemplate,
titleTemplate: titleTemplate,
manifestTemplate: manifestTemplate,
indexTemplate: indexTemplate,
titleTemplate: titleTemplate,
}, nil
}
@ -108,16 +95,11 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
counter := newCounter(time.Duration(server.options.Timeout) * time.Second)
path := server.options.Path
path := "/"
if server.options.EnableRandomUrl {
path = "/" + randomstring.Generate(server.options.RandomUrlLength) + "/"
}
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
handlers := server.setupHandlers(cctx, cancel, path, counter)
srv, err := server.setupHTTPServer(handlers)
if err != nil {
@ -145,10 +127,10 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
scheme = "https"
}
host, port, _ := net.SplitHostPort(listener.Addr().String())
log.Printf("HTTP server is listening at: %s", scheme+"://"+net.JoinHostPort(host, port)+path)
log.Printf("HTTP server is listening at: %s", scheme+"://"+host+":"+port+path)
if server.options.Address == "0.0.0.0" {
for _, address := range listAddresses() {
log.Printf("Alternative URL: %s", scheme+"://"+net.JoinHostPort(address, port)+path)
log.Printf("Alternative URL: %s", scheme+"://"+address+":"+port+path)
}
}
@ -199,21 +181,16 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
}
func (server *Server) setupHandlers(ctx context.Context, cancel context.CancelFunc, pathPrefix string, counter *counter) http.Handler {
fs, err := fs.Sub(bindata.Fs, "static")
if err != nil {
log.Fatalf("failed to open static/ subdirectory of embedded filesystem: %v", err)
}
staticFileHandler := http.FileServer(http.FS(fs))
staticFileHandler := http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
)
var siteMux = http.NewServeMux()
siteMux.HandleFunc(pathPrefix, server.handleIndex)
siteMux.Handle(pathPrefix+"js/", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"favicon.ico", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"icon.svg", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"favicon.png", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"css/", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.Handle(pathPrefix+"icon_192.png", http.StripPrefix(pathPrefix, staticFileHandler))
siteMux.HandleFunc(pathPrefix+"manifest.json", server.handleManifest)
siteMux.HandleFunc(pathPrefix+"auth_token.js", server.handleAuthToken)
siteMux.HandleFunc(pathPrefix+"config.js", server.handleConfig)
@ -253,7 +230,7 @@ func (server *Server) setupHTTPServer(handler http.Handler) (*http.Server, error
func (server *Server) tlsConfig() (*tls.Config, error) {
caFile := homedir.Expand(server.options.TLSCACrtFile)
caCert, err := os.ReadFile(caFile)
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, errors.New("could not open CA crt file " + caFile)
}

View File

@ -1,7 +1,7 @@
package server
import (
"github.com/sorenisanerd/gotty/webtty"
"github.com/yudai/gotty/webtty"
)
// Slave is webtty.Slave with some additional methods.
@ -13,5 +13,5 @@ type Slave interface {
type Factory interface {
Name() string
New(params map[string][]string, headers map[string][]string) (Slave, error)
New(params map[string][]string) (Slave, error)
}

View File

@ -1,10 +1,7 @@
package server
import (
"io"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
type wsWrapper struct {
@ -31,11 +28,6 @@ func (wsw *wsWrapper) Read(p []byte) (n int, err error) {
continue
}
b, err := io.ReadAll(reader)
if len(b) > len(p) {
return 0, errors.Wrapf(err, "Client message exceeded buffer size")
}
n = copy(p, b)
return n, err
return reader.Read(p)
}
}

View File

@ -1,16 +1,17 @@
package utils
import (
"io/ioutil"
"log"
"os"
"reflect"
"strings"
"github.com/codegangsta/cli"
"github.com/fatih/structs"
"github.com/urfave/cli/v2"
"github.com/yudai/hcl"
"github.com/sorenisanerd/gotty/pkg/homedir"
"github.com/yudai/gotty/pkg/homedir"
)
func GenerateFlags(options ...interface{}) (flags []cli.Flag, mappings map[string]string, err error) {
@ -27,37 +28,32 @@ func GenerateFlags(options ...interface{}) (flags []cli.Flag, mappings map[strin
mappings[flagName] = field.Name()
flagShortName := field.Tag("flagSName")
var aliases []string
if flagShortName != "" {
aliases = []string{flagShortName}
flagName += ", " + flagShortName
}
flagDescription := field.Tag("flagDescribe")
switch field.Kind() {
case reflect.String:
flags = append(flags, &cli.StringFlag{
Name: flagName,
Value: field.Value().(string),
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
flags = append(flags, cli.StringFlag{
Name: flagName,
Value: field.Value().(string),
Usage: flagDescription,
EnvVar: envName,
})
case reflect.Bool:
flags = append(flags, &cli.BoolFlag{
Name: flagName,
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
DefaultText: field.Tag("default"),
flags = append(flags, cli.BoolFlag{
Name: flagName,
Usage: flagDescription,
EnvVar: envName,
})
case reflect.Int:
flags = append(flags, &cli.IntFlag{
Name: flagName,
Value: field.Value().(int),
Usage: flagDescription,
EnvVars: []string{envName},
Aliases: aliases,
flags = append(flags, cli.IntFlag{
Name: flagName,
Value: field.Value().(int),
Usage: flagDescription,
EnvVar: envName,
})
}
}
@ -113,7 +109,7 @@ func ApplyConfigFile(filePath string, options ...interface{}) error {
fileString := []byte{}
log.Printf("Loading config file at: %s", filePath)
fileString, err := os.ReadFile(filePath)
fileString, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}

1
vendor/github.com/NYTimes/gziphandler/.gitignore generated vendored Normal file
View File

@ -0,0 +1 @@
*.swp

6
vendor/github.com/NYTimes/gziphandler/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
language: go
go:
- 1.7
- 1.8
- tip

View File

@ -0,0 +1,75 @@
---
layout: code-of-conduct
version: v1.0
---
This code of conduct outlines our expectations for participants within the **NYTimes/gziphandler** community, as well as steps to reporting unacceptable behavior. We are committed to providing a welcoming and inspiring community for all and expect our code of conduct to be honored. Anyone who violates this code of conduct may be banned from the community.
Our open source community strives to:
* **Be friendly and patient.**
* **Be welcoming**: We strive to be a community that welcomes and supports people of all backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability.
* **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary language.
* **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. Its important to remember that a community where people feel uncomfortable or threatened is not a productive one.
* **Be careful in the words that we choose**: we are a community of professionals, and we conduct ourselves professionally. Be kind to others. Do not insult or put down other participants. Harassment and other exclusionary behavior aren't acceptable.
* **Try to understand why we disagree**: Disagreements, both social and technical, happen all the time. It is important that we resolve disagreements and differing views constructively. Remember that were different. The strength of our community comes from its diversity, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds a viewpoint doesnt mean that theyre wrong. Dont forget that it is human to err and blaming each other doesnt get us anywhere. Instead, focus on helping to resolve issues and learning from mistakes.
## Definitions
Harassment includes, but is not limited to:
- Offensive comments related to gender, gender identity and expression, sexual orientation, disability, mental illness, neuro(a)typicality, physical appearance, body size, race, age, regional discrimination, political or religious affiliation
- Unwelcome comments regarding a persons lifestyle choices and practices, including those related to food, health, parenting, drugs, and employment
- Deliberate misgendering. This includes deadnaming or persistently using a pronoun that does not correctly reflect a person's gender identity. You must address people by the name they give you when not addressing them by their username or handle
- Physical contact and simulated physical contact (eg, textual descriptions like “*hug*” or “*backrub*”) without consent or after a request to stop
- Threats of violence, both physical and psychological
- Incitement of violence towards any individual, including encouraging a person to commit suicide or to engage in self-harm
- Deliberate intimidation
- Stalking or following
- Harassing photography or recording, including logging online activity for harassment purposes
- Sustained disruption of discussion
- Unwelcome sexual attention, including gratuitous or off-topic sexual images or behaviour
- Pattern of inappropriate social contact, such as requesting/assuming inappropriate levels of intimacy with others
- Continued one-on-one communication after requests to cease
- Deliberate “outing” of any aspect of a persons identity without their consent except as necessary to protect others from intentional abuse
- Publication of non-harassing private communication
Our open source community prioritizes marginalized peoples safety over privileged peoples comfort. We will not act on complaints regarding:
- Reverse -isms, including reverse racism, reverse sexism, and cisphobia
- Reasonable communication of boundaries, such as “leave me alone,” “go away,” or “Im not discussing this with you”
- Refusal to explain or debate social justice concepts
- Communicating in a tone you dont find congenial
- Criticizing racist, sexist, cissexist, or otherwise oppressive behavior or assumptions
### Diversity Statement
We encourage everyone to participate and are committed to building a community for all. Although we will fail at times, we seek to treat everyone both as fairly and equally as possible. Whenever a participant has made a mistake, we expect them to take responsibility for it. If someone has been harmed or offended, it is our responsibility to listen carefully and respectfully, and do our best to right the wrong.
Although this list cannot be exhaustive, we explicitly honor diversity in age, gender, gender identity or expression, culture, ethnicity, language, national origin, political beliefs, profession, race, religion, sexual orientation, socioeconomic status, and technical ability. We will not tolerate discrimination based on any of the protected
characteristics above, including participants with disabilities.
### Reporting Issues
If you experience or witness unacceptable behavior—or have any other concerns—please report it by contacting us via **code@nytimes.com**. All reports will be handled with discretion. In your report please include:
- Your contact information.
- Names (real, nicknames, or pseudonyms) of any individuals involved. If there are additional witnesses, please
include them as well. Your account of what occurred, and if you believe the incident is ongoing. If there is a publicly available record (e.g. a mailing list archive or a public IRC logger), please include a link.
- Any additional information that may be helpful.
After filing a report, a representative will contact you personally, review the incident, follow up with any additional questions, and make a decision as to how to respond. If the person who is harassing you is part of the response team, they will recuse themselves from handling your incident. If the complaint originates from a member of the response team, it will be handled by a different member of the response team. We will respect confidentiality requests for the purpose of protecting victims of abuse.
### Attribution & Acknowledgements
We all stand on the shoulders of giants across many open source communities. We'd like to thank the communities and projects that established code of conducts and diversity statements as our inspiration:
* [Django](https://www.djangoproject.com/conduct/reporting/)
* [Python](https://www.python.org/community/diversity/)
* [Ubuntu](http://www.ubuntu.com/about/about-ubuntu/conduct)
* [Contributor Covenant](http://contributor-covenant.org/)
* [Geek Feminism](http://geekfeminism.org/about/code-of-conduct/)
* [Citizen Code of Conduct](http://citizencodeofconduct.org/)
This Code of Conduct was based on https://github.com/todogroup/opencodeofconduct

30
vendor/github.com/NYTimes/gziphandler/CONTRIBUTING.md generated vendored Normal file
View File

@ -0,0 +1,30 @@
# Contributing to NYTimes/gziphandler
This is an open source project started by handful of developers at The New York Times and open to the entire Go community.
We really appreciate your help!
## Filing issues
When filing an issue, make sure to answer these five questions:
1. What version of Go are you using (`go version`)?
2. What operating system and processor architecture are you using?
3. What did you do?
4. What did you expect to see?
5. What did you see instead?
## Contributing code
Before submitting changes, please follow these guidelines:
1. Check the open issues and pull requests for existing discussions.
2. Open an issue to discuss a new feature.
3. Write tests.
4. Make sure code follows the ['Go Code Review Comments'](https://github.com/golang/go/wiki/CodeReviewComments).
5. Make sure your changes pass `go test`.
6. Make sure the entire test suite passes locally and on Travis CI.
7. Open a Pull Request.
8. [Squash your commits](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) after receiving feedback and add a [great commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
Unless otherwise noted, the gziphandler source files are distributed under the Apache 2.0-style license found in the LICENSE.md file.

13
vendor/github.com/NYTimes/gziphandler/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,13 @@
Copyright (c) 2015 The New York Times Company
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this library except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

52
vendor/github.com/NYTimes/gziphandler/README.md generated vendored Normal file
View File

@ -0,0 +1,52 @@
Gzip Handler
============
This is a tiny Go package which wraps HTTP handlers to transparently gzip the
response body, for clients which support it. Although it's usually simpler to
leave that to a reverse proxy (like nginx or Varnish), this package is useful
when that's undesirable.
## Usage
Call `GzipHandler` with any handler (an object which implements the
`http.Handler` interface), and it'll return a new handler which gzips the
response. For example:
```go
package main
import (
"io"
"net/http"
"github.com/NYTimes/gziphandler"
)
func main() {
withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
io.WriteString(w, "Hello, World")
})
withGz := gziphandler.GzipHandler(withoutGz)
http.Handle("/", withGz)
http.ListenAndServe("0.0.0.0:8000", nil)
}
```
## Documentation
The docs can be found at [godoc.org][docs], as usual.
## License
[Apache 2.0][license].
[docs]: https://godoc.org/github.com/nytimes/gziphandler
[license]: https://github.com/nytimes/gziphandler/blob/master/LICENSE.md

407
vendor/github.com/NYTimes/gziphandler/gzip.go generated vendored Normal file
View File

@ -0,0 +1,407 @@
package gziphandler
import (
"bufio"
"compress/gzip"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
)
const (
vary = "Vary"
acceptEncoding = "Accept-Encoding"
contentEncoding = "Content-Encoding"
contentType = "Content-Type"
contentLength = "Content-Length"
)
type codings map[string]float64
const (
// DefaultQValue is the default qvalue to assign to an encoding if no explicit qvalue is set.
// This is actually kind of ambiguous in RFC 2616, so hopefully it's correct.
// The examples seem to indicate that it is.
DefaultQValue = 1.0
// DefaultMinSize defines the minimum size to reach to enable compression.
// It's 512 bytes.
DefaultMinSize = 512
)
// gzipWriterPools stores a sync.Pool for each compression level for reuse of
// gzip.Writers. Use poolIndex to covert a compression level to an index into
// gzipWriterPools.
var gzipWriterPools [gzip.BestCompression - gzip.BestSpeed + 2]*sync.Pool
func init() {
for i := gzip.BestSpeed; i <= gzip.BestCompression; i++ {
addLevelPool(i)
}
addLevelPool(gzip.DefaultCompression)
}
// poolIndex maps a compression level to its index into gzipWriterPools. It
// assumes that level is a valid gzip compression level.
func poolIndex(level int) int {
// gzip.DefaultCompression == -1, so we need to treat it special.
if level == gzip.DefaultCompression {
return gzip.BestCompression - gzip.BestSpeed + 1
}
return level - gzip.BestSpeed
}
func addLevelPool(level int) {
gzipWriterPools[poolIndex(level)] = &sync.Pool{
New: func() interface{} {
// NewWriterLevel only returns error on a bad level, we are guaranteeing
// that this will be a valid level so it is okay to ignore the returned
// error.
w, _ := gzip.NewWriterLevel(nil, level)
return w
},
}
}
// GzipResponseWriter provides an http.ResponseWriter interface, which gzips
// bytes before writing them to the underlying response. This doesn't close the
// writers, so don't forget to do that.
// It can be configured to skip response smaller than minSize.
type GzipResponseWriter struct {
http.ResponseWriter
index int // Index for gzipWriterPools.
gw *gzip.Writer
code int // Saves the WriteHeader value.
minSize int // Specifed the minimum response size to gzip. If the response length is bigger than this value, it is compressed.
buf []byte // Holds the first part of the write before reaching the minSize or the end of the write.
contentTypes []string // Only compress if the response is one of these content-types. All are accepted if empty.
}
// Write appends data to the gzip writer.
func (w *GzipResponseWriter) Write(b []byte) (int, error) {
// If content type is not set.
if _, ok := w.Header()[contentType]; !ok {
// It infer it from the uncompressed body.
w.Header().Set(contentType, http.DetectContentType(b))
}
// GZIP responseWriter is initialized. Use the GZIP responseWriter.
if w.gw != nil {
n, err := w.gw.Write(b)
return n, err
}
// Save the write into a buffer for later use in GZIP responseWriter (if content is long enough) or at close with regular responseWriter.
// On the first write, w.buf changes from nil to a valid slice
w.buf = append(w.buf, b...)
// If the global writes are bigger than the minSize and we're about to write
// a response containing a content type we want to handle, enable
// compression.
if len(w.buf) >= w.minSize && handleContentType(w.contentTypes, w) {
err := w.startGzip()
if err != nil {
return 0, err
}
}
return len(b), nil
}
// startGzip initialize any GZIP specific informations.
func (w *GzipResponseWriter) startGzip() error {
// Set the GZIP header.
w.Header().Set(contentEncoding, "gzip")
// if the Content-Length is already set, then calls to Write on gzip
// will fail to set the Content-Length header since its already set
// See: https://github.com/golang/go/issues/14975.
w.Header().Del(contentLength)
// Write the header to gzip response.
if w.code != 0 {
w.ResponseWriter.WriteHeader(w.code)
}
// Initialize the GZIP response.
w.init()
// Flush the buffer into the gzip reponse.
n, err := w.gw.Write(w.buf)
// This should never happen (per io.Writer docs), but if the write didn't
// accept the entire buffer but returned no specific error, we have no clue
// what's going on, so abort just to be safe.
if err == nil && n < len(w.buf) {
return io.ErrShortWrite
}
w.buf = nil
return err
}
// WriteHeader just saves the response code until close or GZIP effective writes.
func (w *GzipResponseWriter) WriteHeader(code int) {
w.code = code
}
// init graps a new gzip writer from the gzipWriterPool and writes the correct
// content encoding header.
func (w *GzipResponseWriter) init() {
// Bytes written during ServeHTTP are redirected to this gzip writer
// before being written to the underlying response.
gzw := gzipWriterPools[w.index].Get().(*gzip.Writer)
gzw.Reset(w.ResponseWriter)
w.gw = gzw
}
// Close will close the gzip.Writer and will put it back in the gzipWriterPool.
func (w *GzipResponseWriter) Close() error {
if w.gw == nil {
// Gzip not trigged yet, write out regular response.
if w.code != 0 {
w.ResponseWriter.WriteHeader(w.code)
}
if w.buf != nil {
_, writeErr := w.ResponseWriter.Write(w.buf)
// Returns the error if any at write.
if writeErr != nil {
return fmt.Errorf("gziphandler: write to regular responseWriter at close gets error: %q", writeErr.Error())
}
}
return nil
}
err := w.gw.Close()
gzipWriterPools[w.index].Put(w.gw)
w.gw = nil
return err
}
// Flush flushes the underlying *gzip.Writer and then the underlying
// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter
// an http.Flusher.
func (w *GzipResponseWriter) Flush() {
if w.gw != nil {
w.gw.Flush()
}
if fw, ok := w.ResponseWriter.(http.Flusher); ok {
fw.Flush()
}
}
// Hijack implements http.Hijacker. If the underlying ResponseWriter is a
// Hijacker, its Hijack method is returned. Otherwise an error is returned.
func (w *GzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := w.ResponseWriter.(http.Hijacker); ok {
return hj.Hijack()
}
return nil, nil, fmt.Errorf("http.Hijacker interface is not supported")
}
// verify Hijacker interface implementation
var _ http.Hijacker = &GzipResponseWriter{}
// MustNewGzipLevelHandler behaves just like NewGzipLevelHandler except that in
// an error case it panics rather than returning an error.
func MustNewGzipLevelHandler(level int) func(http.Handler) http.Handler {
wrap, err := NewGzipLevelHandler(level)
if err != nil {
panic(err)
}
return wrap
}
// NewGzipLevelHandler returns a wrapper function (often known as middleware)
// which can be used to wrap an HTTP handler to transparently gzip the response
// body if the client supports it (via the Accept-Encoding header). Responses will
// be encoded at the given gzip compression level. An error will be returned only
// if an invalid gzip compression level is given, so if one can ensure the level
// is valid, the returned error can be safely ignored.
func NewGzipLevelHandler(level int) (func(http.Handler) http.Handler, error) {
return NewGzipLevelAndMinSize(level, DefaultMinSize)
}
// NewGzipLevelAndMinSize behave as NewGzipLevelHandler except it let the caller
// specify the minimum size before compression.
func NewGzipLevelAndMinSize(level, minSize int) (func(http.Handler) http.Handler, error) {
return GzipHandlerWithOpts(CompressionLevel(level), MinSize(minSize))
}
func GzipHandlerWithOpts(opts ...option) (func(http.Handler) http.Handler, error) {
c := &config{
level: gzip.DefaultCompression,
minSize: DefaultMinSize,
}
for _, o := range opts {
o(c)
}
if err := c.validate(); err != nil {
return nil, err
}
return func(h http.Handler) http.Handler {
index := poolIndex(c.level)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(vary, acceptEncoding)
if acceptsGzip(r) {
gw := &GzipResponseWriter{
ResponseWriter: w,
index: index,
minSize: c.minSize,
contentTypes: c.contentTypes,
}
defer gw.Close()
h.ServeHTTP(gw, r)
} else {
h.ServeHTTP(w, r)
}
})
}, nil
}
// Used for functional configuration.
type config struct {
minSize int
level int
contentTypes []string
}
func (c *config) validate() error {
if c.level != gzip.DefaultCompression && (c.level < gzip.BestSpeed || c.level > gzip.BestCompression) {
return fmt.Errorf("invalid compression level requested: %d", c.level)
}
if c.minSize < 0 {
return fmt.Errorf("minimum size must be more than zero")
}
return nil
}
type option func(c *config)
func MinSize(size int) option {
return func(c *config) {
c.minSize = size
}
}
func CompressionLevel(level int) option {
return func(c *config) {
c.level = level
}
}
func ContentTypes(types []string) option {
return func(c *config) {
c.contentTypes = []string{}
for _, v := range types {
c.contentTypes = append(c.contentTypes, strings.ToLower(v))
}
}
}
// GzipHandler wraps an HTTP handler, to transparently gzip the response body if
// the client supports it (via the Accept-Encoding header). This will compress at
// the default compression level.
func GzipHandler(h http.Handler) http.Handler {
wrapper, _ := NewGzipLevelHandler(gzip.DefaultCompression)
return wrapper(h)
}
// acceptsGzip returns true if the given HTTP request indicates that it will
// accept a gzipped response.
func acceptsGzip(r *http.Request) bool {
acceptedEncodings, _ := parseEncodings(r.Header.Get(acceptEncoding))
return acceptedEncodings["gzip"] > 0.0
}
// returns true if we've been configured to compress the specific content type.
func handleContentType(contentTypes []string, w http.ResponseWriter) bool {
// If contentTypes is empty we handle all content types.
if len(contentTypes) == 0 {
return true
}
ct := strings.ToLower(w.Header().Get(contentType))
for _, c := range contentTypes {
if c == ct {
return true
}
}
return false
}
// parseEncodings attempts to parse a list of codings, per RFC 2616, as might
// appear in an Accept-Encoding header. It returns a map of content-codings to
// quality values, and an error containing the errors encountered. It's probably
// safe to ignore those, because silently ignoring errors is how the internet
// works.
//
// See: http://tools.ietf.org/html/rfc2616#section-14.3.
func parseEncodings(s string) (codings, error) {
c := make(codings)
var e []string
for _, ss := range strings.Split(s, ",") {
coding, qvalue, err := parseCoding(ss)
if err != nil {
e = append(e, err.Error())
} else {
c[coding] = qvalue
}
}
// TODO (adammck): Use a proper multi-error struct, so the individual errors
// can be extracted if anyone cares.
if len(e) > 0 {
return c, fmt.Errorf("errors while parsing encodings: %s", strings.Join(e, ", "))
}
return c, nil
}
// parseCoding parses a single conding (content-coding with an optional qvalue),
// as might appear in an Accept-Encoding header. It attempts to forgive minor
// formatting errors.
func parseCoding(s string) (coding string, qvalue float64, err error) {
for n, part := range strings.Split(s, ";") {
part = strings.TrimSpace(part)
qvalue = DefaultQValue
if n == 0 {
coding = strings.ToLower(part)
} else if strings.HasPrefix(part, "q=") {
qvalue, err = strconv.ParseFloat(strings.TrimPrefix(part, "q="), 64)
if qvalue < 0.0 {
qvalue = 0.0
} else if qvalue > 1.0 {
qvalue = 1.0
}
}
}
if coding == "" {
err = fmt.Errorf("empty content-coding")
}
return
}

43
vendor/github.com/NYTimes/gziphandler/gzip_go18.go generated vendored Normal file
View File

@ -0,0 +1,43 @@
// +build go1.8
package gziphandler
import "net/http"
// Push initiates an HTTP/2 server push.
// Push returns ErrNotSupported if the client has disabled push or if push
// is not supported on the underlying connection.
func (w *GzipResponseWriter) Push(target string, opts *http.PushOptions) error {
pusher, ok := w.ResponseWriter.(http.Pusher)
if ok && pusher != nil {
return pusher.Push(target, setAcceptEncodingForPushOptions(opts))
}
return http.ErrNotSupported
}
// setAcceptEncodingForPushOptions sets "Accept-Encoding" : "gzip" for PushOptions without overriding existing headers.
func setAcceptEncodingForPushOptions(opts *http.PushOptions) *http.PushOptions {
if opts == nil {
opts = &http.PushOptions{
Header: http.Header{
acceptEncoding: []string{"gzip"},
},
}
return opts
}
if opts.Header == nil {
opts.Header = http.Header{
acceptEncoding: []string{"gzip"},
}
return opts
}
if encoding := opts.Header.Get(acceptEncoding); encoding == "" {
opts.Header.Add(acceptEncoding, "gzip")
return opts
}
return opts
}

2
vendor/github.com/codegangsta/cli/.gitignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
*.coverprofile
node_modules/

39
vendor/github.com/codegangsta/cli/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,39 @@
language: go
sudo: false
cache:
directories:
- node_modules
go:
- 1.2.x
- 1.3.x
- 1.4.2
- 1.5.x
- 1.6.x
- 1.7.x
- master
matrix:
allow_failures:
- go: master
include:
- go: 1.6.x
os: osx
- go: 1.7.x
os: osx
before_script:
- go get github.com/urfave/gfmrun/... || true
- go get golang.org/x/tools/... || true
- if [ ! -f node_modules/.bin/markdown-toc ] ; then
npm install markdown-toc ;
fi
script:
- ./runtests gen
- ./runtests vet
- ./runtests test
- ./runtests gfmrun
- ./runtests toc

392
vendor/github.com/codegangsta/cli/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,392 @@
# Change Log
**ATTN**: This project uses [semantic versioning](http://semver.org/).
## [Unreleased]
## [1.19.1] - 2016-11-21
### Fixed
- Fixes regression introduced in 1.19.0 where using an `ActionFunc` as
the `Action` for a command would cause it to error rather than calling the
function. Should not have a affected declarative cases using `func(c
*cli.Context) err)`.
- Shell completion now handles the case where the user specifies
`--generate-bash-completion` immediately after a flag that takes an argument.
Previously it call the application with `--generate-bash-completion` as the
flag value.
## [1.19.0] - 2016-11-19
### Added
- `FlagsByName` was added to make it easy to sort flags (e.g. `sort.Sort(cli.FlagsByName(app.Flags))`)
- A `Description` field was added to `App` for a more detailed description of
the application (similar to the existing `Description` field on `Command`)
- Flag type code generation via `go generate`
- Write to stderr and exit 1 if action returns non-nil error
- Added support for TOML to the `altsrc` loader
- `SkipArgReorder` was added to allow users to skip the argument reordering.
This is useful if you want to consider all "flags" after an argument as
arguments rather than flags (the default behavior of the stdlib `flag`
library). This is backported functionality from the [removal of the flag
reordering](https://github.com/urfave/cli/pull/398) in the unreleased version
2
- For formatted errors (those implementing `ErrorFormatter`), the errors will
be formatted during output. Compatible with `pkg/errors`.
### Changed
- Raise minimum tested/supported Go version to 1.2+
### Fixed
- Consider empty environment variables as set (previously environment variables
with the equivalent of `""` would be skipped rather than their value used).
- Return an error if the value in a given environment variable cannot be parsed
as the flag type. Previously these errors were silently swallowed.
- Print full error when an invalid flag is specified (which includes the invalid flag)
- `App.Writer` defaults to `stdout` when `nil`
- If no action is specified on a command or app, the help is now printed instead of `panic`ing
- `App.Metadata` is initialized automatically now (previously was `nil` unless initialized)
- Correctly show help message if `-h` is provided to a subcommand
- `context.(Global)IsSet` now respects environment variables. Previously it
would return `false` if a flag was specified in the environment rather than
as an argument
- Removed deprecation warnings to STDERR to avoid them leaking to the end-user
- `altsrc`s import paths were updated to use `gopkg.in/urfave/cli.v1`. This
fixes issues that occurred when `gopkg.in/urfave/cli.v1` was imported as well
as `altsrc` where Go would complain that the types didn't match
## [1.18.1] - 2016-08-28
### Fixed
- Removed deprecation warnings to STDERR to avoid them leaking to the end-user (backported)
## [1.18.0] - 2016-06-27
### Added
- `./runtests` test runner with coverage tracking by default
- testing on OS X
- testing on Windows
- `UintFlag`, `Uint64Flag`, and `Int64Flag` types and supporting code
### Changed
- Use spaces for alignment in help/usage output instead of tabs, making the
output alignment consistent regardless of tab width
### Fixed
- Printing of command aliases in help text
- Printing of visible flags for both struct and struct pointer flags
- Display the `help` subcommand when using `CommandCategories`
- No longer swallows `panic`s that occur within the `Action`s themselves when
detecting the signature of the `Action` field
## [1.17.1] - 2016-08-28
### Fixed
- Removed deprecation warnings to STDERR to avoid them leaking to the end-user
## [1.17.0] - 2016-05-09
### Added
- Pluggable flag-level help text rendering via `cli.DefaultFlagStringFunc`
- `context.GlobalBoolT` was added as an analogue to `context.GlobalBool`
- Support for hiding commands by setting `Hidden: true` -- this will hide the
commands in help output
### Changed
- `Float64Flag`, `IntFlag`, and `DurationFlag` default values are no longer
quoted in help text output.
- All flag types now include `(default: {value})` strings following usage when a
default value can be (reasonably) detected.
- `IntSliceFlag` and `StringSliceFlag` usage strings are now more consistent
with non-slice flag types
- Apps now exit with a code of 3 if an unknown subcommand is specified
(previously they printed "No help topic for...", but still exited 0. This
makes it easier to script around apps built using `cli` since they can trust
that a 0 exit code indicated a successful execution.
- cleanups based on [Go Report Card
feedback](https://goreportcard.com/report/github.com/urfave/cli)
## [1.16.1] - 2016-08-28
### Fixed
- Removed deprecation warnings to STDERR to avoid them leaking to the end-user
## [1.16.0] - 2016-05-02
### Added
- `Hidden` field on all flag struct types to omit from generated help text
### Changed
- `BashCompletionFlag` (`--enable-bash-completion`) is now omitted from
generated help text via the `Hidden` field
### Fixed
- handling of error values in `HandleAction` and `HandleExitCoder`
## [1.15.0] - 2016-04-30
### Added
- This file!
- Support for placeholders in flag usage strings
- `App.Metadata` map for arbitrary data/state management
- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after
parsing.
- Support for nested lookup of dot-delimited keys in structures loaded from
YAML.
### Changed
- The `App.Action` and `Command.Action` now prefer a return signature of
`func(*cli.Context) error`, as defined by `cli.ActionFunc`. If a non-nil
`error` is returned, there may be two outcomes:
- If the error fulfills `cli.ExitCoder`, then `os.Exit` will be called
automatically
- Else the error is bubbled up and returned from `App.Run`
- Specifying an `Action` with the legacy return signature of
`func(*cli.Context)` will produce a deprecation message to stderr
- Specifying an `Action` that is not a `func` type will produce a non-zero exit
from `App.Run`
- Specifying an `Action` func that has an invalid (input) signature will
produce a non-zero exit from `App.Run`
### Deprecated
- <a name="deprecated-cli-app-runandexitonerror"></a>
`cli.App.RunAndExitOnError`, which should now be done by returning an error
that fulfills `cli.ExitCoder` to `cli.App.Run`.
- <a name="deprecated-cli-app-action-signature"></a> the legacy signature for
`cli.App.Action` of `func(*cli.Context)`, which should now have a return
signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`.
### Fixed
- Added missing `*cli.Context.GlobalFloat64` method
## [1.14.0] - 2016-04-03 (backfilled 2016-04-25)
### Added
- Codebeat badge
- Support for categorization via `CategorizedHelp` and `Categories` on app.
### Changed
- Use `filepath.Base` instead of `path.Base` in `Name` and `HelpName`.
### Fixed
- Ensure version is not shown in help text when `HideVersion` set.
## [1.13.0] - 2016-03-06 (backfilled 2016-04-25)
### Added
- YAML file input support.
- `NArg` method on context.
## [1.12.0] - 2016-02-17 (backfilled 2016-04-25)
### Added
- Custom usage error handling.
- Custom text support in `USAGE` section of help output.
- Improved help messages for empty strings.
- AppVeyor CI configuration.
### Changed
- Removed `panic` from default help printer func.
- De-duping and optimizations.
### Fixed
- Correctly handle `Before`/`After` at command level when no subcommands.
- Case of literal `-` argument causing flag reordering.
- Environment variable hints on Windows.
- Docs updates.
## [1.11.1] - 2015-12-21 (backfilled 2016-04-25)
### Changed
- Use `path.Base` in `Name` and `HelpName`
- Export `GetName` on flag types.
### Fixed
- Flag parsing when skipping is enabled.
- Test output cleanup.
- Move completion check to account for empty input case.
## [1.11.0] - 2015-11-15 (backfilled 2016-04-25)
### Added
- Destination scan support for flags.
- Testing against `tip` in Travis CI config.
### Changed
- Go version in Travis CI config.
### Fixed
- Removed redundant tests.
- Use correct example naming in tests.
## [1.10.2] - 2015-10-29 (backfilled 2016-04-25)
### Fixed
- Remove unused var in bash completion.
## [1.10.1] - 2015-10-21 (backfilled 2016-04-25)
### Added
- Coverage and reference logos in README.
### Fixed
- Use specified values in help and version parsing.
- Only display app version and help message once.
## [1.10.0] - 2015-10-06 (backfilled 2016-04-25)
### Added
- More tests for existing functionality.
- `ArgsUsage` at app and command level for help text flexibility.
### Fixed
- Honor `HideHelp` and `HideVersion` in `App.Run`.
- Remove juvenile word from README.
## [1.9.0] - 2015-09-08 (backfilled 2016-04-25)
### Added
- `FullName` on command with accompanying help output update.
- Set default `$PROG` in bash completion.
### Changed
- Docs formatting.
### Fixed
- Removed self-referential imports in tests.
## [1.8.0] - 2015-06-30 (backfilled 2016-04-25)
### Added
- Support for `Copyright` at app level.
- `Parent` func at context level to walk up context lineage.
### Fixed
- Global flag processing at top level.
## [1.7.1] - 2015-06-11 (backfilled 2016-04-25)
### Added
- Aggregate errors from `Before`/`After` funcs.
- Doc comments on flag structs.
- Include non-global flags when checking version and help.
- Travis CI config updates.
### Fixed
- Ensure slice type flags have non-nil values.
- Collect global flags from the full command hierarchy.
- Docs prose.
## [1.7.0] - 2015-05-03 (backfilled 2016-04-25)
### Changed
- `HelpPrinter` signature includes output writer.
### Fixed
- Specify go 1.1+ in docs.
- Set `Writer` when running command as app.
## [1.6.0] - 2015-03-23 (backfilled 2016-04-25)
### Added
- Multiple author support.
- `NumFlags` at context level.
- `Aliases` at command level.
### Deprecated
- `ShortName` at command level.
### Fixed
- Subcommand help output.
- Backward compatible support for deprecated `Author` and `Email` fields.
- Docs regarding `Names`/`Aliases`.
## [1.5.0] - 2015-02-20 (backfilled 2016-04-25)
### Added
- `After` hook func support at app and command level.
### Fixed
- Use parsed context when running command as subcommand.
- Docs prose.
## [1.4.1] - 2015-01-09 (backfilled 2016-04-25)
### Added
- Support for hiding `-h / --help` flags, but not `help` subcommand.
- Stop flag parsing after `--`.
### Fixed
- Help text for generic flags to specify single value.
- Use double quotes in output for defaults.
- Use `ParseInt` instead of `ParseUint` for int environment var values.
- Use `0` as base when parsing int environment var values.
## [1.4.0] - 2014-12-12 (backfilled 2016-04-25)
### Added
- Support for environment variable lookup "cascade".
- Support for `Stdout` on app for output redirection.
### Fixed
- Print command help instead of app help in `ShowCommandHelp`.
## [1.3.1] - 2014-11-13 (backfilled 2016-04-25)
### Added
- Docs and example code updates.
### Changed
- Default `-v / --version` flag made optional.
## [1.3.0] - 2014-08-10 (backfilled 2016-04-25)
### Added
- `FlagNames` at context level.
- Exposed `VersionPrinter` var for more control over version output.
- Zsh completion hook.
- `AUTHOR` section in default app help template.
- Contribution guidelines.
- `DurationFlag` type.
## [1.2.0] - 2014-08-02
### Added
- Support for environment variable defaults on flags plus tests.
## [1.1.0] - 2014-07-15
### Added
- Bash completion.
- Optional hiding of built-in help command.
- Optional skipping of flag parsing at command level.
- `Author`, `Email`, and `Compiled` metadata on app.
- `Before` hook func support at app and command level.
- `CommandNotFound` func support at app level.
- Command reference available on context.
- `GenericFlag` type.
- `Float64Flag` type.
- `BoolTFlag` type.
- `IsSet` flag helper on context.
- More flag lookup funcs at context level.
- More tests &amp; docs.
### Changed
- Help template updates to account for presence/absence of flags.
- Separated subcommand help template.
- Exposed `HelpPrinter` var for more control over help output.
## [1.0.0] - 2013-11-01
### Added
- `help` flag in default app flag set and each command flag set.
- Custom handling of argument parsing errors.
- Command lookup by name at app level.
- `StringSliceFlag` type and supporting `StringSlice` type.
- `IntSliceFlag` type and supporting `IntSlice` type.
- Slice type flag lookups by name at context level.
- Export of app and command help functions.
- More tests &amp; docs.
## 0.1.0 - 2013-07-22
### Added
- Initial implementation.
[Unreleased]: https://github.com/urfave/cli/compare/v1.18.0...HEAD
[1.18.0]: https://github.com/urfave/cli/compare/v1.17.0...v1.18.0
[1.17.0]: https://github.com/urfave/cli/compare/v1.16.0...v1.17.0
[1.16.0]: https://github.com/urfave/cli/compare/v1.15.0...v1.16.0
[1.15.0]: https://github.com/urfave/cli/compare/v1.14.0...v1.15.0
[1.14.0]: https://github.com/urfave/cli/compare/v1.13.0...v1.14.0
[1.13.0]: https://github.com/urfave/cli/compare/v1.12.0...v1.13.0
[1.12.0]: https://github.com/urfave/cli/compare/v1.11.1...v1.12.0
[1.11.1]: https://github.com/urfave/cli/compare/v1.11.0...v1.11.1
[1.11.0]: https://github.com/urfave/cli/compare/v1.10.2...v1.11.0
[1.10.2]: https://github.com/urfave/cli/compare/v1.10.1...v1.10.2
[1.10.1]: https://github.com/urfave/cli/compare/v1.10.0...v1.10.1
[1.10.0]: https://github.com/urfave/cli/compare/v1.9.0...v1.10.0
[1.9.0]: https://github.com/urfave/cli/compare/v1.8.0...v1.9.0
[1.8.0]: https://github.com/urfave/cli/compare/v1.7.1...v1.8.0
[1.7.1]: https://github.com/urfave/cli/compare/v1.7.0...v1.7.1
[1.7.0]: https://github.com/urfave/cli/compare/v1.6.0...v1.7.0
[1.6.0]: https://github.com/urfave/cli/compare/v1.5.0...v1.6.0
[1.5.0]: https://github.com/urfave/cli/compare/v1.4.1...v1.5.0
[1.4.1]: https://github.com/urfave/cli/compare/v1.4.0...v1.4.1
[1.4.0]: https://github.com/urfave/cli/compare/v1.3.1...v1.4.0
[1.3.1]: https://github.com/urfave/cli/compare/v1.3.0...v1.3.1
[1.3.0]: https://github.com/urfave/cli/compare/v1.2.0...v1.3.0
[1.2.0]: https://github.com/urfave/cli/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/urfave/cli/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/urfave/cli/compare/v0.1.0...v1.0.0

21
vendor/github.com/codegangsta/cli/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
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.

1364
vendor/github.com/codegangsta/cli/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

492
vendor/github.com/codegangsta/cli/app.go generated vendored Normal file
View File

@ -0,0 +1,492 @@
package cli
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"time"
)
var (
changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md"
appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", 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
HideHelp bool
// Boolean to hide built-in version flag and the VERSION section of help
HideVersion bool
// Populate on app startup, only gettable through method Categories()
categories CommandCategories
// An action to execute when the bash-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
// Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
// *Note*: support for the deprecated `Action` signature will be removed in a future version
Action interface{}
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc
// Execute this function if an 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
// Name of Author (Note: Use App.Authors, this is deprecated)
Author string
// Email of Author (Note: Use App.Authors, this is deprecated)
Email string
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
ErrWriter io.Writer
// Other custom info
Metadata map[string]interface{}
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: "",
Version: "0.0.0",
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
Writer: os.Stdout,
}
}
// 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.Author != "" || a.Email != "" {
a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
}
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
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
if (HelpFlag != BoolFlag{}) {
a.appendFlag(HelpFlag)
}
}
if !a.HideVersion {
a.appendFlag(VersionFlag)
}
a.categories = CommandCategories{}
for _, command := range a.Commands {
a.categories = a.categories.AddCommand(command.Category, command)
}
sort.Sort(a.categories)
if a.Metadata == nil {
a.Metadata = make(map[string]interface{})
}
if a.Writer == nil {
a.Writer = os.Stdout
}
}
// 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) {
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)
// parse flags
set, err := flagSet(a.Name, a.Flags)
if err != nil {
return err
}
set.SetOutput(ioutil.Discard)
err = set.Parse(arguments[1:])
nerr := normalizeFlags(a.Flags, set)
context := NewContext(a, set, nil)
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)
HandleExitCoder(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
}
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 {
fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
ShowAppHelp(context)
HandleExitCoder(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 = HandleAction(a.Action, context)
HandleExitCoder(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 eror
// 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) {
// append help to commands
if len(a.Commands) > 0 {
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
if (HelpFlag != BoolFlag{}) {
a.appendFlag(HelpFlag)
}
}
}
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
// parse flags
set, err := flagSet(a.Name, a.Flags)
if err != nil {
return err
}
set.SetOutput(ioutil.Discard)
err = set.Parse(ctx.Args().Tail())
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)
HandleExitCoder(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
}
}
if a.After != nil {
defer func() {
afterErr := a.After(context)
if afterErr != nil {
HandleExitCoder(err)
if err != nil {
err = NewMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if a.Before != nil {
beforeErr := a.Before(context)
if beforeErr != nil {
HandleExitCoder(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 = HandleAction(a.Action, context)
HandleExitCoder(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
}
// Categories returns a slice containing all the categories with the commands they contain
func (a *App) Categories() CommandCategories {
return a.categories
}
// VisibleCategories returns a slice of categories and commands that are
// Hidden=false
func (a *App) VisibleCategories() []*CommandCategory {
ret := []*CommandCategory{}
for _, category := range a.categories {
if visible := func() *CommandCategory {
for _, command := range category.Commands {
if !command.Hidden {
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 {
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) hasFlag(flag Flag) bool {
for _, f := range a.Flags {
if flag == f {
return true
}
}
return false
}
func (a *App) errWriter() io.Writer {
// When the app ErrWriter is nil use the package level one.
if a.ErrWriter == nil {
return ErrWriter
}
return a.ErrWriter
}
func (a *App) appendFlag(flag Flag) {
if !a.hasFlag(flag) {
a.Flags = append(a.Flags, flag)
}
}
// 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) {
if a, ok := action.(ActionFunc); ok {
return a(context)
} else if a, ok := action.(func(*Context) error); ok {
return a(context)
} else if a, ok := action.(func(*Context)); ok { // deprecated function signature
a(context)
return nil
} else {
return errInvalidActionType
}
}

24
vendor/github.com/codegangsta/cli/appveyor.yml generated vendored Normal file
View File

@ -0,0 +1,24 @@
version: "{build}"
os: Windows Server 2012 R2
clone_folder: c:\gopath\src\github.com\urfave\cli
environment:
GOPATH: C:\gopath
GOVERSION: 1.6
PYTHON: C:\Python27-x64
PYTHON_VERSION: 2.7.x
PYTHON_ARCH: 64
install:
- set PATH=%GOPATH%\bin;C:\go\bin;%PATH%
- go version
- go env
- go get github.com/urfave/gfmrun/...
- go get -v -t ./...
build_script:
- python runtests vet
- python runtests test
- python runtests gfmrun

44
vendor/github.com/codegangsta/cli/category.go generated vendored Normal file
View File

@ -0,0 +1,44 @@
package cli
// CommandCategories is a slice of *CommandCategory.
type CommandCategories []*CommandCategory
// CommandCategory is a category containing commands.
type CommandCategory struct {
Name string
Commands Commands
}
func (c CommandCategories) Less(i, j int) bool {
return 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]
}
// AddCommand adds a command to a category.
func (c CommandCategories) AddCommand(category string, command Command) CommandCategories {
for _, commandCategory := range c {
if commandCategory.Name == category {
commandCategory.Commands = append(commandCategory.Commands, command)
return c
}
}
return append(c, &CommandCategory{Name: category, Commands: []Command{command}})
}
// VisibleCommands returns a slice of the Commands with Hidden=false
func (c *CommandCategory) VisibleCommands() []Command {
ret := []Command{}
for _, command := range c.Commands {
if !command.Hidden {
ret = append(ret, command)
}
}
return ret
}

21
vendor/github.com/codegangsta/cli/cli.go generated vendored Normal file
View File

@ -0,0 +1,21 @@
// 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.NewApp().Run(os.Args)
// }
//
// Of course this application does not do much, so let's make this an actual application:
// func main() {
// app := cli.NewApp()
// app.Name = "greet"
// app.Usage = "say a greeting"
// app.Action = func(c *cli.Context) error {
// println("Greetings")
// }
//
// app.Run(os.Args)
// }
package cli
//go:generate python ./generate-flag-types cli -i flag-types.json -o flag_generated.go

286
vendor/github.com/codegangsta/cli/command.go generated vendored Normal file
View File

@ -0,0 +1,286 @@
package cli
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
// Command is a subcommand for a cli.App.
type Command struct {
// The name of the command
Name string
// short name of the command. Typically one character (deprecated, use `Aliases`)
ShortName 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 interface{}
// TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
// of deprecation period has passed, maybe?
// Execute this function if a usage error occurs.
OnUsageError OnUsageErrorFunc
// List of child commands
Subcommands Commands
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
SkipFlagParsing bool
// Skip argument reordering which attempts to move flags before arguments,
// but only works if all flags appear after all arguments. This behavior was
// removed n version 2 since it only works under specific conditions so we
// backport here by exposing it as an option for compatibility.
SkipArgReorder bool
// Boolean to hide built-in help command
HideHelp bool
// Boolean to hide this command from help or completion
Hidden bool
// Full name of command for help, defaults to full command name, including parent commands.
HelpName string
commandNamePath []string
}
// 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, " ")
}
// Commands is a slice of Command
type Commands []Command
// 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 != BoolFlag{}) {
// append help to flags
c.Flags = append(
c.Flags,
HelpFlag,
)
}
set, err := flagSet(c.Name, c.Flags)
if err != nil {
return err
}
set.SetOutput(ioutil.Discard)
if c.SkipFlagParsing {
err = set.Parse(append([]string{"--"}, ctx.Args().Tail()...))
} else if !c.SkipArgReorder {
firstFlagIndex := -1
terminatorIndex := -1
for index, arg := range ctx.Args() {
if arg == "--" {
terminatorIndex = index
break
} else if arg == "-" {
// Do nothing. A dash alone is not really a flag.
continue
} else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
firstFlagIndex = index
}
}
if firstFlagIndex > -1 {
args := ctx.Args()
regularArgs := make([]string, len(args[1:firstFlagIndex]))
copy(regularArgs, args[1:firstFlagIndex])
var flagArgs []string
if terminatorIndex > -1 {
flagArgs = args[firstFlagIndex:terminatorIndex]
regularArgs = append(regularArgs, args[terminatorIndex:]...)
} else {
flagArgs = args[firstFlagIndex:]
}
err = set.Parse(append(flagArgs, regularArgs...))
} else {
err = set.Parse(ctx.Args().Tail())
}
} else {
err = set.Parse(ctx.Args().Tail())
}
nerr := normalizeFlags(c.Flags, set)
if nerr != nil {
fmt.Fprintln(ctx.App.Writer, nerr)
fmt.Fprintln(ctx.App.Writer)
ShowCommandHelp(ctx, c.Name)
return nerr
}
context := NewContext(ctx.App, set, ctx)
if checkCommandCompletions(context, c.Name) {
return nil
}
if err != nil {
if c.OnUsageError != nil {
err := c.OnUsageError(ctx, err, false)
HandleExitCoder(err)
return err
}
fmt.Fprintln(ctx.App.Writer, "Incorrect Usage:", err.Error())
fmt.Fprintln(ctx.App.Writer)
ShowCommandHelp(ctx, c.Name)
return err
}
if checkCommandHelp(context, c.Name) {
return nil
}
if c.After != nil {
defer func() {
afterErr := c.After(context)
if afterErr != nil {
HandleExitCoder(err)
if err != nil {
err = NewMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if c.Before != nil {
err = c.Before(context)
if err != nil {
fmt.Fprintln(ctx.App.Writer, err)
fmt.Fprintln(ctx.App.Writer)
ShowCommandHelp(ctx, c.Name)
HandleExitCoder(err)
return err
}
}
if c.Action == nil {
c.Action = helpSubcommand.Action
}
context.Command = c
err = HandleAction(c.Action, context)
if err != nil {
HandleExitCoder(err)
}
return err
}
// Names returns the names including short names and aliases.
func (c Command) Names() []string {
names := []string{c.Name}
if c.ShortName != "" {
names = append(names, c.ShortName)
}
return append(names, c.Aliases...)
}
// HasName returns true if Command.Name or Command.ShortName 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 := NewApp()
app.Metadata = ctx.App.Metadata
// set the name and usage
app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
if c.HelpName == "" {
app.HelpName = c.HelpName
} else {
app.HelpName = app.Name
}
if c.Description != "" {
app.Usage = c.Description
} else {
app.Usage = c.Usage
}
// set CommandNotFound
app.CommandNotFound = ctx.App.CommandNotFound
// set the flags and commands
app.Commands = c.Subcommands
app.Flags = c.Flags
app.HideHelp = c.HideHelp
app.Version = ctx.App.Version
app.HideVersion = ctx.App.HideVersion
app.Compiled = ctx.App.Compiled
app.Author = ctx.App.Author
app.Email = ctx.App.Email
app.Writer = ctx.App.Writer
app.categories = CommandCategories{}
for _, command := range c.Subcommands {
app.categories = app.categories.AddCommand(command.Category, command)
}
sort.Sort(app.categories)
// 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
}
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)
}

276
vendor/github.com/codegangsta/cli/context.go generated vendored Normal file
View File

@ -0,0 +1,276 @@
package cli
import (
"errors"
"flag"
"reflect"
"strings"
"syscall"
)
// 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 {
App *App
Command Command
shellComplete bool
flagSet *flag.FlagSet
setFlags map[string]bool
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.shellComplete = parentCtx.shellComplete
}
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)
}
// GlobalSet sets a context flag to a value on the global flagset
func (c *Context) GlobalSet(name, value string) error {
return globalContext(c).flagSet.Set(name, value)
}
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
c.setFlags = make(map[string]bool)
c.flagSet.Visit(func(f *flag.Flag) {
c.setFlags[f.Name] = true
})
c.flagSet.VisitAll(func(f *flag.Flag) {
if _, ok := c.setFlags[f.Name]; ok {
return
}
c.setFlags[f.Name] = false
})
// XXX hack to support IsSet for flags with EnvVar
//
// There isn't an easy way to do this with the current implementation since
// whether a flag was set via an environment variable is very difficult to
// determine here. Instead, we intend to introduce a backwards incompatible
// change in version 2 to add `IsSet` to the Flag interface to push the
// responsibility closer to where the information required to determine
// whether a flag is set by non-standard means such as environment
// variables is avaliable.
//
// See https://github.com/urfave/cli/issues/294 for additional discussion
flags := c.Command.Flags
if c.Command.Name == "" { // cannot == Command{} since it contains slice types
if c.App != nil {
flags = c.App.Flags
}
}
for _, f := range flags {
eachName(f.GetName(), func(name string) {
if isSet, ok := c.setFlags[name]; isSet || !ok {
return
}
val := reflect.ValueOf(f)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
envVarValue := val.FieldByName("EnvVar")
if !envVarValue.IsValid() {
return
}
eachName(envVarValue.String(), func(envVar string) {
envVar = strings.TrimSpace(envVar)
if _, ok := syscall.Getenv(envVar); ok {
c.setFlags[name] = true
return
}
})
})
}
}
return c.setFlags[name]
}
// GlobalIsSet determines if the global flag was actually set
func (c *Context) GlobalIsSet(name string) bool {
ctx := c
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if ctx.IsSet(name) {
return true
}
}
return false
}
// FlagNames returns a slice of flag names used in this context.
func (c *Context) FlagNames() (names []string) {
for _, flag := range c.Command.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" {
continue
}
names = append(names, name)
}
return
}
// GlobalFlagNames returns a slice of global flag names used by the app.
func (c *Context) GlobalFlagNames() (names []string) {
for _, flag := range c.App.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" || name == "version" {
continue
}
names = append(names, name)
}
return
}
// Parent returns the parent context, if any
func (c *Context) Parent() *Context {
return c.parentContext
}
// value returns the value of the flag coressponding to `name`
func (c *Context) value(name string) interface{} {
return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
}
// Args contains apps console arguments
type Args []string
// Args returns the command line arguments associated with the context.
func (c *Context) Args() Args {
args := Args(c.flagSet.Args())
return args
}
// NArg returns the number of the command line arguments.
func (c *Context) NArg() int {
return len(c.Args())
}
// Get returns the nth argument, or else a blank string
func (a Args) Get(n int) string {
if len(a) > n {
return a[n]
}
return ""
}
// First returns the first argument, or else a blank string
func (a Args) First() string {
return a.Get(0)
}
// Tail returns the rest of the arguments (not the first one)
// or else an empty string slice
func (a Args) Tail() []string {
if len(a) >= 2 {
return []string(a)[1:]
}
return []string{}
}
// Present checks if there are any arguments present
func (a Args) Present() bool {
return len(a) != 0
}
// Swap swaps arguments at the given indexes
func (a Args) Swap(from, to int) error {
if from >= len(a) || to >= len(a) {
return errors.New("index out of range")
}
a[from], a[to] = a[to], a[from]
return nil
}
func globalContext(ctx *Context) *Context {
if ctx == nil {
return nil
}
for {
if ctx.parentContext == nil {
return ctx
}
ctx = ctx.parentContext
}
}
func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if f := ctx.flagSet.Lookup(name); f != nil {
return ctx.flagSet
}
}
return nil
}
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
switch ff.Value.(type) {
case *StringSlice:
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 := strings.Split(f.GetName(), ",")
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
}

110
vendor/github.com/codegangsta/cli/errors.go generated vendored Normal file
View File

@ -0,0 +1,110 @@
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 struct {
Errors []error
}
// NewMultiError creates a new MultiError. Pass in one or more errors.
func NewMultiError(err ...error) MultiError {
return MultiError{Errors: err}
}
// Error implements the error interface.
func (m MultiError) Error() string {
errs := make([]string, len(m.Errors))
for i, err := range m.Errors {
errs[i] = err.Error()
}
return strings.Join(errs, "\n")
}
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
}
// ExitError fulfills both the builtin `error` interface and `ExitCoder`
type ExitError struct {
exitCode int
message interface{}
}
// NewExitError makes a new *ExitError
func NewExitError(message interface{}, exitCode int) *ExitError {
return &ExitError{
exitCode: exitCode,
message: message,
}
}
// Error returns the string message, fulfilling the interface required by
// `error`
func (ee *ExitError) Error() string {
return fmt.Sprintf("%v", ee.message)
}
// ExitCode returns the exit code, fulfilling the interface required by
// `ExitCoder`
func (ee *ExitError) ExitCode() int {
return ee.exitCode
}
// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if
// so prints the error to stderr (if it is non-empty) and calls OsExiter with the
// given exit code. If the given error is a MultiError, then this func is
// called on all members of the Errors slice.
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 {
for _, merr := range multiErr.Errors {
HandleExitCoder(merr)
}
return
}
if err.Error() != "" {
if _, ok := err.(ErrorFormatter); ok {
fmt.Fprintf(ErrWriter, "%+v\n", err)
} else {
fmt.Fprintln(ErrWriter, err)
}
}
OsExiter(1)
}

93
vendor/github.com/codegangsta/cli/flag-types.json generated vendored Normal file
View File

@ -0,0 +1,93 @@
[
{
"name": "Bool",
"type": "bool",
"value": false,
"context_default": "false",
"parser": "strconv.ParseBool(f.Value.String())"
},
{
"name": "BoolT",
"type": "bool",
"value": false,
"doctail": " that is true by default",
"context_default": "false",
"parser": "strconv.ParseBool(f.Value.String())"
},
{
"name": "Duration",
"type": "time.Duration",
"doctail": " (see https://golang.org/pkg/time/#ParseDuration)",
"context_default": "0",
"parser": "time.ParseDuration(f.Value.String())"
},
{
"name": "Float64",
"type": "float64",
"context_default": "0",
"parser": "strconv.ParseFloat(f.Value.String(), 64)"
},
{
"name": "Generic",
"type": "Generic",
"dest": false,
"context_default": "nil",
"context_type": "interface{}"
},
{
"name": "Int64",
"type": "int64",
"context_default": "0",
"parser": "strconv.ParseInt(f.Value.String(), 0, 64)"
},
{
"name": "Int",
"type": "int",
"context_default": "0",
"parser": "strconv.ParseInt(f.Value.String(), 0, 64)",
"parser_cast": "int(parsed)"
},
{
"name": "IntSlice",
"type": "*IntSlice",
"dest": false,
"context_default": "nil",
"context_type": "[]int",
"parser": "(f.Value.(*IntSlice)).Value(), error(nil)"
},
{
"name": "Int64Slice",
"type": "*Int64Slice",
"dest": false,
"context_default": "nil",
"context_type": "[]int64",
"parser": "(f.Value.(*Int64Slice)).Value(), error(nil)"
},
{
"name": "String",
"type": "string",
"context_default": "\"\"",
"parser": "f.Value.String(), error(nil)"
},
{
"name": "StringSlice",
"type": "*StringSlice",
"dest": false,
"context_default": "nil",
"context_type": "[]string",
"parser": "(f.Value.(*StringSlice)).Value(), error(nil)"
},
{
"name": "Uint64",
"type": "uint64",
"context_default": "0",
"parser": "strconv.ParseUint(f.Value.String(), 0, 64)"
},
{
"name": "Uint",
"type": "uint",
"context_default": "0",
"parser": "strconv.ParseUint(f.Value.String(), 0, 64)",
"parser_cast": "uint(parsed)"
}
]

799
vendor/github.com/codegangsta/cli/flag.go generated vendored Normal file
View File

@ -0,0 +1,799 @@
package cli
import (
"flag"
"fmt"
"reflect"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
const defaultPlaceholder = "value"
// BashCompletionFlag enables bash-completion for all commands and subcommands
var BashCompletionFlag = BoolFlag{
Name: "generate-bash-completion",
Hidden: true,
}
// VersionFlag prints the version for the application
var VersionFlag = BoolFlag{
Name: "version, v",
Usage: "print the version",
}
// HelpFlag prints the help for all commands and subcommands
// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
// unless HideHelp is set to true)
var HelpFlag = BoolFlag{
Name: "help, 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
// 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 {
return f[i].GetName() < f[j].GetName()
}
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)
GetName() string
}
// errorableFlag is an interface that allows us to return errors during apply
// it allows flags defined in this library to return errors in a fashion backwards compatible
// TODO remove in v2 and modify the existing Flag interface to return errors
type errorableFlag interface {
Flag
ApplyWithError(*flag.FlagSet) error
}
func flagSet(name string, flags []Flag) (*flag.FlagSet, error) {
set := flag.NewFlagSet(name, flag.ContinueOnError)
for _, f := range flags {
//TODO remove in v2 when errorableFlag is removed
if ef, ok := f.(errorableFlag); ok {
if err := ef.ApplyWithError(set); err != nil {
return nil, err
}
} else {
f.Apply(set)
}
}
return set, nil
}
func eachName(longName string, fn func(string)) {
parts := strings.Split(longName, ",")
for _, name := range parts {
name = strings.Trim(name, " ")
fn(name)
}
}
// Generic is a generic parseable type identified by a specific flag
type Generic interface {
Set(value string) error
String() string
}
// Apply takes the flagset and calls Set on the generic flag with the value
// provided by the user for parsing by the flag
// Ignores parsing errors
func (f GenericFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError 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) ApplyWithError(set *flag.FlagSet) error {
val := f.Value
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
if err := val.Set(envVal); err != nil {
return fmt.Errorf("could not parse %s as value for flag %s: %s", envVal, f.Name, err)
}
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
return nil
}
// StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter
type StringSlice []string
// Set appends the string value to the list of values
func (f *StringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (f *StringSlice) String() string {
return fmt.Sprintf("%s", *f)
}
// Value returns the slice of strings set by this flag
func (f *StringSlice) Value() []string {
return *f
}
// Get returns the slice of strings set by this flag
func (f *StringSlice) Get() interface{} {
return *f
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f StringSliceFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &StringSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
if f.Value == nil {
f.Value = &StringSlice{}
}
set.Var(f.Value, name, f.Usage)
})
return nil
}
// IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter
type IntSlice []int
// Set parses the value into an integer and appends it to the list of values
func (f *IntSlice) Set(value string) error {
tmp, err := strconv.Atoi(value)
if err != nil {
return err
}
*f = append(*f, tmp)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (f *IntSlice) String() string {
return fmt.Sprintf("%#v", *f)
}
// Value returns the slice of ints set by this flag
func (f *IntSlice) Value() []int {
return *f
}
// Get returns the slice of ints set by this flag
func (f *IntSlice) Get() interface{} {
return *f
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f IntSliceFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &IntSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
if f.Value == nil {
f.Value = &IntSlice{}
}
set.Var(f.Value, name, f.Usage)
})
return nil
}
// Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter
type Int64Slice []int64
// Set parses the value into an integer and appends it to the list of values
func (f *Int64Slice) Set(value string) error {
tmp, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
*f = append(*f, tmp)
return nil
}
// String returns a readable representation of this value (for usage defaults)
func (f *Int64Slice) String() string {
return fmt.Sprintf("%#v", *f)
}
// Value returns the slice of ints set by this flag
func (f *Int64Slice) Value() []int64 {
return *f
}
// Get returns the slice of ints set by this flag
func (f *Int64Slice) Get() interface{} {
return *f
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f Int64SliceFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
newVal := &Int64Slice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
if err := newVal.Set(s); err != nil {
return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err)
}
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
if f.Value == nil {
f.Value = &Int64Slice{}
}
set.Var(f.Value, name, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f BoolFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error {
val := false
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
if envVal == "" {
val = false
break
}
envValBool, err := strconv.ParseBool(envVal)
if err != nil {
return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
}
val = envValBool
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.BoolVar(f.Destination, name, val, f.Usage)
return
}
set.Bool(name, val, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f BoolTFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error {
val := true
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
if envVal == "" {
val = false
break
}
envValBool, err := strconv.ParseBool(envVal)
if err != nil {
return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err)
}
val = envValBool
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.BoolVar(f.Destination, name, val, f.Usage)
return
}
set.Bool(name, val, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f StringFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f StringFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
f.Value = envVal
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.StringVar(f.Destination, name, f.Value, f.Usage)
return
}
set.String(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f IntFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f IntFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValInt, err := strconv.ParseInt(envVal, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
}
f.Value = int(envValInt)
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.IntVar(f.Destination, name, f.Value, f.Usage)
return
}
set.Int(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f Int64Flag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValInt, err := strconv.ParseInt(envVal, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err)
}
f.Value = envValInt
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.Int64Var(f.Destination, name, f.Value, f.Usage)
return
}
set.Int64(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f UintFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f UintFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValInt, err := strconv.ParseUint(envVal, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err)
}
f.Value = uint(envValInt)
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.UintVar(f.Destination, name, f.Value, f.Usage)
return
}
set.Uint(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f Uint64Flag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValInt, err := strconv.ParseUint(envVal, 0, 64)
if err != nil {
return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err)
}
f.Value = uint64(envValInt)
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.Uint64Var(f.Destination, name, f.Value, f.Usage)
return
}
set.Uint64(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f DurationFlag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValDuration, err := time.ParseDuration(envVal)
if err != nil {
return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err)
}
f.Value = envValDuration
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.DurationVar(f.Destination, name, f.Value, f.Usage)
return
}
set.Duration(name, f.Value, f.Usage)
})
return nil
}
// Apply populates the flag given the flag set and environment
// Ignores errors
func (f Float64Flag) Apply(set *flag.FlagSet) {
f.ApplyWithError(set)
}
// ApplyWithError populates the flag given the flag set and environment
func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal, ok := syscall.Getenv(envVar); ok {
envValFloat, err := strconv.ParseFloat(envVal, 10)
if err != nil {
return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err)
}
f.Value = float64(envValFloat)
break
}
}
}
eachName(f.Name, func(name string) {
if f.Destination != nil {
set.Float64Var(f.Destination, name, f.Value, f.Usage)
return
}
set.Float64(name, f.Value, f.Usage)
})
return nil
}
func visibleFlags(fl []Flag) []Flag {
visible := []Flag{}
for _, flag := range fl {
if !flagValue(flag).FieldByName("Hidden").Bool() {
visible = append(visible, flag)
}
}
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(fullName, placeholder string) string {
var prefixed string
parts := strings.Split(fullName, ",")
for i, name := range parts {
name = strings.Trim(name, " ")
prefixed += prefixFor(name) + name
if placeholder != "" {
prefixed += " " + placeholder
}
if i < len(parts)-1 {
prefixed += ", "
}
}
return prefixed
}
func withEnvHint(envVar, str string) string {
envText := ""
if envVar != "" {
prefix := "$"
suffix := ""
sep := ", $"
if runtime.GOOS == "windows" {
prefix = "%"
suffix = "%"
sep = "%, %"
}
envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(strings.Split(envVar, ","), sep), suffix)
}
return str + envText
}
func flagValue(f Flag) reflect.Value {
fv := reflect.ValueOf(f)
for fv.Kind() == reflect.Ptr {
fv = reflect.Indirect(fv)
}
return fv
}
func stringifyFlag(f Flag) string {
fv := flagValue(f)
switch f.(type) {
case IntSliceFlag:
return withEnvHint(fv.FieldByName("EnvVar").String(),
stringifyIntSliceFlag(f.(IntSliceFlag)))
case Int64SliceFlag:
return withEnvHint(fv.FieldByName("EnvVar").String(),
stringifyInt64SliceFlag(f.(Int64SliceFlag)))
case StringSliceFlag:
return withEnvHint(fv.FieldByName("EnvVar").String(),
stringifyStringSliceFlag(f.(StringSliceFlag)))
}
placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String())
needsPlaceholder := false
defaultValueString := ""
val := fv.FieldByName("Value")
if val.IsValid() {
needsPlaceholder = true
defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface())
if val.Kind() == reflect.String && val.String() != "" {
defaultValueString = fmt.Sprintf(" (default: %q)", val.String())
}
}
if defaultValueString == " (default: )" {
defaultValueString = ""
}
if needsPlaceholder && placeholder == "" {
placeholder = defaultPlaceholder
}
usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultValueString))
return withEnvHint(fv.FieldByName("EnvVar").String(),
fmt.Sprintf("%s\t%s", prefixedNames(fv.FieldByName("Name").String(), placeholder), usageWithDefault))
}
func stringifyIntSliceFlag(f IntSliceFlag) string {
defaultVals := []string{}
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, i := range f.Value.Value() {
defaultVals = append(defaultVals, fmt.Sprintf("%d", i))
}
}
return stringifySliceFlag(f.Usage, f.Name, defaultVals)
}
func stringifyInt64SliceFlag(f Int64SliceFlag) string {
defaultVals := []string{}
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, i := range f.Value.Value() {
defaultVals = append(defaultVals, fmt.Sprintf("%d", i))
}
}
return stringifySliceFlag(f.Usage, f.Name, defaultVals)
}
func stringifyStringSliceFlag(f StringSliceFlag) string {
defaultVals := []string{}
if f.Value != nil && len(f.Value.Value()) > 0 {
for _, s := range f.Value.Value() {
if len(s) > 0 {
defaultVals = append(defaultVals, fmt.Sprintf("%q", s))
}
}
}
return stringifySliceFlag(f.Usage, f.Name, defaultVals)
}
func stringifySliceFlag(usage, name string, defaultVals []string) string {
placeholder, usage := unquoteUsage(usage)
if placeholder == "" {
placeholder = defaultPlaceholder
}
defaultVal := ""
if len(defaultVals) > 0 {
defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", "))
}
usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))
return fmt.Sprintf("%s\t%s", prefixedNames(name, placeholder), usageWithDefault)
}

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