1
0
mirror of https://github.com/taigrr/wtf synced 2025-01-18 04:03:14 -08:00

Compare commits

..

No commits in common. "master" and "v0.30.0" have entirely different histories.

313 changed files with 2272 additions and 6845 deletions

View File

@ -910,174 +910,6 @@
"name": "Risto Saarelma",
"avatar_url": "https://avatars1.githubusercontent.com/u/41840?v=4",
"profile": "https://github.com/rsaarelm",
"contributions": []
},
{
"login": "sam-github",
"name": "Sam Roberts",
"avatar_url": "https://avatars2.githubusercontent.com/u/17607?v=4",
"profile": "https://sam-github.github.io/",
"contributions": []
},
{
"login": "gerchardon",
"name": "gerchardon",
"avatar_url": "https://avatars0.githubusercontent.com/u/5973160?v=4",
"profile": "https://github.com/gerchardon",
"contributions": []
},
{
"login": "mryanmurphy",
"name": "Matt",
"avatar_url": "https://avatars2.githubusercontent.com/u/641427?v=4",
"profile": "https://github.com/mryanmurphy",
"contributions": []
},
{
"login": "ripienaar",
"name": "R.I.Pienaar",
"avatar_url": "https://avatars0.githubusercontent.com/u/82342?v=4",
"profile": "http://devco.net/",
"contributions": []
},
{
"login": "fmotrifork",
"name": "Frederik Mogensen",
"avatar_url": "https://avatars3.githubusercontent.com/u/18327738?v=4",
"profile": "https://github.com/fmotrifork",
"contributions": []
},
{
"login": "aeter",
"name": "aeter",
"avatar_url": "https://avatars0.githubusercontent.com/u/238607?v=4",
"profile": "https://github.com/aeter",
"contributions": []
},
{
"login": "timhwang21",
"name": "Tim Hwang",
"avatar_url": "https://avatars3.githubusercontent.com/u/5831434?v=4",
"profile": "http://timhwang21.gitbook.io",
"contributions": []
},
{
"login": "cyingfan",
"name": "Ying Fan Chong",
"avatar_url": "https://avatars1.githubusercontent.com/u/10404961?v=4",
"profile": "http://about.me/yingfan",
"contributions": []
},
{
"login": "MartinJohns",
"name": "Martin Johns",
"avatar_url": "https://avatars1.githubusercontent.com/u/5269069?v=4",
"profile": "https://github.com/MartinJohns",
"contributions": []
},
{
"login": "jamietanna",
"name": "Jamie Tanna",
"avatar_url": "https://avatars0.githubusercontent.com/u/3315059?v=4",
"profile": "https://www.jvt.me",
"contributions": []
},
{
"login": "trimble",
"name": "Todd Trimble",
"avatar_url": "https://avatars3.githubusercontent.com/u/371317?v=4",
"profile": "https://github.com/trimble",
"contributions": []
},
{
"login": "mhanberg",
"name": "Mitchell Hanberg",
"avatar_url": "https://avatars2.githubusercontent.com/u/5523984?v=4",
"profile": "https://www.mitchellhanberg.com",
"contributions": []
},
{
"login": "franga2000",
"name": "Miha Frangež",
"avatar_url": "https://avatars3.githubusercontent.com/u/3891092?v=4",
"profile": "https://franga2000.com",
"contributions": []
},
{
"login": "sahilister",
"name": "Sahil Dhiman",
"avatar_url": "https://avatars0.githubusercontent.com/u/52946452?v=4",
"profile": "https://blog.sahilister.in/",
"contributions": []
},
{
"login": "applegreengrape",
"name": "Pingzhou | 平舟",
"avatar_url": "https://avatars2.githubusercontent.com/u/17727004?v=4",
"profile": "https://pzoo.netlify.app/",
"contributions": []
},
{
"login": "YuviGold",
"name": "Yuval Goldberg",
"avatar_url": "https://avatars0.githubusercontent.com/u/29873449?v=4",
"profile": "https://github.com/YuviGold",
"contributions": []
},
{
"login": "dabcoder",
"name": "David Bouchare",
"avatar_url": "https://avatars3.githubusercontent.com/u/5034531?v=4",
"profile": "https://github.com/dabcoder",
"contributions": []
},
{
"login": "stone",
"name": "Fredrik Steen",
"avatar_url": "https://avatars3.githubusercontent.com/u/29077?v=4",
"profile": "https://github.com/stone",
"contributions": []
},
{
"login": "zye1996",
"name": "zye1996",
"avatar_url": "https://avatars2.githubusercontent.com/u/28901953?v=4",
"profile": "https://github.com/zye1996",
"contributions": []
},
{
"login": "pgaxatte",
"name": "Pierre Gaxatte",
"avatar_url": "https://avatars.githubusercontent.com/u/30696904?v=4",
"profile": "https://github.com/pgaxatte",
"contributions": []
},
{
"login": "xntrik",
"name": "Christian Frichot",
"avatar_url": "https://avatars.githubusercontent.com/u/678260?v=4",
"profile": "https://xntrik.wtf",
"contributions": []
},
{
"login": "LKaemmerling",
"name": "Lukas Kämmerling",
"avatar_url": "https://avatars.githubusercontent.com/u/4281581?v=4",
"profile": "https://lukas-kaemmerling.de",
"contributions": []
},
{
"login": "inetAnt",
"name": "Antoine Meillet",
"avatar_url": "https://avatars.githubusercontent.com/u/1765366?v=4",
"profile": "https://inetant.net/",
"contributions": []
},
{
"login": "cclauss",
"name": "Christian Clauss",
"avatar_url": "https://avatars.githubusercontent.com/u/3709715?v=4",
"profile": "https://www.patreon.com/cclauss",
"contributions": [
]
}

View File

@ -1,11 +0,0 @@
version: 2
updates:
- package-ecosystem: gomod
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
reviewers:
- senorprogrammer
assignees:
- senorprogrammer

View File

@ -1,51 +0,0 @@
name: "Code scanning - action"
on:
push:
pull_request:
schedule:
- cron: '0 3 * * 3,6'
jobs:
CodeQL-Build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@ -1,22 +0,0 @@
name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
pull_request:
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
# Required: the version of golangci-lint is required and must be
# specified without patch version: we always use the latest patch version.
# https://github.com/golangci/golangci-lint/releases
version: v1.39
args: ./...

View File

@ -1,30 +0,0 @@
name: goreleaser
on:
push:
tags:
- '*'
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.16
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
version: latest
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GH_PAT }}

View File

@ -8,7 +8,7 @@ jobs:
steps:
- uses: actions/checkout@master
- name: check
uses: grandcolline/golang-github-actions@4356d0458ea4bfdb55fcb296437812acef970f9b
uses: grandcolline/golang-github-actions@v1.1.0
with:
run: imports
token: ${{ secrets.GITHUB_TOKEN }}
@ -19,7 +19,7 @@ jobs:
steps:
- uses: actions/checkout@master
- name: check
uses: grandcolline/golang-github-actions@4356d0458ea4bfdb55fcb296437812acef970f9b
uses: grandcolline/golang-github-actions@v1.1.0
with:
run: errcheck
token: ${{ secrets.GITHUB_TOKEN }}
@ -30,7 +30,7 @@ jobs:
#steps:
#- uses: actions/checkout@master
#- name: check
#uses: grandcolline/golang-github-actions@4356d04
#uses: grandcolline/golang-github-actions@v1.1.0
#with:
#run: lint
#token: ${{ secrets.GITHUB_TOKEN }}
@ -41,7 +41,7 @@ jobs:
steps:
- uses: actions/checkout@master
- name: check
uses: grandcolline/golang-github-actions@4356d0458ea4bfdb55fcb296437812acef970f9b
uses: grandcolline/golang-github-actions@v1.1.0
with:
run: shadow
token: ${{ secrets.GITHUB_TOKEN }}
@ -52,7 +52,7 @@ jobs:
steps:
- uses: actions/checkout@master
- name: check
uses: grandcolline/golang-github-actions@4356d0458ea4bfdb55fcb296437812acef970f9b
uses: grandcolline/golang-github-actions@v1.1.0
with:
run: staticcheck
token: ${{ secrets.GITHUB_TOKEN }}
@ -63,7 +63,7 @@ jobs:
#steps:
#- uses: actions/checkout@master
#- name: check
#uses: grandcolline/golang-github-actions@4356d04
#uses: grandcolline/golang-github-actions@v1.1.0
#with:
#run: sec
#token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,18 +0,0 @@
run:
timeout: 2m
linters:
enable:
- vet
- errcheck
- staticcheck
# - dupl
# - funlen
# - goconst
# - gocritic
- gofmt
# - golint
# - misspell
# - stylecheck
- unconvert
# - whitespace

View File

@ -12,6 +12,7 @@ builds:
- darwin
- linux
goarch:
- 386
- amd64
- arm
- arm64
@ -21,10 +22,14 @@ before:
- make install
brews:
-
- github:
owner: wtfutil
name: homebrew-wtfutil
name: wtfutil
homepage: 'https://wtfutil.com'
description: 'The personal information dashboard for your terminal.'
tap:
owner: wtfutil
name: homebrew-wtfutil
#dockers:
#- image_templates:
#- wtfutil/wtf

View File

@ -1,7 +1,7 @@
language: go
go:
- "1.16.x"
- "1.14.x"
before_install:
# Make sure travis builds work for forks

View File

@ -4,143 +4,6 @@
### ⚡️ Added
* Yahoo Finance module added, by [@inetAnt](https://github.com/inetAnt)
### 🐞 Fixed
* Fixed error closing the Jira module response body, [#1070](https://github.com/wtfutil/wtf/issues/1070) by [@senorprogrammer](https://github.com/senorprogrammer)
## v0.36.0
### ⚡️ Added
* HealthChecks module added, by [@stone](https://github.com/stone)
* Asana module added, by [@xntrik](https://github.com/xntrik)
* Kubernetes module now displays the Ready Replicas and Total Replicas count, by [@LKaemmerling](https://github.com/LKaemmerling)
* Now builds using Go 1.16, which provides support for Apple's M1 ARM hardware, by [@LKaemmerling](https://github.com/LKaemmerling)
### 🐞 Fixed
* Numerous dangling response bodies closed, by [@dabcoder](https://github.com/dabcoder)
* HackerNews read-on-response error fixed, by [@LKaemmerling](https://github.com/LKaemmerling)
* CircleCI read-on-response error fixed, by [@dabcoder](https://github.com/dabcoder)
## v0.35.0
### ⚡️ Added
* CircleCI module now supports `numberOfBuilds` setting defining how many builds to display, [#1020](https://github.com/wtfutil/wtf/issues/1020) by [@dabcoder](https://github.com/dabcoder)
* The <kbd>\\</kbd> key now opens module documentation in the browser for the currently-focused module, by [@senorprogrammer](https://github.com/senorprogrammer)
* Krisinformation module added, by [@stone](https://github.com/stone)
* Covid module has been added, by [@dabcoder](https://github.com/dabcoder)
* Support for a "Language" configuration key added. Supports any BCP 47 tag for identifying a langauge, by [@senorprogrammer](https://github.com/senorprogrammer)
### 🐞 Fixed
* CryptoLive prices update again, [#1041](https://github.com/wtfutil/wtf/issues/1041) by [@zye1996](https://github.com/zye1996)
## v0.34.0
2020-11-08
### ⚡️ Added
* DigitalOcean module now supports custom column definitions in the default layout. See [the docs](https://wtfutil.com/modules/digitalocean/) for details, [#986](https://github.com/wtfutil/wtf/issues/986) by [@senorprogrammer](https://github.com/senorprogrammer)
* Finnhub stock quotes module added, [#930](https://github.com/wtfutil/wtf/issues/930) by [@applegreengrape](https://github.com/applegreengrape)
* Grafana Alerts module added, by [@schoentoon](https://github.com/schoentoon)
### 👍 Updated
* Updated `google.golang.org/api` from 0.30.0 to 0.33.0
* Updated `github.com/digitalocean/godo` from 1.46.0 to 1.52.0
* Updated `github.com/xanzy/go-gitlab` from 0.38.1 to 0.39.0
* Updated `github.com/zorkian/go-datadog-api` from 2.29.0+incompatible to 2.30.0+incompatible
* Updated `golang.org/x/text` from 0.3.3 to 0.3.4
## v0.33.0
2020-10-13
### ⚡️ Added
* FeedReader module supports [display mode switching](https://github.com/wtfutil/wtf/pull/976) via the `t` key, by [@cyingfan](https://github.com/cyingfan)
* Clocks module now supports `natural` ordering option, [#896](https://github.com/wtfutil/wtf/issues/896) by [@seanstoppable](https://github.com/Seanstoppable)
* Exit banner message added, by [@senorprogrammer](https://github.com/senorprogrammer)
* [UptimeRobot module added](https://github.com/wtfutil/wtf/pull/983), by [@franga2000](https://github.com/franga2000)
* Gitlab module now defaults the domain to `https://gitlab.com`, by [@jmks](https://github.com/jmks)
### 🐞 Fixed
* Exchange Rates module now displays rates in alphabetical order, sorted by the base rate, by [@senorprogrammer](https://github.com/senorprogrammer)
* Feed Reader module no longer crashes on feeds that don't have a published date, [#958](https://github.com/wtfutil/wtf/issues/958) by [@cyingfan](https://github.com/cyingfan)
* Stray blank lines no longer appear at the end of highlightable lists, [#977](https://github.com/wtfutil/wtf/pull/977) by [@cyingfan](https://github.com/cyingfan)
* `config.yml` now properly set to `0600` instead of `0666`, by [@cyingfan](https://github.com/cyingfan)
* Now blank-imports the `time/tzinfo` package to provide timezone support for Windows users, [#994](https://github.com/wtfutil/wtf/issues/994) by [@trimble](https://github.com/trimble)
### 👍 Updated
* Updated `github.com/gdamore/tcell` from 1.3.0 to 1.4.0
* Updated `github.com/shirou/gopsutil` from 2.20.7+incompatible to 2.20.9+incompatible
* Updated `github.com/mmcdole/gofeed` from 1.0.0 to 1.1.0
* Updated `github.com/digitalocean/godo` from 1.42.1 to 1.46.0
* Updated `github.com/xanzy/go-gitlab` from 0.33.0 to 0.38.1
* Updated `github.com/adlio/trello` from 1.7.0 to 1.8.0
* Updated `github.com/alecthomas/chroma` from 0.8.0 to 0.8.1
* Updated `github.com/nicklaw5/helix` from 0.5.9 to 0.7.0
* Now requires Go 1.15 for compilation in Dockerfiles and go.mod, by [@seanstoppable](https://github.com/Seanstoppable)
## v0.32.0
### ⚡️ Added
* PagerDuty module now supports `showOncallEnd` setting, which determines whether or not to display the oncall rotation end date, by [@senorprogrammer](https://github.com/senorprogrammer)
* Exchange Rates module now supports `precision` setting, which determines how many decimal places to display, [#897](https://github.com/wtfutil/wtf/issues/897) by [@senorprogrammer](https://github.com/senorprogrammer)
### 🐞 Fixed
* Todo module's edit modal now shows up quickly, [#876](https://github.com/wtfutil/wtf/issues/876) by [@aeter](https://github.com/aeter)
* Jira module title now displays properly, [#942](https://github.com/wtfutil/wtf/issues/942) by [@timhwang21](https://github.com/timhwang21)
### 👍 Updated
* Updated `alecthomas/chroma` from 0.7.3 to 0.8.0
* Updated `digitalocean/godo` from 1.38.0 to 1.42.1
* Updated `google.golang.org/api` from 0.29.0 to 0.30.0
* Updated `shirou/gopsutil` from 2.20.6+incompatible to 2.20.7+incompatible
## v0.31.0
### ⚡️ Added
* [docker-credential-helpers](https://github.com/docker/docker-credential-helpers) support added to provide optional securing of module secrets, [#517](https://github.com/wtfutil/wtf/issues/517) by [@sam-github](https://github.com/sam-github)
* `make lint` now uses [golangci-lint](https://github.com/golangci/golangci-lint-action), by [@sam-github](https://github.com/sam-github)
* GitHub module now supports per-section configuration, [#864](https://github.com/wtfutil/wtf/issues/864) by [@mryanmurphy](https://github.com/mryanmurphy)
* PagerDuty module now accepts Team ID and User ID as filters, by [@mryanmurphy](https://github.com/mryanmurphy)
* Weather module now supports a `useEmoji` setting, toggling the use of emoji characters in the title, by [@jonhadfield](https://github.com/jonhadfield)
* Pocket documentation added, by [@3mard](https://github.com/3mard)
### 🐞 Fixed
* GitLab Todo module now allows domain to be set, defaults to `https://gitlab.com`, by [@gerchardon](https://github.com/gerchardon)
* Pi-hole module now works with Pi-hole v4 and v5, by [@jonhadfield](https://github.com/jonhadfield)
* Null pointer exception fixed in VictorOps module, by [@ripienaar](https://github.com/ripienaar)
### 👍 Updated
* Updated `google.golang.org/api` from 0.25.0 to 0.29.0
* Updated `pkg/profile` from 1.4.0 to 1.5.0
* Updated `nicklaw5/helix` from 0.5.8 to 0.5.9
* Updated `digitalocean/godo` from 1.37.0 to 1.38.0
* Updated `gopkg.in/yaml.v2` from 2.2.8 to 2.3.0
* Updated `xanzy/go-gitlab` from 0.31.0 to 0.33.0
* Updated `stretchr/testify` from 1.5.1 to 1.6.1
* Updated `golang.org/x/text` from 0.3.2 to 0.3.3
* Updated `shirou/gopsutil` from 2.20.4+incompatible to 2.20.6+incompatible
## v0.30.0
### ⚡️ Added
* Expansive keyboard controls for the [GitLab](https://wtfutil.com/modules/gitlab/) module, by [@mogensen](https://github.com/mogensen)
* [IPInfo](https://wtfutil.com/modules/ipaddress/ipinfo/) module now supports IPv6 lookup, by [@acaloiaro](https://github.com/acaloiaro)
* The GitHub repo now runs a set of actions that lint PRs for code quality and conformity and comment in-line on the PRs. See here for action details https://github.com/wtfutil/wtf/actions

View File

@ -1,4 +1,4 @@
FROM golang:1.16-alpine as build
FROM golang:1.13-alpine as build
ARG version=master

View File

@ -1,4 +1,4 @@
FROM golang:1.16 as build
FROM golang:1.13 as build
ARG version=master

View File

@ -1,8 +1,6 @@
*Mozilla Public License, version 2.0*
Copyright 2018, Chris Cummer
1. Definitions
1.1. “Contributor” means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
Mozilla Public License, version 2.0 1. Definitions 1.1. “Contributor” means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
1.2. “Contributor Version” means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributors Contribution.
@ -26,9 +24,9 @@ that the Covered Software was made available under the terms of version 1.1 or e
1.10. “Modifications” means any of the following:
any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
any new file in Source Code Form that contains any Covered Software.
any new file in Source Code Form that contains any Covered Software.
1.11. “Patent Claims” of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
@ -38,9 +36,7 @@ that the Covered Software was made available under the terms of version 1.1 or e
1.14. “You” (or “Your”) means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
2. License Grants and Conditions 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
@ -66,9 +62,7 @@ This License does not grant any rights in the trademarks, service marks, or logo
2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients rights in the Source Code Form.
3. Responsibilities 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients rights in the Source Code Form.
3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then:
@ -82,37 +76,23 @@ You may distribute such Executable Form under the terms of this License, or subl
3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
4. Inability to Comply Due to Statute or Regulation
4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
5. Termination 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
6. Disclaimer of Warranty
6. Disclaimer of Warranty Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
7. Limitation of Liability Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such partys negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
7. Limitation of Liability
8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a partys ability to bring cross-claims or counter-claims.
Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such partys negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
8. Litigation
Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a partys ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
10. Versions of the License 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
@ -120,14 +100,10 @@ This License represents the complete agreement concerning the subject matter her
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.
Exhibit B - “Incompatible With Secondary Licenses” Notice This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.

View File

@ -26,23 +26,10 @@ THIS_FILE := $(lastword $(MAKEFILE_LIST))
APP=wtfutil
define HEADER
____ __ ____ .___________. _______
\ \ / \ / / | || ____|
\ \/ \/ / `---| |----`| |__
\ / | | | __|
\ /\ / | | | |
\__/ \__/ |__| |__|
endef
export HEADER
# -------------------- Actions -------------------- #
## build: builds a local version
build:
@echo "$$HEADER"
@echo "Building..."
go build -o bin/${APP}
@echo "Done building"
@ -69,7 +56,7 @@ docker-build:
## docker-install: installs a local version of the app from docker build
docker-install:
@echo "Installing..."
@echo "Installing ${APP}..."
docker create --name wtf_build wtfutil:build
docker cp wtf_build:/usr/local/bin/wtfutil ~/.local/bin/
$(eval INSTALLPATH = $(shell which ${APP}))
@ -91,9 +78,7 @@ isntall:
## install: installs a local version of the app
install:
$(eval GOVERS = $(shell go version))
@echo "$$HEADER"
@echo "Installing ${APP} with ${GOVERS}..."
@echo "Installing ${APP}..."
@go clean
@go install -ldflags="-s -w -X main.version=$(shell git describe --always --abbrev=6) -X main.date=$(shell date +%FT%T%z)"
@mv ~/go/bin/wtf ~/go/bin/${APP}
@ -102,48 +87,44 @@ install:
## lint: runs a number of code quality checks against the source code
lint:
golangci-lint cache clean
golangci-lint run
@echo "\033[35mhttps://github.com/kisielk/errcheck\033[0m"
errcheck ./app
errcheck ./cfg
errcheck ./flags
errcheck ./help
errcheck ./logger
errcheck ./modules/...
errcheck ./utils
errcheck ./view
errcheck ./wtf
errcheck ./main.go
# lint:
# @echo "\033[35mhttps://github.com/kisielk/errcheck\033[0m"
# errcheck ./app
# errcheck ./cfg
# errcheck ./flags
# errcheck ./help
# errcheck ./logger
# errcheck ./modules/...
# errcheck ./utils
# errcheck ./view
# errcheck ./wtf
# errcheck ./main.go
@echo "\033[35mhttps://golang.org/cmd/vet/k\033[0m"
go vet ./app
go vet ./cfg
go vet ./flags
go vet ./help
go vet ./logger
go vet ./modules/...
go vet ./utils
go vet ./view
go vet ./wtf
go vet ./main.go
# @echo "\033[35mhttps://golang.org/cmd/vet/k\033[0m"
# go vet ./app
# go vet ./cfg
# go vet ./flags
# go vet ./help
# go vet ./logger
# go vet ./modules/...
# go vet ./utils
# go vet ./view
# go vet ./wtf
# go vet ./main.go
@echo "\033[35m# https://staticcheck.io/docs/k\033[0m"
staticcheck ./app
staticcheck ./cfg
staticcheck ./flags
staticcheck ./help
staticcheck ./logger
staticcheck ./modules/...
staticcheck ./utils
staticcheck ./view
staticcheck ./wtf
staticcheck ./main.go
# @echo "\033[35m# https://staticcheck.io/docs/k\033[0m"
# staticcheck ./app
# staticcheck ./cfg
# staticcheck ./flags
# staticcheck ./help
# staticcheck ./logger
# staticcheck ./modules/...
# staticcheck ./utils
# staticcheck ./view
# staticcheck ./wtf
# staticcheck ./main.go
# @echo "\033[35m# https://github.com/mdempsky/unconvert\033[0m"
# unconvert ./...
@echo "\033[35m# https://github.com/mdempsky/unconvert\033[0m"
unconvert ./...
## loc: displays the lines of code (LoC) count
loc:
@ -151,12 +132,10 @@ loc:
## run: executes the locally-installed version
run: build
@echo "$$HEADER"
bin/${APP}
## test: runs the test suite
test: build
@echo "$$HEADER"
go test ./...
## uninstall: uninstals a locally-installed version

View File

@ -13,10 +13,6 @@ WTF (aka 'wtfutil') is the personal information dashboard for your terminal, pro
Used by thousands of developers and tech people around the world, WTF is free and open-source. To support the continued use and development of WTF, please consider sponsoring WTF via [GitHub Sponsors](https://github.com/sponsors/senorprogrammer).
### Are you a contributor or sponsor?
Awesome! [See here](https://wtfutil.com/#exit-message) for how you can change the exit message, the message WTF shows when quitting, to something special just for you.
#
<p></p>
@ -132,11 +128,7 @@ docker cp wtf_build:/usr/local/bin/wtfutil ~/.local/bin
docker rm wtf_build
```
**Note:** WTF is _only_ compatible with Go versions **1.16.0** or later (due to the use of Go modules and newer standard library functions). If you would like to use `gccgo` to compile, you _must_ use `gccgo-9` or later which introduces support for Go modules.
### Installing via Arch User Repository
Arch Linux users can utilise the [wtfutil](https://aur.archlinux.org/packages/wtfutil) package to build it from source, or [wtfutil-bin](https://aur.archlinux.org/packages/wtfutil-bin/) to install pre-built binaries.
**Note:** WTF is _only_ compatible with Go versions **1.12.0** or later (due to the use of Go modules and newer standard library functions). If you would like to use `gccgo` to compile, you _must_ use `gccgo-9` or later which introduces support for Go modules.
## Running via Docker
@ -176,8 +168,8 @@ Also, follow [on Twitter](https://twitter.com/wtfutil) for news and latest updat
See [https://wtfutil.com](https://wtfutil.com) for the definitive
documentation. Here's some short-cuts:
* [Installation](https://wtfutil.com/quick_start/)
* [Configuration](https://wtfutil.com/configuration/files/)
* [Installation](https://wtfutil.com/getting_started/installation/)
* [Configuration](https://wtfutil.com/configuration/)
* [Module Documentation](https://wtfutil.com/modules/)
## Modules
@ -395,36 +387,6 @@ Dependency management in WTF is handled by [Go modules](https://github.com/golan
<td align="center"><a href="https://github.com/Tdnshah"><img src="https://avatars2.githubusercontent.com/u/13272752?v=4" width="48px;" alt=""/><br /><sub><b>Tejas Shah</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/mogensen"><img src="https://avatars2.githubusercontent.com/u/592710?v=4" width="48px;" alt=""/><br /><sub><b>Frederik Mogensen</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/rsaarelm"><img src="https://avatars1.githubusercontent.com/u/41840?v=4" width="48px;" alt=""/><br /><sub><b>Risto Saarelma</b></sub></a><br /></td>
<td align="center"><a href="https://sam-github.github.io/"><img src="https://avatars2.githubusercontent.com/u/17607?v=4" width="48px;" alt=""/><br /><sub><b>Sam Roberts</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/gerchardon"><img src="https://avatars0.githubusercontent.com/u/5973160?v=4" width="48px;" alt=""/><br /><sub><b>gerchardon</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/mryanmurphy"><img src="https://avatars2.githubusercontent.com/u/641427?v=4" width="48px;" alt=""/><br /><sub><b>Matt</b></sub></a><br /></td>
<td align="center"><a href="http://devco.net/"><img src="https://avatars0.githubusercontent.com/u/82342?v=4" width="48px;" alt=""/><br /><sub><b>R.I.Pienaar</b></sub></a><br /></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/fmotrifork"><img src="https://avatars3.githubusercontent.com/u/18327738?v=4" width="48px;" alt=""/><br /><sub><b>Frederik Mogensen</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/aeter"><img src="https://avatars0.githubusercontent.com/u/238607?v=4" width="48px;" alt=""/><br /><sub><b>aeter</b></sub></a><br /></td>
<td align="center"><a href="http://timhwang21.gitbook.io"><img src="https://avatars3.githubusercontent.com/u/5831434?v=4" width="48px;" alt=""/><br /><sub><b>Tim Hwang</b></sub></a><br /></td>
<td align="center"><a href="http://about.me/yingfan"><img src="https://avatars1.githubusercontent.com/u/10404961?v=4" width="48px;" alt=""/><br /><sub><b>Ying Fan Chong</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/MartinJohns"><img src="https://avatars1.githubusercontent.com/u/5269069?v=4" width="48px;" alt=""/><br /><sub><b>Martin Johns</b></sub></a><br /></td>
<td align="center"><a href="https://www.jvt.me"><img src="https://avatars0.githubusercontent.com/u/3315059?v=4" width="48px;" alt=""/><br /><sub><b>Jamie Tanna</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/trimble"><img src="https://avatars3.githubusercontent.com/u/371317?v=4" width="48px;" alt=""/><br /><sub><b>Todd Trimble</b></sub></a><br /></td>
</tr>
<tr>
<td align="center"><a href="https://www.mitchellhanberg.com"><img src="https://avatars2.githubusercontent.com/u/5523984?v=4" width="48px;" alt=""/><br /><sub><b>Mitchell Hanberg</b></sub></a><br /></td>
<td align="center"><a href="https://franga2000.com"><img src="https://avatars3.githubusercontent.com/u/3891092?v=4" width="48px;" alt=""/><br /><sub><b>Miha Frangež</b></sub></a><br /></td>
<td align="center"><a href="https://blog.sahilister.in/"><img src="https://avatars0.githubusercontent.com/u/52946452?v=4" width="48px;" alt=""/><br /><sub><b>Sahil Dhiman</b></sub></a><br /></td>
<td align="center"><a href="https://pzoo.netlify.app/"><img src="https://avatars2.githubusercontent.com/u/17727004?v=4" width="48px;" alt=""/><br /><sub><b>Pingzhou &#124; 平舟</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/YuviGold"><img src="https://avatars0.githubusercontent.com/u/29873449?v=4" width="48px;" alt=""/><br /><sub><b>Yuval Goldberg</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/dabcoder"><img src="https://avatars3.githubusercontent.com/u/5034531?v=4" width="48px;" alt=""/><br /><sub><b>David Bouchare</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/stone"><img src="https://avatars3.githubusercontent.com/u/29077?v=4" width="48px;" alt=""/><br /><sub><b>Fredrik Steen</b></sub></a><br /></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/zye1996"><img src="https://avatars2.githubusercontent.com/u/28901953?v=4" width="48px;" alt=""/><br /><sub><b>zye1996</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/pgaxatte"><img src="https://avatars.githubusercontent.com/u/30696904?v=4" width="48px;" alt=""/><br /><sub><b>Pierre Gaxatte</b></sub></a><br /></td>
<td align="center"><a href="https://xntrik.wtf"><img src="https://avatars.githubusercontent.com/u/678260?v=4" width="48px;" alt=""/><br /><sub><b>Christian Frichot</b></sub></a><br /></td>
<td align="center"><a href="https://lukas-kaemmerling.de"><img src="https://avatars.githubusercontent.com/u/4281581?v=4" width="48px;" alt=""/><br /><sub><b>Lukas Kämmerling</b></sub></a><br /></td>
<td align="center"><a href="https://inetant.net/"><img src="https://avatars.githubusercontent.com/u/1765366?v=4" width="48px;" alt=""/><br /><sub><b>Antoine Meillet</b></sub></a><br /></td>
<td align="center"><a href="https://www.patreon.com/cclauss"><img src="https://avatars.githubusercontent.com/u/3709715?v=4" width="48px;" alt=""/><br /><sub><b>Christian Clauss</b></sub></a><br /></td>
</tr>
</table>

View File

@ -19,3 +19,4 @@ wtf:
height: 2
width: 2
refreshInterval: 30
updateInterval: 15

View File

@ -1,71 +0,0 @@
package app
import (
"errors"
"github.com/olebedev/config"
"github.com/rivo/tview"
)
// WtfAppManager handles the instances of WtfApp, ensuring that they're displayed as requested
type WtfAppManager struct {
WtfApps []*WtfApp
selected int
}
// NewAppManager creates and returns an instance of AppManager
func NewAppManager() WtfAppManager {
appMan := WtfAppManager{
WtfApps: []*WtfApp{},
}
return appMan
}
// MakeNewWtfApp creates and starts a new instance of WtfApp from a set of configuration params
func (appMan *WtfAppManager) MakeNewWtfApp(config *config.Config, configFilePath string) {
wtfApp := NewWtfApp(tview.NewApplication(), config, configFilePath)
appMan.Add(wtfApp)
wtfApp.Start()
}
// Add adds a WtfApp to the collection of apps that the AppManager manages.
// This app is then available for display onscreen.
func (appMan *WtfAppManager) Add(wtfApp *WtfApp) {
appMan.WtfApps = append(appMan.WtfApps, wtfApp)
}
// Current returns the currently-displaying instance of WtfApp
func (appMan *WtfAppManager) Current() (*WtfApp, error) {
if appMan.selected < 0 || appMan.selected >= len(appMan.WtfApps) {
return nil, errors.New("invalid app index selected")
}
return appMan.WtfApps[appMan.selected], nil
}
// Next cycles the WtfApps forward by one, making the next one in the list
// the current one. If there are none after the current one, it wraps around.
func (appMan *WtfAppManager) Next() (*WtfApp, error) {
appMan.selected++
if appMan.selected >= len(appMan.WtfApps) {
appMan.selected = 0
}
return appMan.Current()
}
// Prev cycles the WtfApps backwards by one, making the previous one in the
// list the current one. If there are none before the current one, it wraps around.
func (appMan *WtfAppManager) Prev() (*WtfApp, error) {
appMan.selected--
if appMan.selected < 0 {
appMan.selected = len(appMan.WtfApps) - 1
}
return appMan.Current()
}

View File

@ -1,104 +0,0 @@
package app
import (
"fmt"
"os"
"strings"
"github.com/logrusorgru/aurora"
"github.com/olebedev/config"
)
const exitMessageHeader = `
____ __ ____ .___________. _______
\ \ / \ / / | || ____|
\ \/ \/ / ----| |-----| |__
\ / | | | __|
\ /\ / | | | |
\__/ \__/ |__| |__|
the personal information dashboard for your terminal
`
// DisplayExitMessage displays the onscreen exit message when the app quits
func (wtfApp *WtfApp) DisplayExitMessage() {
exitMessageIsDisplayable := readDisplayableConfig(wtfApp.config)
wtfApp.displayExitMsg(exitMessageIsDisplayable)
}
/* -------------------- Unexported Functions -------------------- */
func (wtfApp *WtfApp) displayExitMsg(exitMessageIsDisplayable bool) string {
// If a sponsor or contributor and opt out of seeing the exit message, do not display it
if (wtfApp.ghUser.IsContributor || wtfApp.ghUser.IsSponsor) && !exitMessageIsDisplayable {
return ""
}
msgs := []string{}
msgs = append(msgs, aurora.Magenta(exitMessageHeader).String())
if wtfApp.ghUser.IsContributor {
msgs = append(msgs, wtfApp.contributorThankYouMessage())
}
if wtfApp.ghUser.IsSponsor {
msgs = append(msgs, wtfApp.sponsorThankYouMessage())
}
if !wtfApp.ghUser.IsContributor && !wtfApp.ghUser.IsSponsor {
msgs = append(msgs, wtfApp.supportRequestMessage())
}
displayMsg := strings.Join(msgs, "\n")
fmt.Println(displayMsg)
return displayMsg
}
// readDisplayableConfig figures out whether or not the exit message should be displayed
// per the user's wishes. It allows contributors and sponsors to opt out of the exit message
func readDisplayableConfig(cfg *config.Config) bool {
displayExitMsg := cfg.UBool("wtf.exitMessage.display", true)
return displayExitMsg
}
// readGitHubAPIKey attempts to find a GitHub API key somewhere in the configuration file
func readGitHubAPIKey(cfg *config.Config) string {
apiKey := cfg.UString("wtf.exitMessage.githubAPIKey", os.Getenv("WTF_GITHUB_TOKEN"))
if apiKey != "" {
return apiKey
}
moduleConfig, err := cfg.Get("wtf.mods.github")
if err != nil {
return ""
}
return moduleConfig.UString("apiKey", "")
}
/* -------------------- Messaging -------------------- */
func (wtfApp *WtfApp) contributorThankYouMessage() string {
str := " On behalf of all the users of WTF, thank you for contributing to the source code."
str += fmt.Sprintf(" %s", aurora.Green("\n\n You rock."))
return str
}
func (wtfApp *WtfApp) sponsorThankYouMessage() string {
str := " Your sponsorship of WTF makes a difference. Thank you for sponsoring and supporting WTF."
str += fmt.Sprintf(" %s", aurora.Green("\n\n You're awesome."))
return str
}
func (wtfApp *WtfApp) supportRequestMessage() string {
str := " The development and maintenance of WTF is supported by sponsorships.\n"
str += fmt.Sprintf(" Please consider sponsoring WTF at %s\n", aurora.Green("https://github.com/sponsors/senorprogrammer"))
return str
}

View File

@ -1,71 +0,0 @@
package app
import (
"strings"
"testing"
"github.com/wtfutil/wtf/support"
"gotest.tools/assert"
)
func Test_displayExitMessage(t *testing.T) {
tests := []struct {
name string
isDisplayable bool
isContributor bool
isSponsor bool
compareWith string
expected string
}{
{
name: "when not displayable",
isDisplayable: false,
isContributor: true,
isSponsor: true,
compareWith: "equals",
expected: "",
},
{
name: "when contributor",
isDisplayable: true,
isContributor: true,
compareWith: "contains",
expected: "thank you for contributing",
},
{
name: "when sponsor",
isDisplayable: true,
isSponsor: true,
compareWith: "contains",
expected: "Thank you for sponsoring",
},
{
name: "when user",
isDisplayable: true,
isContributor: false,
isSponsor: false,
compareWith: "contains",
expected: "supported by sponsorships",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wtfApp := WtfApp{}
wtfApp.ghUser = &support.GitHubUser{
IsContributor: tt.isContributor,
IsSponsor: tt.isSponsor,
}
actual := wtfApp.displayExitMsg(tt.isDisplayable)
if tt.compareWith == "equals" {
assert.Equal(t, actual, tt.expected)
}
if tt.compareWith == "contains" {
assert.Equal(t, true, strings.Contains(actual, tt.expected))
}
})
}
}

View File

@ -1,7 +1,6 @@
package app
import (
"fmt"
"sort"
"github.com/olebedev/config"
@ -9,7 +8,6 @@ import (
"github.com/wtfutil/wtf/wtf"
)
// FocusState is a custom type that differentiates focusable scopes
type FocusState int
const (
@ -21,18 +19,17 @@ const (
// FocusTracker is used by the app to track which onscreen widget currently has focus,
// and to move focus between widgets.
type FocusTracker struct {
App *tview.Application
Idx int
IsFocused bool
Widgets []wtf.Wtfable
config *config.Config
tviewApp *tview.Application
config *config.Config
}
// NewFocusTracker creates and returns an instance of FocusTracker
func NewFocusTracker(tviewApp *tview.Application, widgets []wtf.Wtfable, config *config.Config) FocusTracker {
func NewFocusTracker(app *tview.Application, widgets []wtf.Wtfable, config *config.Config) FocusTracker {
focusTracker := FocusTracker{
tviewApp: tviewApp,
App: app,
Idx: -1,
IsFocused: false,
Widgets: widgets,
@ -47,7 +44,6 @@ func NewFocusTracker(tviewApp *tview.Application, widgets []wtf.Wtfable, config
/* -------------------- Exported Functions -------------------- */
// FocusOn puts the focus on the item that belongs to the focus character passed in
func (tracker *FocusTracker) FocusOn(char string) bool {
if !tracker.useNavShortcuts() {
return false
@ -111,7 +107,6 @@ func (tracker *FocusTracker) Prev() {
tracker.IsFocused = true
}
// Refocus forces the focus back to the currently-selected item
func (tracker *FocusTracker) Refocus() {
tracker.focus(tracker.Idx)
}
@ -120,7 +115,6 @@ func (tracker *FocusTracker) Refocus() {
// AssignHotKeys assigns an alphabetic keyboard character to each focusable
// widget so that the widget can be brought into focus by pressing that keyboard key
// Valid numbers are between 1 and 9, inclusive
func (tracker *FocusTracker) assignHotKeys() {
if !tracker.useNavShortcuts() {
return
@ -128,37 +122,30 @@ func (tracker *FocusTracker) assignHotKeys() {
usedKeys := make(map[string]bool)
focusables := tracker.focusables()
i := 1
// First, block out the explicitly-defined characters so they can't be automatically
// assigned to other modules
for _, focusable := range focusables {
if focusable.FocusChar() != "" {
usedKeys[focusable.FocusChar()] = true
}
}
focusNum := 1
// Range over all the modules and assign focus characters to any that are focusable
// and don't have explicitly-defined focus characters
for _, focusable := range focusables {
if focusable.FocusChar() != "" {
continue
}
if _, foundKey := usedKeys[fmt.Sprint(focusNum)]; foundKey {
for ; foundKey; _, foundKey = usedKeys[fmt.Sprint(focusNum)] {
focusNum++
if _, foundKey := usedKeys[string('0'+i)]; foundKey {
for ; foundKey; _, foundKey = usedKeys[string('0'+i)] {
i++
}
}
// Don't allow focus characters > "9"
if focusNum >= 10 {
// Don't have nav characters > "9"
if i >= 10 {
break
}
focusable.SetFocusChar(fmt.Sprint(focusNum))
focusNum++
focusable.SetFocusChar(string('0' + i))
i++
}
}
@ -200,7 +187,7 @@ func (tracker *FocusTracker) focus(idx int) {
widget.CommonSettings().Colors.BorderTheme.Focused,
),
)
tracker.tviewApp.SetFocus(view)
tracker.App.SetFocus(view)
}
func (tracker *FocusTracker) focusables() []wtf.Wtfable {
@ -213,7 +200,7 @@ func (tracker *FocusTracker) focusables() []wtf.Wtfable {
}
// Sort for deterministic ordering
sort.SliceStable(focusable, func(i, j int) bool {
sort.SliceStable(focusable[:], func(i, j int) bool {
iTop := focusable[i].CommonSettings().Top
jTop := focusable[j].CommonSettings().Top
@ -243,7 +230,7 @@ func (tracker *FocusTracker) focusState() FocusState {
}
for _, widget := range tracker.Widgets {
if widget.TextView() == tracker.tviewApp.GetFocus() {
if widget.TextView() == tracker.App.GetFocus() {
return widgetFocused
}
}

View File

@ -5,77 +5,55 @@ import (
"os"
"github.com/logrusorgru/aurora"
"github.com/wtfutil/wtf/cfg"
"github.com/wtfutil/wtf/wtf"
)
// ModuleValidator is responsible for validating the state of a module's configuration
type ModuleValidator struct{}
type widgetError struct {
name string
validationErrors []cfg.Validatable
}
// NewModuleValidator creates and returns an instance of ModuleValidator
func NewModuleValidator() *ModuleValidator {
return &ModuleValidator{}
val := &ModuleValidator{}
return val
}
// Validate rolls through all the enabled widgets and looks for configuration errors.
// If it finds any it stringifies them, writes them to the console, and kills the app gracefully
func (val *ModuleValidator) Validate(widgets []wtf.Wtfable) {
validationErrors := validate(widgets)
var errStr string
hasErrors := false
if len(validationErrors) > 0 {
fmt.Println()
for _, error := range validationErrors {
for _, message := range error.errorMessages() {
fmt.Println(message)
for _, widget := range widgets {
var widgetErrStr string
for _, val := range widget.CommonSettings().Validations() {
if val.HasError() {
hasErrors = true
widgetErrStr += fmt.Sprintf(" - %s\t%s %v\n", val, aurora.Red("Error:"), val.Error())
}
}
if widgetErrStr != "" {
errStr += fmt.Sprintf(
"%s\n",
fmt.Sprintf(
"%s in %s configuration",
aurora.Red("Errors"),
aurora.Yellow(
fmt.Sprintf(
"%s.position",
widget.Name(),
),
),
),
)
errStr += widgetErrStr + "\n"
}
}
if hasErrors {
fmt.Println()
fmt.Println(errStr)
os.Exit(1)
}
}
func validate(widgets []wtf.Wtfable) (widgetErrors []widgetError) {
for _, widget := range widgets {
error := widgetError{name: widget.Name()}
for _, val := range widget.CommonSettings().Validations() {
if val.HasError() {
error.validationErrors = append(error.validationErrors, val)
}
}
if len(error.validationErrors) > 0 {
widgetErrors = append(widgetErrors, error)
}
}
return widgetErrors
}
func (err widgetError) errorMessages() (messages []string) {
widgetMessage := fmt.Sprintf(
"%s in %s configuration",
aurora.Red("Errors"),
aurora.Yellow(
fmt.Sprintf(
"%s.position",
err.name,
),
),
)
messages = append(messages, widgetMessage)
for _, e := range err.validationErrors {
configMessage := fmt.Sprintf(" - %s\t%s %v", e.String(), aurora.Red("Error:"), e.Error())
messages = append(messages, configMessage)
}
return messages
}

View File

@ -1,102 +0,0 @@
package app
import (
"fmt"
"testing"
"github.com/logrusorgru/aurora"
"github.com/olebedev/config"
"github.com/stretchr/testify/assert"
"github.com/wtfutil/wtf/wtf"
)
const (
valid = `
wtf:
mods:
clocks:
enabled: true
position:
top: 0
left: 0
height: 1
width: 1
refreshInterval: 30`
invalid = `
wtf:
mods:
clocks:
enabled: true
position:
top: abc
left: 0
height: 1
width: 1
refreshInterval: 30`
)
func Test_NewModuleValidator(t *testing.T) {
assert.IsType(t, &ModuleValidator{}, NewModuleValidator())
}
func Test_validate(t *testing.T) {
tests := []struct {
name string
moduleName string
config *config.Config
expected []string
}{
{
name: "valid config",
moduleName: "clocks",
config: func() *config.Config {
cfg, _ := config.ParseYaml(valid)
return cfg
}(),
expected: []string{},
},
{
name: "invalid config",
moduleName: "clocks",
config: func() *config.Config {
cfg, _ := config.ParseYaml(invalid)
return cfg
}(),
expected: []string{
fmt.Sprintf("%s in %s configuration", aurora.Red("Errors"), aurora.Yellow("clocks.position")),
fmt.Sprintf(
" - Invalid value for %s: 0 %s strconv.ParseInt: parsing \"abc\": invalid syntax",
aurora.Yellow("top"),
aurora.Red("Error:"),
),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
widget := MakeWidget(nil, nil, tt.moduleName, tt.config)
if widget == nil {
t.Logf("Failed to create widget %s", tt.moduleName)
t.FailNow()
}
errs := validate([]wtf.Wtfable{widget})
if len(tt.expected) == 0 {
assert.Empty(t, errs)
} else {
assert.NotEmpty(t, errs)
var actual []string
for _, err := range errs {
actual = append(actual, err.errorMessages()...)
}
assert.Equal(t, tt.expected, actual)
}
})
}
}

View File

@ -3,7 +3,6 @@ package app
import (
"github.com/olebedev/config"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/modules/asana"
"github.com/wtfutil/wtf/modules/azuredevops"
"github.com/wtfutil/wtf/modules/bamboohr"
"github.com/wtfutil/wtf/modules/bargraph"
@ -14,7 +13,6 @@ import (
"github.com/wtfutil/wtf/modules/circleci"
"github.com/wtfutil/wtf/modules/clocks"
"github.com/wtfutil/wtf/modules/cmdrunner"
"github.com/wtfutil/wtf/modules/covid"
"github.com/wtfutil/wtf/modules/cryptoexchanges/bittrex"
"github.com/wtfutil/wtf/modules/cryptoexchanges/blockfolio"
"github.com/wtfutil/wtf/modules/cryptoexchanges/cryptolive"
@ -34,16 +32,13 @@ import (
"github.com/wtfutil/wtf/modules/gitlabtodo"
"github.com/wtfutil/wtf/modules/gitter"
"github.com/wtfutil/wtf/modules/googleanalytics"
"github.com/wtfutil/wtf/modules/grafana"
"github.com/wtfutil/wtf/modules/gspreadsheets"
"github.com/wtfutil/wtf/modules/hackernews"
"github.com/wtfutil/wtf/modules/healthchecks"
"github.com/wtfutil/wtf/modules/hibp"
"github.com/wtfutil/wtf/modules/ipaddresses/ipapi"
"github.com/wtfutil/wtf/modules/ipaddresses/ipinfo"
"github.com/wtfutil/wtf/modules/jenkins"
"github.com/wtfutil/wtf/modules/jira"
"github.com/wtfutil/wtf/modules/krisinformation"
"github.com/wtfutil/wtf/modules/kubernetes"
"github.com/wtfutil/wtf/modules/logger"
"github.com/wtfutil/wtf/modules/mercurial"
@ -61,19 +56,17 @@ import (
"github.com/wtfutil/wtf/modules/spotify"
"github.com/wtfutil/wtf/modules/spotifyweb"
"github.com/wtfutil/wtf/modules/status"
"github.com/wtfutil/wtf/modules/stocks/finnhub"
"github.com/wtfutil/wtf/modules/stocks/yfinance"
"github.com/wtfutil/wtf/modules/subreddit"
"github.com/wtfutil/wtf/modules/textfile"
"github.com/wtfutil/wtf/modules/todo"
"github.com/wtfutil/wtf/modules/todo_plus"
"github.com/wtfutil/wtf/modules/todoist"
"github.com/wtfutil/wtf/modules/transmission"
"github.com/wtfutil/wtf/modules/travisci"
"github.com/wtfutil/wtf/modules/trello"
"github.com/wtfutil/wtf/modules/twitch"
"github.com/wtfutil/wtf/modules/twitter"
"github.com/wtfutil/wtf/modules/twitterstats"
"github.com/wtfutil/wtf/modules/unknown"
"github.com/wtfutil/wtf/modules/uptimerobot"
"github.com/wtfutil/wtf/modules/victorops"
"github.com/wtfutil/wtf/modules/weatherservices/arpansagovau"
"github.com/wtfutil/wtf/modules/weatherservices/prettyweather"
@ -84,7 +77,7 @@ import (
// MakeWidget creates and returns instances of widgets
func MakeWidget(
tviewApp *tview.Application,
app *tview.Application,
pages *tview.Pages,
moduleName string,
config *config.Config,
@ -107,251 +100,224 @@ func MakeWidget(
switch moduleConfig.UString("type", moduleName) {
case "arpansagovau":
settings := arpansagovau.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = arpansagovau.NewWidget(tviewApp, settings)
case "asana":
settings := asana.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = asana.NewWidget(tviewApp, pages, settings)
widget = arpansagovau.NewWidget(app, settings)
case "azuredevops":
settings := azuredevops.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = azuredevops.NewWidget(tviewApp, pages, settings)
widget = azuredevops.NewWidget(app, pages, settings)
case "bamboohr":
settings := bamboohr.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = bamboohr.NewWidget(tviewApp, settings)
widget = bamboohr.NewWidget(app, settings)
case "bargraph":
settings := bargraph.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = bargraph.NewWidget(tviewApp, settings)
widget = bargraph.NewWidget(app, settings)
case "bittrex":
settings := bittrex.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = bittrex.NewWidget(tviewApp, settings)
widget = bittrex.NewWidget(app, settings)
case "blockfolio":
settings := blockfolio.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = blockfolio.NewWidget(tviewApp, settings)
widget = blockfolio.NewWidget(app, settings)
case "buildkite":
settings := buildkite.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = buildkite.NewWidget(tviewApp, pages, settings)
widget = buildkite.NewWidget(app, pages, settings)
case "cdsFavorites":
settings := cdsfavorites.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = cdsfavorites.NewWidget(tviewApp, pages, settings)
widget = cdsfavorites.NewWidget(app, pages, settings)
case "cdsQueue":
settings := cdsqueue.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = cdsqueue.NewWidget(tviewApp, pages, settings)
widget = cdsqueue.NewWidget(app, pages, settings)
case "cdsStatus":
settings := cdsstatus.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = cdsstatus.NewWidget(tviewApp, pages, settings)
widget = cdsstatus.NewWidget(app, pages, settings)
case "circleci":
settings := circleci.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = circleci.NewWidget(tviewApp, settings)
widget = circleci.NewWidget(app, settings)
case "clocks":
settings := clocks.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = clocks.NewWidget(tviewApp, settings)
case "covid":
settings := covid.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = covid.NewWidget(tviewApp, settings)
widget = clocks.NewWidget(app, settings)
case "cmdrunner":
settings := cmdrunner.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = cmdrunner.NewWidget(tviewApp, settings)
widget = cmdrunner.NewWidget(app, settings)
case "cryptolive":
settings := cryptolive.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = cryptolive.NewWidget(tviewApp, settings)
widget = cryptolive.NewWidget(app, settings)
case "datadog":
settings := datadog.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = datadog.NewWidget(tviewApp, pages, settings)
widget = datadog.NewWidget(app, pages, settings)
case "devto":
settings := devto.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = devto.NewWidget(tviewApp, pages, settings)
widget = devto.NewWidget(app, pages, settings)
case "digitalclock":
settings := digitalclock.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = digitalclock.NewWidget(tviewApp, settings)
widget = digitalclock.NewWidget(app, settings)
case "digitalocean":
settings := digitalocean.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = digitalocean.NewWidget(tviewApp, pages, settings)
widget = digitalocean.NewWidget(app, pages, settings)
case "docker":
settings := docker.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = docker.NewWidget(tviewApp, pages, settings)
widget = docker.NewWidget(app, pages, settings)
case "feedreader":
settings := feedreader.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = feedreader.NewWidget(tviewApp, pages, settings)
widget = feedreader.NewWidget(app, pages, settings)
case "football":
settings := football.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = football.NewWidget(tviewApp, pages, settings)
widget = football.NewWidget(app, pages, settings)
case "gcal":
settings := gcal.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gcal.NewWidget(tviewApp, settings)
widget = gcal.NewWidget(app, settings)
case "gerrit":
settings := gerrit.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gerrit.NewWidget(tviewApp, pages, settings)
widget = gerrit.NewWidget(app, pages, settings)
case "git":
settings := git.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = git.NewWidget(tviewApp, pages, settings)
widget = git.NewWidget(app, pages, settings)
case "github":
settings := github.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = github.NewWidget(tviewApp, pages, settings)
widget = github.NewWidget(app, pages, settings)
case "gitlab":
settings := gitlab.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gitlab.NewWidget(tviewApp, pages, settings)
widget = gitlab.NewWidget(app, pages, settings)
case "gitlabtodo":
settings := gitlabtodo.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gitlabtodo.NewWidget(tviewApp, pages, settings)
widget = gitlabtodo.NewWidget(app, pages, settings)
case "gitter":
settings := gitter.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gitter.NewWidget(tviewApp, pages, settings)
widget = gitter.NewWidget(app, pages, settings)
case "googleanalytics":
settings := googleanalytics.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = googleanalytics.NewWidget(tviewApp, settings)
widget = googleanalytics.NewWidget(app, settings)
case "gspreadsheets":
settings := gspreadsheets.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = gspreadsheets.NewWidget(tviewApp, settings)
case "grafana":
settings := grafana.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = grafana.NewWidget(tviewApp, pages, settings)
widget = gspreadsheets.NewWidget(app, settings)
case "hackernews":
settings := hackernews.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = hackernews.NewWidget(tviewApp, pages, settings)
case "healthchecks":
settings := healthchecks.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = healthchecks.NewWidget(tviewApp, pages, settings)
widget = hackernews.NewWidget(app, pages, settings)
case "hibp":
settings := hibp.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = hibp.NewWidget(tviewApp, settings)
widget = hibp.NewWidget(app, settings)
case "ipapi":
settings := ipapi.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = ipapi.NewWidget(tviewApp, settings)
widget = ipapi.NewWidget(app, settings)
case "ipinfo":
settings := ipinfo.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = ipinfo.NewWidget(tviewApp, settings)
widget = ipinfo.NewWidget(app, settings)
case "jenkins":
settings := jenkins.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = jenkins.NewWidget(tviewApp, pages, settings)
widget = jenkins.NewWidget(app, pages, settings)
case "jira":
settings := jira.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = jira.NewWidget(tviewApp, pages, settings)
widget = jira.NewWidget(app, pages, settings)
case "kubernetes":
settings := kubernetes.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = kubernetes.NewWidget(tviewApp, settings)
case "krisinformation":
settings := krisinformation.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = krisinformation.NewWidget(tviewApp, settings)
widget = kubernetes.NewWidget(app, settings)
case "logger":
settings := logger.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = logger.NewWidget(tviewApp, settings)
widget = logger.NewWidget(app, settings)
case "mercurial":
settings := mercurial.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = mercurial.NewWidget(tviewApp, pages, settings)
widget = mercurial.NewWidget(app, pages, settings)
case "nbascore":
settings := nbascore.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = nbascore.NewWidget(tviewApp, pages, settings)
widget = nbascore.NewWidget(app, pages, settings)
case "newrelic":
settings := newrelic.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = newrelic.NewWidget(tviewApp, pages, settings)
widget = newrelic.NewWidget(app, pages, settings)
case "opsgenie":
settings := opsgenie.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = opsgenie.NewWidget(tviewApp, settings)
widget = opsgenie.NewWidget(app, settings)
case "pagerduty":
settings := pagerduty.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = pagerduty.NewWidget(tviewApp, settings)
widget = pagerduty.NewWidget(app, settings)
case "pihole":
settings := pihole.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = pihole.NewWidget(tviewApp, pages, settings)
widget = pihole.NewWidget(app, pages, settings)
case "power":
settings := power.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = power.NewWidget(tviewApp, settings)
widget = power.NewWidget(app, settings)
case "prettyweather":
settings := prettyweather.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = prettyweather.NewWidget(tviewApp, settings)
widget = prettyweather.NewWidget(app, settings)
case "pocket":
settings := pocket.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = pocket.NewWidget(tviewApp, pages, settings)
widget = pocket.NewWidget(app, pages, settings)
case "resourceusage":
settings := resourceusage.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = resourceusage.NewWidget(tviewApp, settings)
widget = resourceusage.NewWidget(app, settings)
case "rollbar":
settings := rollbar.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = rollbar.NewWidget(tviewApp, pages, settings)
widget = rollbar.NewWidget(app, pages, settings)
case "security":
settings := security.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = security.NewWidget(tviewApp, settings)
widget = security.NewWidget(app, settings)
case "spacex":
settings := spacex.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = spacex.NewWidget(tviewApp, settings)
widget = spacex.NewWidget(app, settings)
case "spotify":
settings := spotify.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = spotify.NewWidget(tviewApp, pages, settings)
widget = spotify.NewWidget(app, pages, settings)
case "spotifyweb":
settings := spotifyweb.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = spotifyweb.NewWidget(tviewApp, pages, settings)
widget = spotifyweb.NewWidget(app, pages, settings)
case "status":
settings := status.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = status.NewWidget(tviewApp, settings)
widget = status.NewWidget(app, settings)
case "subreddit":
settings := subreddit.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = subreddit.NewWidget(tviewApp, pages, settings)
widget = subreddit.NewWidget(app, pages, settings)
case "textfile":
settings := textfile.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = textfile.NewWidget(tviewApp, pages, settings)
widget = textfile.NewWidget(app, pages, settings)
case "todo":
settings := todo.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = todo.NewWidget(tviewApp, pages, settings)
case "todo_plus":
settings := todo_plus.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = todo_plus.NewWidget(tviewApp, pages, settings)
widget = todo.NewWidget(app, pages, settings)
case "todoist":
settings := todo_plus.FromTodoist(moduleName, moduleConfig, config)
widget = todo_plus.NewWidget(tviewApp, pages, settings)
settings := todoist.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = todoist.NewWidget(app, pages, settings)
case "transmission":
settings := transmission.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = transmission.NewWidget(tviewApp, pages, settings)
widget = transmission.NewWidget(app, pages, settings)
case "travisci":
settings := travisci.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = travisci.NewWidget(tviewApp, pages, settings)
widget = travisci.NewWidget(app, pages, settings)
case "trello":
settings := todo_plus.FromTrello(moduleName, moduleConfig, config)
widget = todo_plus.NewWidget(tviewApp, pages, settings)
settings := trello.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = trello.NewWidget(app, settings)
case "twitch":
settings := twitch.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = twitch.NewWidget(tviewApp, pages, settings)
widget = twitch.NewWidget(app, pages, settings)
case "twitter":
settings := twitter.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = twitter.NewWidget(tviewApp, pages, settings)
widget = twitter.NewWidget(app, pages, settings)
case "twitterstats":
settings := twitterstats.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = twitterstats.NewWidget(tviewApp, pages, settings)
case "uptimerobot":
settings := uptimerobot.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = uptimerobot.NewWidget(tviewApp, pages, settings)
widget = twitterstats.NewWidget(app, pages, settings)
case "victorops":
settings := victorops.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = victorops.NewWidget(tviewApp, settings)
widget = victorops.NewWidget(app, settings)
case "weather":
settings := weather.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = weather.NewWidget(tviewApp, pages, settings)
widget = weather.NewWidget(app, pages, settings)
case "zendesk":
settings := zendesk.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = zendesk.NewWidget(tviewApp, pages, settings)
widget = zendesk.NewWidget(app, pages, settings)
case "exchangerates":
settings := exchangerates.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = exchangerates.NewWidget(tviewApp, pages, settings)
case "finnhub":
settings := finnhub.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = finnhub.NewWidget(tviewApp, settings)
case "yfinance":
settings := yfinance.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = yfinance.NewWidget(tviewApp, settings)
widget = exchangerates.NewWidget(app, pages, settings)
default:
settings := unknown.NewSettingsFromYAML(moduleName, moduleConfig, config)
widget = unknown.NewWidget(tviewApp, settings)
widget = unknown.NewWidget(app, settings)
}
return widget
}
// MakeWidgets creates and returns a collection of enabled widgets
func MakeWidgets(tviewApp *tview.Application, pages *tview.Pages, config *config.Config) []wtf.Wtfable {
func MakeWidgets(app *tview.Application, pages *tview.Pages, config *config.Config) []wtf.Wtfable {
widgets := []wtf.Wtfable{}
moduleNames, _ := config.Map("wtf.mods")
for moduleName := range moduleNames {
widget := MakeWidget(tviewApp, pages, moduleName, config)
widget := MakeWidget(app, pages, moduleName, config)
if widget != nil {
widgets = append(widgets, widget)

View File

@ -1,19 +1,15 @@
package app
import (
"fmt"
"log"
"os"
"time"
"github.com/gdamore/tcell"
_ "github.com/gdamore/tcell/terminfo/extended"
"github.com/logrusorgru/aurora"
"github.com/olebedev/config"
"github.com/radovskyb/watcher"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/cfg"
"github.com/wtfutil/wtf/support"
"github.com/wtfutil/wtf/utils"
"github.com/wtfutil/wtf/wtf"
)
@ -21,42 +17,39 @@ import (
// WtfApp is the container for a collection of widgets that are all constructed from a single
// configuration file and displayed together
type WtfApp struct {
TViewApp *tview.Application
app *tview.Application
config *config.Config
configFilePath string
display *Display
focusTracker FocusTracker
ghUser *support.GitHubUser
pages *tview.Pages
validator *ModuleValidator
widgets []wtf.Wtfable
}
// NewWtfApp creates and returns an instance of WtfApp
func NewWtfApp(tviewApp *tview.Application, config *config.Config, configFilePath string) *WtfApp {
wtfApp := &WtfApp{
TViewApp: tviewApp,
func NewWtfApp(app *tview.Application, config *config.Config, configFilePath string) *WtfApp {
wtfApp := WtfApp{
app: app,
config: config,
configFilePath: configFilePath,
pages: tview.NewPages(),
}
wtfApp.TViewApp.SetBeforeDrawFunc(func(s tcell.Screen) bool {
wtfApp.app.SetBeforeDrawFunc(func(s tcell.Screen) bool {
s.Clear()
return false
})
wtfApp.widgets = MakeWidgets(wtfApp.TViewApp, wtfApp.pages, wtfApp.config)
wtfApp.app.SetInputCapture(wtfApp.keyboardIntercept)
wtfApp.widgets = MakeWidgets(wtfApp.app, wtfApp.pages, wtfApp.config)
wtfApp.display = NewDisplay(wtfApp.widgets, wtfApp.config)
wtfApp.focusTracker = NewFocusTracker(wtfApp.TViewApp, wtfApp.widgets, wtfApp.config)
wtfApp.focusTracker = NewFocusTracker(wtfApp.app, wtfApp.widgets, wtfApp.config)
wtfApp.validator = NewModuleValidator()
githubAPIKey := readGitHubAPIKey(wtfApp.config)
wtfApp.ghUser = support.NewGitHubUser(githubAPIKey)
wtfApp.pages.AddPage("grid", wtfApp.display.Grid, true, true)
wtfApp.app.SetRoot(wtfApp.pages, true)
wtfApp.validator.Validate(wtfApp.widgets)
@ -67,29 +60,15 @@ func NewWtfApp(tviewApp *tview.Application, config *config.Config, configFilePat
),
)
wtfApp.TViewApp.SetInputCapture(wtfApp.keyboardIntercept)
wtfApp.TViewApp.SetRoot(wtfApp.pages, true)
return wtfApp
return &wtfApp
}
/* -------------------- Exported Functions -------------------- */
// Run starts the underlying tview app
func (wtfApp *WtfApp) Run() {
if err := wtfApp.TViewApp.Run(); err != nil {
fmt.Printf("\n%s %v\n", aurora.Red("ERROR"), err)
os.Exit(1)
}
}
// Start initializes the app
func (wtfApp *WtfApp) Start() {
go wtfApp.scheduleWidgets()
wtfApp.scheduleWidgets()
go wtfApp.watchForConfigChanges()
// FIXME: This should be moved to the AppManager
go func() { _ = wtfApp.ghUser.Load() }()
}
// Stop kills all the currently-running widgets in this app
@ -108,18 +87,9 @@ func (wtfApp *WtfApp) stopAllWidgets() {
func (wtfApp *WtfApp) keyboardIntercept(event *tcell.EventKey) *tcell.EventKey {
// These keys are global keys used by the app. Widgets should not implement these keys
switch event.Key() {
case tcell.KeyCtrlC:
wtfApp.Stop()
wtfApp.TViewApp.Stop()
wtfApp.DisplayExitMessage()
case tcell.KeyCtrlR:
wtfApp.refreshAllWidgets()
return nil
case tcell.KeyCtrlSpace:
// FIXME: This can't reside in the app, the app doesn't know about
// the AppManager. The AppManager needs to catch this one
fmt.Println("Next app")
return nil
case tcell.KeyTab:
wtfApp.focusTracker.Next()
case tcell.KeyBacktab:
@ -139,7 +109,6 @@ func (wtfApp *WtfApp) keyboardIntercept(event *tcell.EventKey) *tcell.EventKey {
switch string(event.Rune()) {
case "/":
return nil
default:
}
}
@ -171,9 +140,9 @@ func (wtfApp *WtfApp) watchForConfigChanges() {
wtfApp.Stop()
config := cfg.LoadWtfConfigFile(wtfApp.configFilePath)
newApp := NewWtfApp(wtfApp.TViewApp, config, wtfApp.configFilePath)
openURLUtil := utils.ToStrs(config.UList("wtf.openUrlUtil", []interface{}{}))
utils.Init(config.UString("wtf.openFileUtil", "open"), openURLUtil)
newApp := NewWtfApp(wtfApp.app, config, wtfApp.configFilePath)
openUrlUtil := utils.ToStrs(config.UList("wtf.openUrlUtil", []interface{}{}))
utils.Init(config.UString("wtf.openFileUtil", "open"), openUrlUtil)
newApp.Start()
case err := <-watch.Error:

View File

@ -5,12 +5,6 @@ import (
"strings"
"github.com/olebedev/config"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
const (
defaultLanguageTag = "en-CA"
)
type Module struct {
@ -29,32 +23,27 @@ type Sigils struct {
}
}
// Common defines a set of common configuration settings applicable to all modules
type Common struct {
Module
PositionSettings `help:"Defines where in the grid this modules widget will be displayed."`
Sigils
Colors ColorTheme
Config *config.Config
DocPath string
Colors ColorTheme
Bordered bool `help:"Whether or not the module should be displayed with a border." values:"true, false" optional:"true" default:"true"`
Enabled bool `help:"Whether or not this module is executed and if its data displayed onscreen." values:"true, false" optional:"true" default:"false"`
Focusable bool `help:"Whether or not this module is focusable." values:"true, false" optional:"true" default:"false"`
LanguageTag string `help:"The BCP 47 langauge tag to localize text to." values:"Any supported BCP 47 language tag." optional:"true" default:"en-CA"`
RefreshInterval int `help:"How often, in seconds, this module will update its data." values:"A positive integer, 0..n." optional:"true"`
Title string `help:"The title string to show when displaying this module" optional:"true"`
Config *config.Config
focusChar int `help:"Define one of the number keys as a short cut key to access the widget." optional:"true"`
}
// NewCommonSettingsFromModule returns a common settings configuration tailed to the given module
func NewCommonSettingsFromModule(name, defaultTitle string, defaultFocusable bool, moduleConfig *config.Config, globalConfig *config.Config) *Common {
func NewCommonSettingsFromModule(name, defaultTitle string, defaultFocusable bool, moduleConfig *config.Config, globalSettings *config.Config) *Common {
baseColors := NewDefaultColorTheme()
colorsConfig, err := globalConfig.Get("wtf.colors")
colorsConfig, err := globalSettings.Get("wtf.colors")
if err != nil && strings.Contains(err.Error(), "Nonexistent map") {
// Create a default colors config to fill in for the missing one
// This comes into play when the configuration file does not contain a `colors:` key, i.e:
@ -101,7 +90,6 @@ func NewCommonSettingsFromModule(name, defaultTitle string, defaultFocusable boo
Config: moduleConfig,
Enabled: moduleConfig.UBool("enabled", false),
Focusable: moduleConfig.UBool("focusable", defaultFocusable),
LanguageTag: globalConfig.UString("wtf.language", defaultLanguageTag),
RefreshInterval: moduleConfig.UInt("refreshInterval", 300),
Title: moduleConfig.UString("title", defaultTitle),
@ -109,10 +97,11 @@ func NewCommonSettingsFromModule(name, defaultTitle string, defaultFocusable boo
}
sigilsPath := "wtf.sigils"
common.Sigils.Checkbox.Checked = globalConfig.UString(sigilsPath+".checkbox.checked", "x")
common.Sigils.Checkbox.Unchecked = globalConfig.UString(sigilsPath+".checkbox.unchecked", " ")
common.Sigils.Paging.Normal = globalConfig.UString(sigilsPath+".paging.normal", globalConfig.UString("wtf.paging.pageSigil", "*"))
common.Sigils.Paging.Selected = globalConfig.UString(sigilsPath+".paging.select", globalConfig.UString("wtf.paging.selectedSigil", "_"))
common.Sigils.Checkbox.Checked = globalSettings.UString(sigilsPath+".checkbox.checked", "x")
common.Sigils.Checkbox.Unchecked = globalSettings.UString(sigilsPath+".checkbox.unchecked", " ")
common.Sigils.Paging.Normal = globalSettings.UString(sigilsPath+".paging.normal", globalSettings.UString("wtf.paging.pageSigil", "*"))
common.Sigils.Paging.Selected = globalSettings.UString(sigilsPath+".paging.select", globalSettings.UString("wtf.paging.selectedSigil", "_"))
return &common
}
@ -135,32 +124,12 @@ func (common *Common) DefaultRowColor() string {
)
}
// FocusChar returns the keyboard number assigned to the widget used to give onscreen
// focus to this widget, as a string. Focus characters can be a range between 1 and 9
func (common *Common) FocusChar() string {
if common.focusChar <= 0 {
if common.focusChar <= -1 {
return ""
}
if common.focusChar > 9 {
return ""
}
return fmt.Sprint(common.focusChar)
}
// LocalizedPrinter returns a message.Printer instance localized to the BCP 47 language
// configuration value defined in 'wtf.language' config. If none exists, it defaults to
// 'en-CA'. Use this to format numbers, etc.
func (common *Common) LocalizedPrinter() (*message.Printer, error) {
langTag, err := language.Parse(common.LanguageTag)
if err != nil {
return nil, err
}
prntr := message.NewPrinter(langTag)
return prntr, nil
return string('0' + common.focusChar)
}
func (common *Common) RowColor(idx int) string {
@ -176,9 +145,7 @@ func (common *Common) RightAlignFormat(width int) string {
return fmt.Sprintf("%%%ds", width-borderOffset)
}
// PaginationMarker generates the pagination indicators that appear in the top-right corner
// of multisource widgets
func (common *Common) PaginationMarker(len, pos, width int) string {
func (common *Common) SigilStr(len, pos, width int) string {
sigils := ""
if len > 1 {
@ -192,15 +159,6 @@ func (common *Common) PaginationMarker(len, pos, width int) string {
return sigils
}
// SetDocumentationPath is used to explicitly set the documentation path that should be opened
// when the key to open the documentation is pressed.
// Setting this is probably not necessary unless the module documentation is nested inside a
// documentation subdirectory in the /wtfutildocs repo, or the module here has a different
// name than the module's display name in the documentation (which ideally wouldn't be a thing).
func (common *Common) SetDocumentationPath(path string) {
common.DocPath = path
}
// Validations aggregates all the validations from all the sub-sections in Common into a
// single array of validations
func (common *Common) Validations() []Validatable {

View File

@ -47,36 +47,29 @@ func Test_DefaultRowColor(t *testing.T) {
func Test_FocusChar(t *testing.T) {
tests := []struct {
name string
before func(testCfg *Common)
expectedChar string
before func(testCfg *Common)
}{
{
name: "with negative focus char",
name: "with no focus char specified",
expectedChar: "",
before: func(testCfg *Common) {
testCfg.focusChar = -1
},
expectedChar: "",
},
{
name: "with positive focus char",
name: "with explicit focus char specified",
expectedChar: "3",
before: func(testCfg *Common) {
testCfg.focusChar = 3
},
expectedChar: "3",
},
{
name: "with zero focus char",
name: "with ridiculous focus char specified",
expectedChar: "Q",
before: func(testCfg *Common) {
testCfg.focusChar = 0
testCfg.focusChar = 33
},
expectedChar: "",
},
{
name: "with large focus char",
before: func(testCfg *Common) {
testCfg.focusChar = 10
},
expectedChar: "",
},
}
@ -144,7 +137,7 @@ func Test_RightAlignFormat(t *testing.T) {
}
}
func Test_PaginationMarker(t *testing.T) {
func Test_SigilStr(t *testing.T) {
tests := []struct {
name string
len int
@ -184,7 +177,7 @@ func Test_PaginationMarker(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expected, testCfg.PaginationMarker(tt.len, tt.pos, tt.width))
assert.Equal(t, tt.expected, testCfg.SigilStr(tt.len, tt.pos, tt.width))
})
}
}

View File

@ -29,7 +29,7 @@ const (
// CreateFile creates the named file in the config directory, if it does not already exist.
// If the file exists it does not recreate it.
// If successful, returns the absolute path to the file
// If successful, eturns the absolute path to the file
// If unsuccessful, returns an error
func CreateFile(fileName string) (string, error) {
configDir, err := WtfConfigDir()
@ -37,7 +37,7 @@ func CreateFile(fileName string) (string, error) {
return "", err
}
filePath := filepath.Join(configDir, fileName)
filePath := fmt.Sprintf("%s/%s", configDir, fileName)
// Check if the file already exists; if it does not, create it
_, err = os.Stat(filePath)
@ -78,7 +78,7 @@ func WtfConfigDir() (string, error) {
if configDir == "" {
configDir = WtfConfigDirV2
} else {
configDir += "/wtf/"
configDir = configDir + "/wtf/"
}
configDir, err := expandHomeDir(configDir)
if err != nil {
@ -106,7 +106,7 @@ func LoadWtfConfigFile(filePath string) *config.Config {
// chmodConfigFile sets the mode of the config file to r+w for the owner only
func chmodConfigFile() {
configDir, _ := WtfConfigDir()
relPath := filepath.Join(configDir, WtfConfigFile)
relPath := fmt.Sprintf("%s%s", configDir, WtfConfigFile)
absPath, _ := expandHomeDir(relPath)
_, err := os.Stat(absPath)

View File

@ -36,7 +36,7 @@ const defaultConfigFile = `wtf:
odd: "white"
enabled: true
locations:
Paris: "Europe/Paris"
Avignon: "Europe/Paris"
Barcelona: "Europe/Madrid"
Dubai: "Asia/Dubai"
position:
@ -58,7 +58,7 @@ const defaultConfigFile = `wtf:
left: 1
width: 2
height: 1
refreshInterval: 14400
updateInterval: 14400
ipinfo:
colors:
name: "lightblue"

View File

@ -1,224 +0,0 @@
package cfg
import (
"errors"
"fmt"
"runtime"
"github.com/docker/docker-credential-helpers/client"
"github.com/docker/docker-credential-helpers/credentials"
"github.com/olebedev/config"
"github.com/wtfutil/wtf/logger"
)
type SecretLoadParams struct {
name string
globalConfig *config.Config
service string
secret *string
}
// Load module secrets.
//
// The credential helpers impose this structure:
//
// SERVICE is mapped to a SECRET and USERNAME
//
// Only SECRET is secret, SERVICE and USERNAME are not, so this
// API doesn't expose USERNAME.
//
// SERVICE was intended to be the URL of an API server, but
// for hosted services that do not have or need a configurable
// API server, its easier to just use the module name as the
// SERVICE:
//
// cfg.ModuleSecret(name, globalConfig, &settings.apiKey).Load()
//
// The user will use the module name as the service, and the API key as
// the secret, for example:
//
// % wtfutil save-secret circleci
// Secret: ...
//
// If a module (such as pihole, jenkins, or github) might have multiple
// instantiations each using a different API service (with its own unique
// API key), then the module should use the API URL to lookup the secret.
// For example, for github:
//
// cfg.ModuleSecret(name, globalConfig, &settings.apiKey).
// Service(settings.baseURL).
// Load()
//
// The user will use the API URL as the service, and the API key as the
// secret, for example, with github configured as:
//
// -- config.yml
// mods:
// github:
// baseURL: "https://github.mycompany.com/api/v3"
// ...
//
// the secret must be saved as:
//
// % wtfutil save-secret https://github.mycompany.com/api/v3
// Secret: ...
//
// If baseURL is not set in the configuration it will be the modules
// default, and the SERVICE will default to the module name, "github",
// and the user must save the secret as:
//
// % wtfutil save-secret github
// Secret: ...
//
// Ideally, the individual module documentation would describe the
// SERVICE name to use to save the secret.
func ModuleSecret(name string, globalConfig *config.Config, secret *string) *SecretLoadParams {
return &SecretLoadParams{
name: name,
globalConfig: globalConfig,
secret: secret,
service: name, // Default the service to the module name
}
}
func (slp *SecretLoadParams) Service(service string) *SecretLoadParams {
if service != "" {
slp.service = service
}
return slp
}
func (slp *SecretLoadParams) Load() {
configureSecret(
slp.globalConfig,
slp.service,
slp.secret,
)
}
type Secret struct {
Service string
Secret string
Username string
Store string
}
func configureSecret(
globalConfig *config.Config,
service string,
secret *string,
) {
if service == "" {
return
}
if secret == nil {
return
}
// Don't overwrite the secret if it was configured with yaml
if *secret != "" {
return
}
cred, err := FetchSecret(globalConfig, service)
if err != nil {
logger.Log(fmt.Sprintf("Loading secret failed: %s", err.Error()))
return
}
if cred == nil {
// No secret store configued.
return
}
if secret != nil && *secret == "" {
*secret = cred.Secret
}
}
// Fetch secret for `service`. Service is customarily a URL, but can be any
// identifier uniquely used by wtf to identify the service, such as the name
// of the module. nil is returned if the secretStore global property is not
// present or the secret is not found in that store.
func FetchSecret(globalConfig *config.Config, service string) (*Secret, error) {
prog := newProgram(globalConfig)
if prog == nil {
// No secret store configured.
return nil, nil
}
cred, err := client.Get(prog.runner, service)
if err != nil {
return nil, fmt.Errorf("get %v from %v: %w", service, prog.store, err)
}
return &Secret{
Service: cred.ServerURL,
Secret: cred.Secret,
Username: cred.Username,
Store: prog.store,
}, nil
}
func StoreSecret(globalConfig *config.Config, secret *Secret) error {
prog := newProgram(globalConfig)
if prog == nil {
return errors.New("cannot store secrets: wtf.secretStore is not configured")
}
cred := &credentials.Credentials{
ServerURL: secret.Service,
Username: secret.Username,
Secret: secret.Secret,
}
// docker-credential requires a username, but it isn't necessary for
// all services. Use a default if a username was not set.
if cred.Username == "" {
cred.Username = "default"
}
err := client.Store(prog.runner, cred)
if err != nil {
return fmt.Errorf("store %v: %w", prog.store, err)
}
return nil
}
type program struct {
store string
runner client.ProgramFunc
}
func newProgram(globalConfig *config.Config) *program {
secretStore := globalConfig.UString("wtf.secretStore", "(none)")
if secretStore == "(none)" {
return nil
}
if secretStore == "" {
switch runtime.GOOS {
case "windows":
secretStore = "winrt"
case "darwin":
secretStore = "osxkeychain"
default:
secretStore = "secretservice"
}
}
return &program{
secretStore,
client.NewShellProgramFunc("docker-credential-" + secretStore),
}
}

View File

@ -4,9 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/chzyer/readline"
goFlags "github.com/jessevdk/go-flags"
"github.com/olebedev/config"
"github.com/wtfutil/wtf/cfg"
@ -19,26 +17,10 @@ type Flags struct {
Module string `short:"m" long:"module" optional:"yes" description:"Display info about a specific module, i.e.: 'wtfutil -m=todo'"`
Profile bool `short:"p" long:"profile" optional:"yes" description:"Profile application memory usage"`
Version bool `short:"v" long:"version" description:"Show version info"`
// Work-around go-flags misfeatures. If any sub-command is defined
// then `wtf` (no sub-commands, the common usage), is warned about.
Opt struct {
Cmd string `positional-arg-name:"command"`
Args []string `positional-arg-name:"args"`
} `positional-args:"yes"`
hasCustom bool
}
var EXTRA = `
Commands:
save-secret <service>
service Service URL or module name of secret.
Save a secret into the secret store. The secret will be prompted for.
Requires wtf.secretStore to be configured. See individual modules for
information on what service and secret means for their configuration,
not all modules use secrets.
`
// NewFlags creates an instance of Flags
func NewFlags() *Flags {
flags := Flags{}
@ -64,58 +46,6 @@ func (flags *Flags) RenderIf(version, date string, config *config.Config) {
fmt.Printf("%s (%s)\n", version, date)
os.Exit(0)
}
if flags.Opt.Cmd == "" {
return
}
switch cmd := flags.Opt.Cmd; cmd {
case "save-secret":
var service, secret string
args := flags.Opt.Args
if len(args) < 1 || args[0] == "" {
fmt.Fprintf(os.Stderr, "save-secret: service required, see `%s --help`\n", os.Args[0])
os.Exit(1)
}
service = args[0]
if len(args) > 1 {
fmt.Fprintf(os.Stderr, "save-secret: too many arguments, see `%s --help`\n", os.Args[0])
os.Exit(1)
}
b, err := readline.Password("Secret: ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
secret = string(b)
secret = strings.TrimSpace(secret)
if secret == "" {
fmt.Fprintf(os.Stderr, "save-secret: secret required, see `%s --help`\n", os.Args[0])
os.Exit(1)
}
err = cfg.StoreSecret(config, &cfg.Secret{
Service: service,
Secret: secret,
Username: "default",
})
if err != nil {
fmt.Fprintf(os.Stderr, "Saving secret for service %q: %s\n", service, err.Error())
os.Exit(1)
}
fmt.Printf("Saved secret for service %q\n", service)
os.Exit(0)
default:
fmt.Fprintf(os.Stderr, "Command `%s` is not supported, try `%s --help`\n", cmd, os.Args[0])
os.Exit(1)
}
}
// HasCustomConfig returns TRUE if a config path was passed in, FALSE if one was not
@ -138,7 +68,6 @@ func (flags *Flags) Parse() {
parser := goFlags.NewParser(flags, goFlags.Default)
if _, err := parser.Parse(); err != nil {
if flagsErr, ok := err.(*goFlags.Error); ok && flagsErr.Type == goFlags.ErrHelp {
fmt.Println(EXTRA)
os.Exit(0)
}
}

View File

@ -40,6 +40,8 @@ func main() {
generateWidgetFile(data)
generateSettingsFile(data)
fmt.Println("Done")
}
/* -------------------- Unexported Functions -------------------- */

View File

@ -9,14 +9,16 @@ import (
type Widget struct {
view.TextWidget
app *tview.Application
settings *Settings
}
// NewWidget creates and returns an instance of Widget
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, settings.common),
TextWidget: view.NewTextWidget(app, settings.common),
app: app,
settings: settings,
}

75
go.mod
View File

@ -1,86 +1,67 @@
module github.com/wtfutil/wtf
go 1.16
go 1.14
require (
bitbucket.org/mikehouston/asana-go v0.0.0-20201102222432-715318d0343a
code.cloudfoundry.org/bytefmt v0.0.0-20190819182555-854d396b647c
github.com/Azure/go-autorest v11.1.2+incompatible // indirect
github.com/Microsoft/go-winio v0.4.14 // indirect
github.com/PagerDuty/go-pagerduty v0.0.0-20191002190746-f60f4fc45222
github.com/PuerkitoBio/goquery v1.5.0 // indirect
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
github.com/VictorAvelar/devto-api-go v1.0.0
github.com/adlio/trello v1.8.0
github.com/alecthomas/chroma v0.8.1
github.com/adlio/trello v1.7.0
github.com/alecthomas/chroma v0.7.2
github.com/andygrunwald/go-gerrit v0.0.0-20190825170856-5959a9bf9ff8
github.com/briandowns/openweathermap v0.0.0-20180804155945-5f41b7c9d92d
github.com/cenkalti/backoff v2.2.1+incompatible // indirect
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e
github.com/creack/pty v1.1.11
github.com/digitalocean/godo v1.52.0
github.com/digitalocean/godo v1.35.1
github.com/docker/distribution v2.7.1+incompatible // indirect
github.com/docker/docker v1.13.1
github.com/docker/docker-credential-helpers v0.6.3
github.com/docker/go-connections v0.4.0 // indirect
github.com/docker/go-units v0.4.0 // indirect
github.com/dustin/go-humanize v1.0.0
github.com/gdamore/tcell v1.4.0
github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c // indirect
github.com/facebookgo/freeport v0.0.0-20150612182905-d4adf43b75b9 // indirect
github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect
github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 // indirect
github.com/gdamore/tcell v1.3.0
github.com/go-ole/go-ole v1.2.4 // indirect
github.com/godbus/dbus v4.1.0+incompatible // indirect
github.com/google/go-github/v32 v32.1.0
github.com/google/go-github/v26 v26.1.3
github.com/gophercloud/gophercloud v0.5.0 // indirect
github.com/hekmon/cunits v2.0.1+incompatible // indirect
github.com/hekmon/transmissionrpc v0.0.0-20190525133028-1d589625bacd
github.com/jedib0t/go-pretty/v6 v6.1.0
github.com/imdario/mergo v0.3.8 // indirect
github.com/jessevdk/go-flags v1.4.0
github.com/lib/pq v1.2.0 // indirect
github.com/logrusorgru/aurora v0.0.0-20190803045625-94edacc10f9b
github.com/microsoft/azure-devops-go-api/azuredevops v0.0.0-20191014190507-26902c1d4325
github.com/mmcdole/gofeed v1.1.0
github.com/nicklaw5/helix v0.7.0
github.com/mmcdole/gofeed v1.0.0-beta2
github.com/mmcdole/goxpp v0.0.0-20181012175147-0068e33feabf // indirect
github.com/nicklaw5/helix v0.5.8
github.com/olebedev/config v0.0.0-20190528211619-364964f3a8e4
github.com/olekukonko/tablewriter v0.0.4
github.com/onsi/ginkgo v1.12.0 // indirect
github.com/onsi/gomega v1.9.0 // indirect
github.com/ovh/cds v0.0.0-20201014170613-39429542624d
github.com/pborman/uuid v1.2.0 // indirect
github.com/piquette/finance-go v1.0.0
github.com/onsi/ginkgo v1.10.3 // indirect
github.com/onsi/gomega v1.7.1 // indirect
github.com/ovh/cds v0.0.0-20200131143542-5e69464c6598
github.com/pkg/errors v0.9.1
github.com/pkg/profile v1.5.0
github.com/pkg/profile v1.4.0
github.com/radovskyb/watcher v1.0.7
github.com/rivo/tview v0.0.0-20200108161608-1316ea7a4b35
github.com/shirou/gopsutil v2.20.9+incompatible
github.com/shopspring/decimal v1.2.0 // indirect
github.com/shurcooL/githubv4 v0.0.0-20200802174311-f27d2ca7f6d5
github.com/shurcooL/graphql v0.0.0-20181231061246-d48a9a75455f // indirect
github.com/spf13/cobra v0.0.5 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.6.1 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
github.com/stretchr/testify v1.6.1
github.com/shirou/gopsutil v2.20.4+incompatible
github.com/stretchr/testify v1.5.1
github.com/wtfutil/spotigopher v0.0.0-20191127141047-7d8168fe103a
github.com/wtfutil/todoist v0.0.2-0.20191216004217-0ec29ceda61a
github.com/xanzy/go-gitlab v0.39.0
github.com/xanzy/go-gitlab v0.31.0
github.com/zmb3/spotify v0.0.0-20191010212056-e12fb981aacb
github.com/zorkian/go-datadog-api v2.30.0+incompatible
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208
golang.org/x/text v0.3.4
google.golang.org/api v0.33.0
github.com/zorkian/go-datadog-api v2.29.0+incompatible
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/text v0.3.2
google.golang.org/api v0.23.0
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/jarcoal/httpmock.v1 v1.0.0-20181110093347-3be5f16b70eb // indirect
gopkg.in/yaml.v2 v2.3.0
gopkg.in/yaml.v2 v2.2.8
gotest.tools v2.2.0+incompatible
jaytaylor.com/html2text v0.0.0-20200412013138-3577fbdbcff7
k8s.io/apimachinery v0.0.0-20190223094358-dcb391cde5ca
k8s.io/client-go v10.0.0+incompatible
)
// These hacks are in place to work around this bug in coreos/etcd/proxy/grpcproxy > v1.30.0 that fails
// with this error:
//
// google.golang.org/grpc/naming: module google.golang.org/grpc@latest found (v1.31.1), but does not contain package google.golang.org/grpc/naming
//
// See here for more details: https://github.com/etcd-io/etcd/issues/12124
replace google.golang.org/grpc v1.30.0 => google.golang.org/grpc v1.29.1
replace google.golang.org/grpc v1.31.0 => google.golang.org/grpc v1.29.1

655
go.sum

File diff suppressed because it is too large Load Diff

53
main.go
View File

@ -1,31 +1,44 @@
package main
// Generators
// To generate the skeleton for a new TextWidget use 'WTF_WIDGET_NAME=MySuperAwesomeWidget go generate -run=text
//go:generate -command text go run generator/textwidget.go
//go:generate text
import (
"fmt"
"log"
"os"
// Blank import of tzdata embeds the timezone database to allow Windows hosts to find timezone
// information even if the timezone database is not available on the local system. See release
// notes at https://golang.org/doc/go1.15#time/tzdata for details. This prevents "no timezone
// data available" errors in clocks module.
_ "time/tzdata"
"github.com/logrusorgru/aurora"
"github.com/olebedev/config"
"github.com/pkg/profile"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/app"
"github.com/wtfutil/wtf/cfg"
"github.com/wtfutil/wtf/flags"
"github.com/wtfutil/wtf/utils"
"github.com/wtfutil/wtf/wtf"
)
var tviewApp *tview.Application
var (
date = "dev"
version = "dev"
)
/* -------------------- Functions -------------------- */
func setTerm(config *config.Config) {
term := config.UString("wtf.term", os.Getenv("TERM"))
err := os.Setenv("TERM", term)
if err != nil {
fmt.Printf("\n%s Failed to set $TERM to %s.\n", aurora.Red("ERROR"), aurora.Yellow(term))
os.Exit(1)
}
}
/* -------------------- Main -------------------- */
func main() {
@ -35,31 +48,29 @@ func main() {
flags := flags.NewFlags()
flags.Parse()
hasCustom := flags.HasCustomConfig()
cfg.Initialize(hasCustom)
// Load the configuration file
cfg.Initialize(flags.HasCustomConfig())
config := cfg.LoadWtfConfigFile(flags.ConfigFilePath())
wtf.SetTerminal(config)
flags.RenderIf(version, date, config)
if flags.Profile {
defer profile.Start(profile.MemProfile).Stop()
}
openFileUtil := config.UString("wtf.openFileUtil", "open")
openURLUtil := utils.ToStrs(config.UList("wtf.openUrlUtil", []interface{}{}))
utils.Init(openFileUtil, openURLUtil)
openUrlUtil := utils.ToStrs(config.UList("wtf.openUrlUtil", []interface{}{}))
utils.Init(config.UString("wtf.openFileUtil", "open"), openUrlUtil)
/* Initialize the App Manager */
appMan := app.NewAppManager()
appMan.MakeNewWtfApp(config, flags.Config)
setTerm(config)
currentApp, err := appMan.Current()
if err != nil {
// Build the application
tviewApp = tview.NewApplication()
wtfApp := app.NewWtfApp(tviewApp, config, flags.Config)
wtfApp.Start()
if err := tviewApp.Run(); err != nil {
fmt.Printf("\n%s %v\n", aurora.Red("ERROR"), err)
os.Exit(1)
}
currentApp.Run()
}

View File

@ -1,280 +0,0 @@
package asana
import (
"fmt"
"strings"
"time"
asana "bitbucket.org/mikehouston/asana-go"
)
func fetchTasksFromProject(token, projectId, mode string) ([]*TaskItem, error) {
taskItems := []*TaskItem{}
uidToName := make(map[string]string)
client := asana.NewClientWithAccessToken(token)
uid, err := getCurrentUserId(client, mode)
if err != nil {
return nil, err
}
q := &asana.TaskQuery{
Project: projectId,
}
fetchedTasks, _, err := getTasksFromAsana(client, q)
if err != nil {
return nil, fmt.Errorf("error fetching tasks: %s", err)
}
processFetchedTasks(client, &fetchedTasks, &taskItems, &uidToName, mode, projectId, uid)
return taskItems, nil
}
func fetchTasksFromProjectSections(token, projectId string, sections []string, mode string) ([]*TaskItem, error) {
taskItems := []*TaskItem{}
uidToName := make(map[string]string)
client := asana.NewClientWithAccessToken(token)
uid, err := getCurrentUserId(client, mode)
if err != nil {
return nil, err
}
p := &asana.Project{
ID: projectId,
}
for _, section := range sections {
sectionId, err := findSection(client, p, section)
if err != nil {
return nil, fmt.Errorf("error fetching tasks: %s", err)
}
q := &asana.TaskQuery{
Section: sectionId,
}
fetchedTasks, _, err := getTasksFromAsana(client, q)
if err != nil {
return nil, fmt.Errorf("error fetching tasks: %s", err)
}
if len(fetchedTasks) > 0 {
taskItem := &TaskItem{
name: section,
taskType: TASK_SECTION,
}
taskItems = append(taskItems, taskItem)
}
processFetchedTasks(client, &fetchedTasks, &taskItems, &uidToName, mode, projectId, uid)
}
return taskItems, nil
}
func fetchTasksFromWorkspace(token, workspaceId, mode string) ([]*TaskItem, error) {
taskItems := []*TaskItem{}
uidToName := make(map[string]string)
client := asana.NewClientWithAccessToken(token)
uid, err := getCurrentUserId(client, mode)
if err != nil {
return nil, err
}
q := &asana.TaskQuery{
Workspace: workspaceId,
Assignee: "me",
}
fetchedTasks, _, err := getTasksFromAsana(client, q)
if err != nil {
return nil, fmt.Errorf("error fetching tasks: %s", err)
}
processFetchedTasks(client, &fetchedTasks, &taskItems, &uidToName, mode, workspaceId, uid)
return taskItems, nil
}
func toggleTaskCompletionById(token, taskId string) error {
client := asana.NewClientWithAccessToken(token)
t := &asana.Task{
ID: taskId,
}
err := t.Fetch(client)
if err != nil {
return fmt.Errorf("error fetching task: %s", err)
}
updateReq := &asana.UpdateTaskRequest{}
if *t.Completed {
f := false
updateReq.Completed = &f
} else {
t := true
updateReq.Completed = &t
}
err = t.Update(client, updateReq)
if err != nil {
return fmt.Errorf("error updating task: %s", err)
}
return nil
}
func processFetchedTasks(client *asana.Client, fetchedTasks *[]*asana.Task, taskItems *[]*TaskItem, uidToName *map[string]string, mode, projectId, uid string) {
for _, task := range *fetchedTasks {
switch {
case strings.HasSuffix(mode, "_all"):
if task.Assignee != nil {
// Check if we have already looked up this user
if assigneeName, ok := (*uidToName)[task.Assignee.ID]; ok {
task.Assignee.Name = assigneeName
} else {
// We haven't looked up this user before, perform the lookup now
assigneeName, err := getOtherUserEmail(client, task.Assignee.ID)
if err != nil {
task.Assignee.Name = "Error"
}
(*uidToName)[task.Assignee.ID] = assigneeName
task.Assignee.Name = assigneeName
}
} else {
task.Assignee = &asana.User{
Name: "Unassigned",
}
}
taskItem := buildTaskItem(task, projectId)
(*taskItems) = append((*taskItems), taskItem)
case !strings.HasSuffix(mode, "_all") && task.Assignee != nil && task.Assignee.ID == uid:
taskItem := buildTaskItem(task, projectId)
(*taskItems) = append((*taskItems), taskItem)
}
}
}
func buildTaskItem(task *asana.Task, projectId string) *TaskItem {
dueOnString := ""
if task.DueOn != nil {
dueOn := time.Time(*task.DueOn)
currentYear, _, _ := time.Now().Date()
if currentYear != dueOn.Year() {
dueOnString = dueOn.Format("Jan 2 2006")
} else {
dueOnString = dueOn.Format("Jan 2")
}
}
assignString := ""
if task.Assignee != nil {
assignString = task.Assignee.Name
}
taskItem := &TaskItem{
name: task.Name,
id: task.ID,
numSubtasks: task.NumSubtasks,
dueOn: dueOnString,
url: fmt.Sprintf("https://app.asana.com/0/%s/%s/f", projectId, task.ID),
taskType: TASK_TYPE,
completed: *task.Completed,
assignee: assignString,
}
return taskItem
}
func getOtherUserEmail(client *asana.Client, uid string) (string, error) {
if uid == "" {
return "", fmt.Errorf("missing uid")
}
u := &asana.User{
ID: uid,
}
err := u.Fetch(client, nil)
if err != nil {
return "", fmt.Errorf("error fetching user: %s", err)
}
return u.Email, nil
}
func getCurrentUserId(client *asana.Client, mode string) (string, error) {
if strings.HasSuffix(mode, "_all") {
return "", nil
}
u, err := client.CurrentUser()
if err != nil {
return "", fmt.Errorf("error getting current user: %s", err)
}
return u.ID, nil
}
func findSection(client *asana.Client, project *asana.Project, sectionName string) (string, error) {
sectionId := ""
sections, _, err := project.Sections(client, &asana.Options{
Limit: 100,
})
if err != nil {
return "", fmt.Errorf("error getting sections: %s", err)
}
for _, section := range sections {
if section.Name == sectionName {
sectionId = section.ID
break
}
}
if sectionId == "" {
return "", fmt.Errorf("we didn't find the section %s", sectionName)
}
return sectionId, nil
}
func getTasksFromAsana(client *asana.Client, q *asana.TaskQuery) ([]*asana.Task, bool, error) {
moreTasks := false
tasks, np, err := client.QueryTasks(q, &asana.Options{
Limit: 100,
Fields: []string{
"assignee",
"name",
"num_subtasks",
"due_on",
"completed",
},
})
if err != nil {
return nil, false, fmt.Errorf("error querying tasks: %s", err)
}
if np != nil {
moreTasks = true
}
return tasks, moreTasks, nil
}

View File

@ -1,20 +0,0 @@
package asana
import "github.com/gdamore/tcell"
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.SetKeyboardChar("j", widget.Next, "Select next task")
widget.SetKeyboardChar("k", widget.Prev, "Select previous task")
widget.SetKeyboardChar("q", widget.Unselect, "Unselect task")
widget.SetKeyboardChar("o", widget.openTask, "Open task in browser")
widget.SetKeyboardChar("x", widget.toggleTaskCompletion, "Toggles the task's completion state")
widget.SetKeyboardChar("?", widget.ShowHelp, "Shows help")
widget.SetKeyboardKey(tcell.KeyDown, widget.Next, "Select next task")
widget.SetKeyboardKey(tcell.KeyUp, widget.Prev, "Select previous task")
widget.SetKeyboardKey(tcell.KeyEsc, widget.Unselect, "Unselect task")
widget.SetKeyboardKey(tcell.KeyEnter, widget.openTask, "Open task in browser")
}

View File

@ -1,48 +0,0 @@
package asana
import (
"github.com/olebedev/config"
"github.com/wtfutil/wtf/cfg"
"github.com/wtfutil/wtf/utils"
)
const (
defaultFocusable = true
defaultTitle = "Asana"
)
type Settings struct {
*cfg.Common
projectId string `help:"The Asana Project ID. If the mode is 'project' or 'project_sections' this is required to known which Asana Project to pull your tasks from" values:"A valid Asana Project ID string" optional:"true"`
workspaceId string `help:"The Asana Workspace ID. If mode is 'workspace' this is required" values:"A valid Asana Workspace ID string" optional:"true"`
sections []string `help:"The Asana Section Labels to fetch from the Project. Required if the mode is 'project_sections'" values:"An array of Asana Section Label strings" optional:"true"`
allUsers bool `help:"Fetch tasks for all users, defaults to false" values:"bool" optional:"true"`
mode string `help:"What mode to query Asana, 'project', 'project_sections', 'workspace'" values:"A string with either 'project', 'project_sections' or 'workspace'"`
hideComplete bool `help:"Hide completed tasks, defaults to false" values:"bool" optional:"true"`
apiKey string `help:"Your Asana Personal Access Token. Leave this blank to use the WTF_ASANA_TOKEN environment variable." values:"Your Asana Personal Access Token as a string" optional:"true"`
token string
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig,
globalConfig),
projectId: ymlConfig.UString("projectId", ""),
apiKey: ymlConfig.UString("apiKey", ""),
workspaceId: ymlConfig.UString("workspaceId", ""),
sections: utils.ToStrs(ymlConfig.UList("sections")),
allUsers: ymlConfig.UBool("allUsers", false),
mode: ymlConfig.UString("mode", ""),
hideComplete: ymlConfig.UBool("hideComplete", false),
}
return &settings
}

View File

@ -1,259 +0,0 @@
package asana
import (
"fmt"
"os"
"strings"
"sync"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/utils"
"github.com/wtfutil/wtf/view"
)
type TaskType int
const (
TASK_TYPE TaskType = iota
TASK_SECTION
TASK_BREAK
)
type TaskItem struct {
name string
numSubtasks int32
dueOn string
id string
url string
taskType TaskType
completed bool
assignee string
}
type Widget struct {
view.ScrollableWidget
tasks []*TaskItem
mu sync.Mutex
err error
settings *Settings
tviewApp *tview.Application
}
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := &Widget{
ScrollableWidget: view.NewScrollableWidget(tviewApp, pages, settings.Common),
tviewApp: tviewApp,
settings: settings,
}
widget.SetRenderFunction(widget.Render)
widget.initializeKeyboardControls()
return widget
}
/* -------------------- Exported Functions -------------------- */
func (widget *Widget) Refresh() {
widget.tasks = nil
widget.err = nil
widget.SetItemCount(0)
widget.mu.Lock()
defer widget.mu.Unlock()
tasks, err := widget.Fetch(
widget.settings.workspaceId,
widget.settings.projectId,
widget.settings.mode,
widget.settings.sections,
widget.settings.allUsers,
)
if err != nil {
widget.err = err
} else {
widget.tasks = tasks
widget.SetItemCount(len(tasks))
}
widget.Render()
}
func (widget *Widget) Render() {
widget.Redraw(widget.content)
}
func (widget *Widget) Fetch(workspaceId, projectId, mode string, sections []string, allUsers bool) ([]*TaskItem, error) {
availableModes := map[string]interface{}{
"project": nil,
"project_sections": nil,
"workspace": nil,
}
if _, ok := availableModes[mode]; !ok {
return nil, fmt.Errorf("missing mode, or mode is invalid - please set to project, project_sections or workspace")
}
if widget.settings.apiKey != "" {
widget.settings.token = widget.settings.apiKey
} else {
widget.settings.token = os.Getenv("WTF_ASANA_TOKEN")
}
if widget.settings.token == "" {
return nil, fmt.Errorf("missing environment variable token or apikey config")
}
subMode := mode
if allUsers && mode != "workspace" {
subMode += "_all"
}
if projectId == "" && strings.HasPrefix(subMode, "project") {
return nil, fmt.Errorf("missing project id")
}
if workspaceId == "" && subMode == "workspace" {
return nil, fmt.Errorf("missing workspace id")
}
var tasks []*TaskItem
var err error
switch {
case strings.HasPrefix(subMode, "project_sections"):
tasks, err = fetchTasksFromProjectSections(widget.settings.token, projectId, sections, subMode)
case strings.HasPrefix(subMode, "project"):
tasks, err = fetchTasksFromProject(widget.settings.token, projectId, subMode)
case subMode == "workspace":
tasks, err = fetchTasksFromWorkspace(widget.settings.token, workspaceId, subMode)
default:
err = fmt.Errorf("no mode found")
}
if err != nil {
return nil, err
}
return tasks, nil
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) content() (string, string, bool) {
title := widget.CommonSettings().Title
if widget.err != nil {
return title, widget.err.Error(), true
}
data := widget.tasks
if len(data) == 0 {
return title, "No data", false
}
var str string
for idx, taskItem := range data {
switch {
case taskItem.taskType == TASK_TYPE:
if widget.settings.hideComplete && taskItem.completed {
continue
}
rowColor := widget.RowColor(idx)
completed := "[ []"
if taskItem.completed {
completed = "[x[]"
}
row := ""
if widget.settings.allUsers && taskItem.assignee != "" {
row = fmt.Sprintf(
"[%s] %s %s: %s",
rowColor,
completed,
taskItem.assignee,
taskItem.name,
)
} else {
row = fmt.Sprintf(
"[%s] %s %s",
rowColor,
completed,
taskItem.name,
)
}
if taskItem.numSubtasks > 0 {
row += fmt.Sprintf(" (%d)", taskItem.numSubtasks)
}
if taskItem.dueOn != "" {
row += fmt.Sprintf(" due: %s", taskItem.dueOn)
}
row += " [white]"
str += utils.HighlightableHelper(widget.View, row, idx, len(taskItem.name))
case taskItem.taskType == TASK_SECTION:
if idx > 1 {
row := "[white] "
str += utils.HighlightableHelper(widget.View, row, idx, len(taskItem.name))
}
row := fmt.Sprintf(
"[white] %s [white]",
taskItem.name,
)
str += utils.HighlightableHelper(widget.View, row, idx, len(taskItem.name))
row = "[white] "
str += utils.HighlightableHelper(widget.View, row, idx, len(taskItem.name))
}
}
return title, str, false
}
func (widget *Widget) openTask() {
sel := widget.GetSelected()
if sel >= 0 && widget.tasks != nil && sel < len(widget.tasks) {
task := widget.tasks[sel]
if task.taskType == TASK_TYPE && task.url != "" {
utils.OpenFile(task.url)
}
}
}
func (widget *Widget) toggleTaskCompletion() {
sel := widget.GetSelected()
if sel >= 0 && widget.tasks != nil && sel < len(widget.tasks) {
task := widget.tasks[sel]
if task.taskType == TASK_TYPE {
widget.mu.Lock()
err := toggleTaskCompletionById(widget.settings.token, task.id)
if err != nil {
widget.err = err
}
widget.mu.Unlock()
widget.Refresh()
}
}
}

View File

@ -14,7 +14,7 @@ const (
// Settings defines the configuration options for this module
type Settings struct {
*cfg.Common
common *cfg.Common
apiToken string `help:"Your Azure DevOps Access Token."`
labelColor string
@ -26,7 +26,7 @@ type Settings struct {
// NewSettingsFromYAML creates and returns an instance of Settings with configuration options populated
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocus, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocus, ymlConfig, globalConfig),
apiToken: ymlConfig.UString("apiToken", os.Getenv("WTF_AZURE_DEVOPS_API_TOKEN")),
labelColor: ymlConfig.UString("labelColor", "white"),
@ -35,8 +35,5 @@ func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *co
projectName: ymlConfig.UString("projectName", os.Getenv("WTF_AZURE_DEVOPS_PROJECT_NAME")),
}
cfg.ModuleSecret(name, globalConfig, &settings.apiToken).
Service(settings.orgURL).Load()
return &settings
}

View File

@ -19,9 +19,9 @@ type Widget struct {
ctx context.Context
}
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, pages, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}

View File

@ -13,7 +13,7 @@ const (
)
type Settings struct {
*cfg.Common
common *cfg.Common
apiKey string `help:"Your BambooHR API token."`
subdomain string `help:"Your BambooHR API subdomain name."`
@ -21,13 +21,11 @@ type Settings struct {
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
apiKey: ymlConfig.UString("apiKey", ymlConfig.UString("apikey", os.Getenv("WTF_BAMBOO_HR_TOKEN"))),
subdomain: ymlConfig.UString("subdomain", os.Getenv("WTF_BAMBOO_HR_SUBDOMAIN")),
}
cfg.ModuleSecret(name, globalConfig, &settings.apiKey).Load()
return &settings
}

View File

@ -19,9 +19,9 @@ type Widget struct {
items []Item
}
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}

View File

@ -11,12 +11,12 @@ const (
)
type Settings struct {
*cfg.Common
common *cfg.Common
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
}
return &settings

View File

@ -17,15 +17,15 @@ import (
type Widget struct {
view.BarGraph
tviewApp *tview.Application
app *tview.Application
}
// NewWidget Make new instance of widget
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
BarGraph: view.NewBarGraph(tviewApp, "Sample Bar Graph", settings.Common),
BarGraph: view.NewBarGraph(app, "Sample Bar Graph", settings.common),
tviewApp: tviewApp,
app: app,
}
widget.View.SetWrap(true)
@ -69,7 +69,7 @@ func (widget *Widget) Refresh() {
widget.View.Clear()
widget.tviewApp.QueueUpdateDraw(func() {
widget.app.QueueUpdateDraw(func() {
display(widget)
})

View File

@ -57,8 +57,6 @@ func (widget *Widget) recentBuilds(pipeline PipelineSettings) ([]Build, error) {
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf(resp.Status)
}

View File

@ -1,6 +1,5 @@
package buildkite
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
}

View File

@ -21,8 +21,7 @@ type PipelineSettings struct {
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
apiKey string `help:"Your Buildkite API Token"`
orgSlug string `help:"Organization Slug"`
pipelines []PipelineSettings `help:"An array of pipelines to get data from"`
@ -31,15 +30,12 @@ type Settings struct {
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
apiKey: ymlConfig.UString("apiKey", os.Getenv("WTF_BUILDKITE_TOKEN")),
orgSlug: ymlConfig.UString("organizationSlug"),
pipelines: buildPipelineSettings(ymlConfig),
}
cfg.ModuleSecret(name, globalConfig, &settings.apiKey).Load()
return &settings
}

View File

@ -7,7 +7,12 @@ import (
"github.com/wtfutil/wtf/view"
)
const HelpText = `
Keyboard commands for Buildkite:
`
type Widget struct {
view.KeyboardWidget
view.TextWidget
settings *Settings
@ -15,14 +20,17 @@ type Widget struct {
err error
}
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, pages, settings.Common),
settings: settings,
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}
widget.initializeKeyboardControls()
widget.View.SetInputCapture(widget.InputCapture)
widget.View.SetScrollable(true)
widget.KeyboardWidget.SetView(widget.View)
return &widget
}

View File

@ -25,7 +25,7 @@ func (widget *Widget) content() (string, string, bool) {
}
_, _, width, _ := widget.View.GetRect()
str := widget.settings.PaginationMarker(len(widget.workflows), widget.Idx, width) + "\n"
str := widget.settings.common.SigilStr(len(widget.workflows), widget.Idx, width) + "\n"
title := fmt.Sprintf("%s - %s", widget.CommonSettings().Title, widget.title(workflow))
str += widget.displayWorkflowRuns(workflow)
@ -36,7 +36,7 @@ func (widget *Widget) content() (string, string, bool) {
func (widget *Widget) title(workflow *sdk.Workflow) string {
return fmt.Sprintf(
"[%s]%s/%s[white]",
widget.settings.Colors.TextTheme.Title,
widget.settings.common.Colors.TextTheme.Title,
workflow.ProjectKey, workflow.Name,
)
}

View File

@ -5,8 +5,7 @@ import (
)
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("j", widget.Next, "Select next workflow")
widget.SetKeyboardChar("k", widget.Prev, "Select previous workflow")

View File

@ -15,8 +15,7 @@ const (
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
token string `help:"Your CDS API token."`
apiURL string `help:"Your CDS API URL."`
uiURL string
@ -26,14 +25,10 @@ type Settings struct {
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
token: ymlConfig.UString("token", ymlConfig.UString("token", os.Getenv("CDS_TOKEN"))),
apiURL: ymlConfig.UString("apiURL", os.Getenv("CDS_API_URL")),
hideTags: utils.ToStrs(ymlConfig.UList("hideTags")),
}
settings.SetDocumentationPath("cds/favorites")
return &settings
}

View File

@ -14,6 +14,7 @@ import (
// Widget define wtf widget to register widget later
type Widget struct {
view.MultiSourceWidget
view.KeyboardWidget
view.TextWidget
workflows []sdk.Workflow
@ -27,19 +28,22 @@ type Widget struct {
}
// NewWidget creates a new instance of the widget
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
MultiSourceWidget: view.NewMultiSourceWidget(settings.Common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(tviewApp, pages, settings.Common),
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
MultiSourceWidget: view.NewMultiSourceWidget(settings.common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}
widget.initializeKeyboardControls()
widget.View.SetRegions(true)
widget.View.SetInputCapture(widget.InputCapture)
widget.SetDisplayFunction(widget.display)
widget.Unselect()
widget.KeyboardWidget.SetView(widget.View)
widget.client = cdsclient.New(cdsclient.Config{
Host: settings.apiURL,
@ -106,6 +110,11 @@ func (widget *Widget) Refresh() {
widget.display()
}
// HelpText displays the widgets controls
func (widget *Widget) HelpText() string {
return widget.KeyboardWidget.HelpText()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) buildWorkflowsCollection() []sdk.Workflow {

View File

@ -23,7 +23,7 @@ func (widget *Widget) content() (string, string, bool) {
filter := widget.currentFilter()
_, _, width, _ := widget.View.GetRect()
str := widget.settings.PaginationMarker(len(widget.filters), widget.Idx, width) + "\n"
str := widget.settings.common.SigilStr(len(widget.filters), widget.Idx, width) + "\n"
str += widget.displayQueue(filter)
title := fmt.Sprintf("%s - %s", widget.CommonSettings().Title, widget.title(filter))
@ -34,7 +34,7 @@ func (widget *Widget) content() (string, string, bool) {
func (widget *Widget) title(filter string) string {
return fmt.Sprintf(
"[%s]%d - %s[white]",
widget.settings.Colors.TextTheme.Title,
widget.settings.common.Colors.TextTheme.Title,
widget.maxItems,
filter,
)
@ -73,12 +73,11 @@ func (widget *Widget) generateQueueJobLine(id int64, parameters []sdk.Parameter,
row[2] = pad(run, 7)
row[3] = pad(prj+"/"+workflow+"/"+node, 40)
switch {
case status == sdk.StatusBuilding:
if status == sdk.StatusBuilding {
row[1] = pad(fmt.Sprintf(" %s.%s ", executedJob.WorkerName, executedJob.WorkerID), 27)
case bookedBy.ID != 0:
} else if bookedBy.ID != 0 {
row[1] = pad(fmt.Sprintf(" %s.%d ", bookedBy.Name, bookedBy.ID), 27)
default:
} else {
row[1] = pad("", 27)
}

View File

@ -5,8 +5,7 @@ import (
)
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("j", widget.Next, "Select next workflow")
widget.SetKeyboardChar("k", widget.Prev, "Select previous workflow")

View File

@ -14,8 +14,7 @@ const (
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
token string `help:"Your CDS API token."`
apiURL string `help:"Your CDS API URL."`
uiURL string
@ -24,13 +23,9 @@ type Settings struct {
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
token: ymlConfig.UString("token", ymlConfig.UString("token", os.Getenv("CDS_TOKEN"))),
apiURL: ymlConfig.UString("apiURL", os.Getenv("CDS_API_URL")),
}
settings.SetDocumentationPath("cds/queue")
return &settings
}

View File

@ -14,6 +14,7 @@ import (
// Widget define wtf widget to register widget later
type Widget struct {
view.MultiSourceWidget
view.KeyboardWidget
view.TextWidget
filters []string
@ -27,21 +28,25 @@ type Widget struct {
}
// NewWidget creates a new instance of the widget
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
MultiSourceWidget: view.NewMultiSourceWidget(settings.Common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(tviewApp, pages, settings.Common),
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
MultiSourceWidget: view.NewMultiSourceWidget(settings.common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}
widget.initializeKeyboardControls()
widget.View.SetRegions(true)
widget.View.SetInputCapture(widget.InputCapture)
widget.SetDisplayFunction(widget.display)
widget.Unselect()
widget.filters = []string{sdk.StatusWaiting, sdk.StatusBuilding}
widget.KeyboardWidget.SetView(widget.View)
widget.client = cdsclient.New(cdsclient.Config{
Host: settings.apiURL,
BuitinConsumerAuthenticationToken: settings.token,
@ -106,6 +111,11 @@ func (widget *Widget) Refresh() {
widget.display()
}
// HelpText displays the widgets controls
func (widget *Widget) HelpText() string {
return widget.KeyboardWidget.HelpText()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) currentFilter() string {

View File

@ -43,18 +43,17 @@ func (widget *Widget) displayStatus() string {
)
for _, line := range status.Lines {
switch {
case line.Status == sdk.MonitoringStatusWarn && strings.Contains(line.Component, "Global"):
if line.Status == sdk.MonitoringStatusWarn && strings.Contains(line.Component, "Global") {
globalWarn = append(globalWarn, line.String())
case line.Status != sdk.MonitoringStatusOK && strings.Contains(line.Component, "Global"):
} else if line.Status != sdk.MonitoringStatusOK && strings.Contains(line.Component, "Global") {
globalRed = append(globalRed, line.String())
case strings.Contains(line.Component, "Global"):
} else if strings.Contains(line.Component, "Global") {
global = append(global, line.String())
case line.Status == sdk.MonitoringStatusWarn:
} else if line.Status == sdk.MonitoringStatusWarn {
warn = append(warn, line.String())
case line.Status == sdk.MonitoringStatusOK:
} else if line.Status == sdk.MonitoringStatusOK {
ok = append(ok, line.String())
default:
} else {
red = append(red, line.String())
}
}

View File

@ -5,8 +5,7 @@ import (
)
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("j", widget.Next, "Select next line")
widget.SetKeyboardChar("k", widget.Prev, "Select previous line")

View File

@ -14,8 +14,7 @@ const (
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
token string `help:"Your CDS API token."`
apiURL string `help:"Your CDS API URL."`
uiURL string
@ -24,13 +23,9 @@ type Settings struct {
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
token: ymlConfig.UString("token", ymlConfig.UString("token", os.Getenv("CDS_TOKEN"))),
apiURL: ymlConfig.UString("apiURL", os.Getenv("CDS_API_URL")),
}
settings.SetDocumentationPath("cds/status")
return &settings
}

View File

@ -14,6 +14,7 @@ import (
// Widget define wtf widget to register widget later
type Widget struct {
view.MultiSourceWidget
view.KeyboardWidget
view.TextWidget
filters []string
@ -27,21 +28,25 @@ type Widget struct {
}
// NewWidget creates a new instance of the widget
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
MultiSourceWidget: view.NewMultiSourceWidget(settings.Common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(tviewApp, pages, settings.Common),
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
MultiSourceWidget: view.NewMultiSourceWidget(settings.common, "workflow", "workflows"),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
}
widget.initializeKeyboardControls()
widget.View.SetRegions(true)
widget.View.SetInputCapture(widget.InputCapture)
widget.SetDisplayFunction(widget.display)
widget.Unselect()
widget.filters = []string{sdk.StatusWaiting, sdk.StatusBuilding}
widget.KeyboardWidget.SetView(widget.View)
widget.client = cdsclient.New(cdsclient.Config{
Host: settings.apiURL,
BuitinConsumerAuthenticationToken: settings.token,
@ -106,6 +111,11 @@ func (widget *Widget) Refresh() {
widget.display()
}
// HelpText displays the widgets controls
func (widget *Widget) HelpText() string {
return widget.KeyboardWidget.HelpText()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) openWorkflow() {

View File

@ -1,9 +1,7 @@
package circleci
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
@ -30,7 +28,7 @@ func (client *Client) BuildsFor() ([]*Build, error) {
return builds, err
}
err = utils.ParseJSON(&builds, bytes.NewReader(resp))
err = utils.ParseJSON(&builds, resp.Body)
if err != nil {
return builds, err
}
@ -44,7 +42,7 @@ var (
circleAPIURL = &url.URL{Scheme: "https", Host: "circleci.com", Path: "/api/v1/"}
)
func (client *Client) circleRequest(path string) ([]byte, error) {
func (client *Client) circleRequest(path string) (*http.Response, error) {
params := url.Values{}
params.Add("circle-token", client.apiKey)
@ -63,15 +61,9 @@ func (client *Client) circleRequest(path string) ([]byte, error) {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf(resp.Status)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
return resp, nil
}

View File

@ -13,22 +13,18 @@ const (
)
type Settings struct {
*cfg.Common
common *cfg.Common
apiKey string `help:"Your CircleCI API token."`
numberOfBuilds int `help:"The number of build, 10 by default"`
apiKey string `help:"Your CircleCI API token."`
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
apiKey: ymlConfig.UString("apiKey", ymlConfig.UString("apikey", os.Getenv("WTF_CIRCLE_API_KEY"))),
numberOfBuilds: ymlConfig.UInt("numberOfBuilds", 10),
apiKey: ymlConfig.UString("apiKey", ymlConfig.UString("apikey", os.Getenv("WTF_CIRCLE_API_KEY"))),
}
cfg.ModuleSecret(name, globalConfig, &settings.apiKey).Load()
return &settings
}

View File

@ -14,9 +14,9 @@ type Widget struct {
settings *Settings
}
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
Client: NewClient(settings.apiKey),
settings: settings,
@ -48,7 +48,7 @@ func (widget *Widget) content() (string, string, bool) {
str = err.Error()
} else {
for idx, build := range builds {
if idx > widget.settings.numberOfBuilds {
if idx > 10 {
break
}

View File

@ -1,7 +1,6 @@
package clocks
import (
"strings"
"time"
)
@ -19,14 +18,6 @@ func NewClock(label string, timeLoc *time.Location) Clock {
return clock
}
func BuildClock(label string, location string) (clock Clock, err error) {
timeLoc, err := time.LoadLocation(sanitizeLocation(location))
if err != nil {
return Clock{}, err
}
return NewClock(label, timeLoc), nil
}
func (clock *Clock) Date(dateFormat string) string {
return clock.LocalTime().Format(dateFormat)
}
@ -42,7 +33,3 @@ func (clock *Clock) ToLocal(t time.Time) time.Time {
func (clock *Clock) Time(timeFormat string) string {
return clock.LocalTime().Format(timeFormat)
}
func sanitizeLocation(locStr string) string {
return strings.Replace(locStr, " ", "_", -1)
}

View File

@ -10,9 +10,7 @@ type ClockCollection struct {
}
func (clocks *ClockCollection) Sorted(sortOrder string) []Clock {
if sortOrder == "natural" {
//no-op
} else if sortOrder == "chronological" {
if sortOrder == "chronological" {
clocks.SortedChronologically()
} else {
clocks.SortedAlphabetically()

View File

@ -1,13 +1,15 @@
package clocks
import "fmt"
import (
"fmt"
)
func (widget *Widget) display(clocks []Clock, dateFormat string, timeFormat string) {
str := ""
if len(clocks) == 0 {
str = fmt.Sprintf("\n%s", " no timezone data available")
} else {
for idx, clock := range clocks {
str += fmt.Sprintf(
" [%s]%-12s %-10s %7s[white]\n",

View File

@ -13,55 +13,24 @@ const (
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
dateFormat string `help:"The format of the date string for all clocks." values:"Any valid Go date layout which is handled by Time.Format. Defaults to Jan 2."`
timeFormat string `help:"The format of the time string for all clocks." values:"Any valid Go time layout which is handled by Time.Format. Defaults to 15:04 MST."`
locations []Clock `help:"Defines the timezones for the world clocks that you want to display. key is a unique label that will be displayed in the UI. value is a timezone name." values:"Any TZ database timezone."`
sort string `help:"Defines the display order of the clocks in the widget." values:"'alphabetical', 'chronological', or 'natural. 'alphabetical' will sort in ascending order by key, 'chronological' will sort in ascending order by date/time, 'natural' will keep ordering as per the config."`
dateFormat string `help:"The format of the date string for all clocks." values:"Any valid Go date layout which is handled by Time.Format. Defaults to Jan 2."`
timeFormat string `help:"The format of the time string for all clocks." values:"Any valid Go time layout which is handled by Time.Format. Defaults to 15:04 MST."`
locations map[string]interface{} `help:"Defines the timezones for the world clocks that you want to display. key is a unique label that will be displayed in the UI. value is a timezone name." values:"Any TZ database timezone."`
sort string `help:"Defines the display order of the clocks in the widget." values:"'alphabetical' or 'chronological'. 'alphabetical' will sort in acending order by key, 'chronological' will sort in ascending order by date/time."`
}
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
dateFormat: ymlConfig.UString("dateFormat", utils.SimpleDateFormat),
timeFormat: ymlConfig.UString("timeFormat", utils.SimpleTimeFormat),
locations: buildLocations(ymlConfig),
locations: ymlConfig.UMap("locations"),
sort: ymlConfig.UString("sort"),
}
return &settings
}
func buildLocations(ymlConfig *config.Config) []Clock {
clocks := []Clock{}
locations, err := ymlConfig.Map("locations")
if err == nil {
for k, v := range locations {
name := k
zone := v.(string)
clock, err := BuildClock(name, zone)
if err == nil {
clocks = append(clocks, clock)
}
}
return clocks
}
listLocations := ymlConfig.UList("locations")
for _, location := range listLocations {
if location, ok := location.(map[string]interface{}); ok {
for k, v := range location {
name := k
zone := v.(string)
clock, err := BuildClock(name, zone)
if err == nil {
clocks = append(clocks, clock)
}
}
}
}
return clocks
}

View File

@ -1,6 +1,9 @@
package clocks
import (
"strings"
"time"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
)
@ -8,22 +11,24 @@ import (
type Widget struct {
view.TextWidget
app *tview.Application
clockColl ClockCollection
dateFormat string
timeFormat string
settings *Settings
}
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
app: app,
settings: settings,
dateFormat: settings.dateFormat,
timeFormat: settings.timeFormat,
}
widget.clockColl = widget.buildClockCollection()
widget.clockColl = widget.buildClockCollection(settings.locations)
return &widget
}
@ -32,16 +37,29 @@ func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
// Refresh updates the onscreen contents of the widget
func (widget *Widget) Refresh() {
sortedClocks := widget.clockColl.Sorted(widget.settings.sort)
widget.display(sortedClocks, widget.dateFormat, widget.timeFormat)
widget.app.QueueUpdateDraw(func() {
sortedClocks := widget.clockColl.Sorted(widget.settings.sort)
widget.display(sortedClocks, widget.dateFormat, widget.timeFormat)
})
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) buildClockCollection() ClockCollection {
func (widget *Widget) buildClockCollection(locData map[string]interface{}) ClockCollection {
clockColl := ClockCollection{}
clockColl.Clocks = widget.settings.locations
for label, locStr := range locData {
timeLoc, err := time.LoadLocation(widget.sanitizeLocation(locStr.(string)))
if err != nil {
continue
}
clockColl.Clocks = append(clockColl.Clocks, NewClock(label, timeLoc))
}
return clockColl
}
func (widget *Widget) sanitizeLocation(locStr string) string {
return strings.Replace(locStr, " ", "_", -1)
}

View File

@ -13,12 +13,11 @@ const (
// Settings for the cmdrunner widget
type Settings struct {
*cfg.Common
common *cfg.Common
args []string `help:"The arguments to the command, with each item as an element in an array. Example: for curl -I cisco.com, the arguments array would be ['-I', 'cisco.com']."`
cmd string `help:"The terminal command to be run, withouth the arguments. Ie: ping, whoami, curl."`
tail bool `help:"Automatically scroll to the end of the command output."`
pty bool `help:"Run the command in a pseudo-terminal. Some apps will behave differently if they feel in a terminal. For example, some apps will produce colorized output in a terminal, and non-colorized output otherwise. Default false" optional:"true"`
maxLines int `help:"Maximum number of lines kept in the buffer."`
// The dimensions of the module
@ -29,11 +28,10 @@ type Settings struct {
// NewSettingsFromYAML loads the cmdrunner portion of the WTF config
func NewSettingsFromYAML(name string, moduleConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, moduleConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, moduleConfig, globalConfig),
args: utils.ToStrs(moduleConfig.UList("args")),
cmd: moduleConfig.UString("cmd"),
pty: moduleConfig.UBool("pty", false),
tail: moduleConfig.UBool("tail", false),
maxLines: moduleConfig.UInt("maxLines", 256),
}

View File

@ -3,13 +3,11 @@ package cmdrunner
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strings"
"sync"
"github.com/creack/pty"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
)
@ -27,9 +25,9 @@ type Widget struct {
}
// NewWidget creates a new instance of the widget
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
buffer: &bytes.Buffer{},
@ -123,45 +121,23 @@ func runCommandLoop(widget *Widget) {
<-widget.runChan
widget.resetBuffer()
cmd := exec.Command(widget.settings.cmd, widget.settings.args...)
cmd.Stdout = widget
cmd.Env = widget.environment()
var err error
if widget.settings.pty {
err = runCommandPty(widget, cmd)
} else {
err = runCommand(widget, cmd)
}
err := cmd.Run()
// The command has exited, print any error messages
if err != nil {
widget.handleError(err)
widget.m.Lock()
_, writeErr := widget.buffer.WriteString(err.Error())
if writeErr != nil {
return
}
widget.m.Unlock()
}
widget.redrawChan <- true
}
}
func runCommand(widget *Widget, cmd *exec.Cmd) error {
cmd.Stdout = widget
return cmd.Run()
}
func runCommandPty(widget *Widget, cmd *exec.Cmd) error {
f, err := pty.Start(cmd)
// The command has exited, print any error messages
if err != nil {
return err
}
_, err = io.Copy(widget.buffer, f)
return err
}
func (widget *Widget) handleError(err error) {
widget.m.Lock()
defer widget.m.Unlock()
_, writeErr := widget.buffer.WriteString(err.Error())
if writeErr != nil {
return
}
}
func redrawLoop(widget *Widget) {
for {
widget.Redraw(widget.content)

View File

@ -1,14 +0,0 @@
package covid
// Cases holds the latest cases
type Cases struct {
Latest Latest `json:"latest"`
}
// Latest holds the number of global confirmed cases and deaths due to Covid
type Latest struct {
Confirmed int `json:"confirmed"`
Deaths int `json:"deaths"`
// Not currently used but holds information about the country
Locations []interface{} `json:"locations,omitempty"`
}

View File

@ -1,24 +0,0 @@
package covid
import (
"encoding/json"
"testing"
)
func Test_CasesInclude(t *testing.T) {
// The api does not seem to return the correct recovered numbers
responseBody := `{"latest":{"confirmed":3093619,"deaths":73018,"recovered":0},"locations":[]}`
latestData := Cases{}
_ = json.Unmarshal([]byte(responseBody), &latestData)
expectedConfirmed := 3093619
expectedDeaths := 73018
actualConfirmed := latestData.Latest.Confirmed
actualDeaths := latestData.Latest.Deaths
if expectedConfirmed != actualConfirmed {
t.Errorf("\nexpected: %v\n got: %v", expectedConfirmed, actualConfirmed)
}
if expectedDeaths != actualDeaths {
t.Errorf("\nexpected: %v\n got: %v", expectedDeaths, actualDeaths)
}
}

View File

@ -1,58 +0,0 @@
package covid
import (
"fmt"
"net/http"
"github.com/wtfutil/wtf/utils"
)
const covidTrackerAPIURL = "https://coronavirus-tracker-api.herokuapp.com/v2/"
// LatestCases queries the /latest endpoint, does not take any query parameters
func LatestCases() (*Cases, error) {
latestURL := covidTrackerAPIURL + "latest"
resp, err := http.Get(latestURL)
if resp.StatusCode != 200 {
return nil, fmt.Errorf(resp.Status)
}
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
var latestGlobalCases Cases
err = utils.ParseJSON(&latestGlobalCases, resp.Body)
if err != nil {
return nil, err
}
return &latestGlobalCases, nil
}
// LatestCountryCases queries the /locations endpoint, takes a query parameter: the country code
func (widget *Widget) LatestCountryCases(countries []interface{}) ([]*Cases, error) {
countriesCovidData := []*Cases{}
for _, name := range countries {
countryURL := covidTrackerAPIURL + "locations?source=jhu&country_code=" + name.(string)
resp, err := http.Get(countryURL)
if resp.StatusCode != 200 {
return nil, fmt.Errorf(resp.Status)
}
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
var latestCountryCases Cases
err = utils.ParseJSON(&latestCountryCases, resp.Body)
if err != nil {
return nil, err
}
// add stats for each country to the slice
countriesCovidData = append(countriesCovidData, &latestCountryCases)
}
return countriesCovidData, nil
}

View File

@ -1,31 +0,0 @@
package covid
import (
"github.com/olebedev/config"
"github.com/wtfutil/wtf/cfg"
)
const (
defaultFocusable = false
defaultTitle = "Covid tracker"
)
// Settings is the struct for this module's settings
type Settings struct {
*cfg.Common
countries []interface{} `help:"Countries (codes) from which to retrieve stats."`
}
// NewSettingsFromYAML returns the settings from the config yaml file
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
// List of countries to retrieve stats from
countries: ymlConfig.UList("countries"),
}
return &settings
}

View File

@ -1,86 +0,0 @@
package covid
import (
"fmt"
"github.com/rivo/tview"
"github.com/wtfutil/wtf/view"
)
// Widget is the struct that defines this module widget
type Widget struct {
view.TextWidget
settings *Settings
err error
}
// NewWidget creates a new widget for this module
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := &Widget{
TextWidget: view.NewTextWidget(app, nil, settings.Common),
settings: settings,
}
widget.View.SetScrollable(true)
return widget
}
// Refresh checks if this module widget is disabled
func (widget *Widget) Refresh() {
if widget.Disabled() {
return
}
widget.Redraw(widget.content)
}
// Render renders this module widget
func (widget *Widget) Render() {
widget.Redraw(widget.content)
}
// Display stats based on the user's locale
func (widget *Widget) displayStats(cases int) string {
prntr, err := widget.settings.LocalizedPrinter()
if err != nil {
return err.Error()
}
return prntr.Sprintf("%d", cases)
}
func (widget *Widget) content() (string, string, bool) {
title := defaultTitle
if widget.CommonSettings().Title != "" {
title = widget.CommonSettings().Title
}
cases, err := LatestCases()
var covidStats string
if err != nil {
widget.err = err
} else {
// Display global stats
covidStats = fmt.Sprintf("[%s]Global[white]\n", widget.settings.Colors.Subheading)
covidStats += fmt.Sprintf("%s: %s\n", "Confirmed", widget.displayStats(cases.Latest.Confirmed))
covidStats += fmt.Sprintf("%s: %s\n", "Deaths", widget.displayStats(cases.Latest.Deaths))
}
// Retrieve country stats if country codes are set in the config
if len(widget.settings.countries) > 0 {
countryCases, err := widget.LatestCountryCases(widget.settings.countries)
if err != nil {
widget.err = err
} else {
for i, name := range countryCases {
covidStats += fmt.Sprintf("[%s]Country[white]: %s\n", widget.settings.Colors.Subheading, widget.settings.countries[i])
covidStats += fmt.Sprintf("%s: %s\n", "Confirmed", widget.displayStats(name.Latest.Confirmed))
covidStats += fmt.Sprintf("%s: %s\n", "Deaths", widget.displayStats(name.Latest.Deaths))
}
}
}
return title, covidStats, true
}

View File

@ -32,16 +32,15 @@ type summary struct {
}
type Settings struct {
*cfg.Common
colors
common *cfg.Common
summary
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
}
settings.colors.base.name = ymlConfig.UString("colors.base.name")
@ -63,7 +62,5 @@ func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *co
settings.summary.currencies[key] = currency
}
settings.SetDocumentationPath("cryptocurrencies/bittrex")
return &settings
}

View File

@ -29,9 +29,9 @@ type Widget struct {
}
// NewWidget Make new instance of widget
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
settings: settings,
summaryList: summaryList{},

View File

@ -17,9 +17,8 @@ type colors struct {
}
type Settings struct {
*cfg.Common
colors
common *cfg.Common
deviceToken string
displayHoldings bool
@ -28,13 +27,11 @@ type Settings struct {
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
deviceToken: ymlConfig.UString("device_token"),
displayHoldings: ymlConfig.UBool("displayHoldings", true),
}
settings.SetDocumentationPath("cryptocurrencies/blockfolio")
return &settings
}

View File

@ -18,9 +18,9 @@ type Widget struct {
settings *Settings
}
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
device_token: settings.deviceToken,
settings: settings,

View File

@ -38,16 +38,15 @@ type currency struct {
}
type Settings struct {
*cfg.Common
colors
common *cfg.Common
currencies map[string]*currency
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
}
settings.colors.from.name = ymlConfig.UString("colors.from.name")

View File

@ -129,6 +129,7 @@ func (widget *Widget) updateCurrencies() {
setPrices(&jsonResponse, fromCurrency)
}
}
func makeRequest(currency *fromCurrency) *http.Request {
@ -137,7 +138,7 @@ func makeRequest(currency *fromCurrency) *http.Request {
tsyms += fmt.Sprintf("%s,", to.name)
}
url := fmt.Sprintf("%s?fsym=%s&tsyms=%s", baseURL, currency.name, tsyms)
url := fmt.Sprintf("%s?fsym=%s&tsyms=%s", baseURL, currency.name, "")
request, _ := http.NewRequest("GET", url, nil)
return request

View File

@ -35,9 +35,8 @@ type colors struct {
}
type Settings struct {
*cfg.Common
colors
common *cfg.Common
currencies map[string]interface{}
top map[string]interface{}
@ -51,7 +50,7 @@ func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *co
top, _ := ymlConfig.Map("top")
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
currencies: currencies,
top: top,
@ -73,7 +72,5 @@ func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *co
settings.colors.top.to.field = ymlConfig.UString("colors.top.to.field")
settings.colors.top.to.value = ymlConfig.UString("colors.top.to.value")
settings.SetDocumentationPath("cryptocurrencies/cryptolive")
return &settings
}

View File

@ -39,16 +39,15 @@ type currency struct {
}
type Settings struct {
*cfg.Common
colors
top map[string]*currency
common *cfg.Common
top map[string]*currency
}
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
}
settings.colors.from.name = ymlConfig.UString("colors.from.name")

View File

@ -20,9 +20,9 @@ type Widget struct {
}
// NewWidget Make new instance of widget
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
priceWidget: price.NewWidget(settings.priceSettings),
toplistWidget: toplist.NewWidget(settings.toplistSettings),

View File

@ -5,7 +5,7 @@ import (
datadog "github.com/zorkian/go-datadog-api"
)
// Monitors returns a list of Datadog monitors
// Monitors returns a list of newrelic monitors
func (widget *Widget) Monitors() ([]datadog.Monitor, error) {
client := datadog.NewClient(
widget.settings.apiKey,

View File

@ -5,8 +5,7 @@ import (
)
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("j", widget.Next, "Select next item")
widget.SetKeyboardChar("k", widget.Prev, "Select previous item")

View File

@ -13,7 +13,7 @@ const (
)
type Settings struct {
*cfg.Common
common *cfg.Common
apiKey string `help:"Your Datadog API key."`
applicationKey string `help:"Your Datadog Application key."`
@ -23,15 +23,12 @@ type Settings struct {
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
apiKey: ymlConfig.UString("apiKey", ymlConfig.UString("apikey", os.Getenv("WTF_DATADOG_API_KEY"))),
applicationKey: ymlConfig.UString("applicationKey", os.Getenv("WTF_DATADOG_APPLICATION_KEY")),
tags: ymlConfig.UList("monitors.tags"),
}
cfg.ModuleSecret(name+"-api", globalConfig, &settings.apiKey).Load()
cfg.ModuleSecret(name+"-app", globalConfig, &settings.applicationKey).Load()
return &settings
}

View File

@ -10,6 +10,7 @@ import (
)
type Widget struct {
view.KeyboardWidget
view.ScrollableWidget
monitors []datadog.Monitor
@ -17,15 +18,19 @@ type Widget struct {
err error
}
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
ScrollableWidget: view.NewScrollableWidget(tviewApp, pages, settings.Common),
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
ScrollableWidget: view.NewScrollableWidget(app, settings.common),
settings: settings,
}
widget.SetRenderFunction(widget.Render)
widget.initializeKeyboardControls()
widget.View.SetInputCapture(widget.InputCapture)
widget.KeyboardWidget.SetView(widget.View)
return &widget
}
@ -61,6 +66,10 @@ func (widget *Widget) Render() {
widget.Redraw(widget.content)
}
func (widget *Widget) HelpText() string {
return widget.KeyboardWidget.HelpText()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) content() (string, string, bool) {
@ -78,7 +87,7 @@ func (widget *Widget) content() (string, string, bool) {
" %s\n",
fmt.Sprintf(
"[%s]Triggered Monitors[white]",
widget.settings.Colors.Subheading,
widget.settings.common.Colors.Subheading,
),
)
for idx, triggeredMonitor := range triggeredMonitors {

View File

@ -3,8 +3,7 @@ package devto
import "github.com/gdamore/tcell"
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("d", widget.Next, "Select next item")
widget.SetKeyboardChar("a", widget.Prev, "Select previous item")

View File

@ -13,7 +13,7 @@ const (
// Settings defines the configuration options for this module
type Settings struct {
*cfg.Common
common *cfg.Common
numberOfArticles int `help:"Number of stories to show. Default is 10" optional:"true"`
contentTag string `help:"List articles from a specific tag. Default is empty" optional:"true"`
@ -24,8 +24,7 @@ type Settings struct {
// NewSettingsFromYAML creates and returns an instance of Settings with configuration options populated
func NewSettingsFromYAML(name string, yamlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, yamlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, yamlConfig, globalConfig),
numberOfArticles: yamlConfig.UInt("numberOfArticles", 10),
contentTag: yamlConfig.UString("contentTag", ""),
contentUsername: yamlConfig.UString("contentUsername", ""),

View File

@ -12,16 +12,17 @@ import (
)
type Widget struct {
view.KeyboardWidget
view.ScrollableWidget
articles []devto.ListedArticle
settings *Settings
err error
}
func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
func NewWidget(app *tview.Application, pages *tview.Pages, settings *Settings) *Widget {
widget := &Widget{
ScrollableWidget: view.NewScrollableWidget(tviewApp, pages, settings.Common),
KeyboardWidget: view.NewKeyboardWidget(app, pages, settings.common),
ScrollableWidget: view.NewScrollableWidget(app, settings.common),
settings: settings,
}
@ -29,6 +30,9 @@ func NewWidget(tviewApp *tview.Application, pages *tview.Pages, settings *Settin
widget.SetRenderFunction(widget.Render)
widget.View.SetScrollable(true)
widget.initializeKeyboardControls()
widget.View.SetInputCapture(widget.InputCapture)
widget.KeyboardWidget.SetView(widget.View)
return widget
}

View File

@ -13,7 +13,7 @@ const AM = "A"
const PM = "P"
const minRowsForBorder = 3
// Converts integer to string along with makes sure the length of string is > 2
// Converts integer to string along with makes sure the lenght of string is > 2
func intStrConv(val int) string {
valStr := strconv.Itoa(val)
@ -39,9 +39,9 @@ func getHourMinute(hourFormat string) string {
}
strMinutes := intStrConv(time.Now().Minute())
strMinutes += AMPM
return strHours + getColon() + strMinutes
strMintues := intStrConv(time.Now().Minute())
strMintues = strMintues + AMPM
return strHours + getColon() + strMintues
}
// Returns the : with blinking based on the seconds

View File

@ -3,7 +3,7 @@ package digitalclock
import "strings"
func mergeLines(outString []string) string {
return strings.Join(outString, "\n")
return strings.Join(outString[:], "\n")
}
func renderWidget(widgetSettings Settings) string {

View File

@ -12,7 +12,7 @@ const (
// Settings defines the configuration properties for this module
type Settings struct {
*cfg.Common
common *cfg.Common
color string `help:"The color of the clock."`
font string `help:"The font of the clock." values:"bigfont or digitalfont"`
@ -23,7 +23,7 @@ type Settings struct {
// NewSettingsFromYAML creates a new settings instance from a YAML config block
func NewSettingsFromYAML(name string, ymlConfig *config.Config, globalConfig *config.Config) *Settings {
settings := Settings{
Common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
common: cfg.NewCommonSettingsFromModule(name, defaultTitle, defaultFocusable, ymlConfig, globalConfig),
color: ymlConfig.UString("color"),
font: ymlConfig.UString("font"),

View File

@ -9,14 +9,16 @@ import (
type Widget struct {
view.TextWidget
app *tview.Application
settings *Settings
}
// NewWidget creates a new widget using settings
func NewWidget(tviewApp *tview.Application, settings *Settings) *Widget {
func NewWidget(app *tview.Application, settings *Settings) *Widget {
widget := Widget{
TextWidget: view.NewTextWidget(tviewApp, nil, settings.Common),
TextWidget: view.NewTextWidget(app, settings.common),
app: app,
settings: settings,
}

View File

@ -2,60 +2,33 @@ package digitalocean
import (
"fmt"
"strings"
"github.com/wtfutil/wtf/utils"
)
const maxColWidth = 12
func (widget *Widget) content() (string, string, bool) {
columnSet := widget.settings.columns
title := widget.CommonSettings().Title
if widget.err != nil {
return title, widget.err.Error(), true
}
if len(columnSet) < 1 {
return title, " no columns defined", false
}
str := fmt.Sprintf(" [::b][%s]", widget.settings.Colors.Subheading)
for _, colName := range columnSet {
truncName := utils.Truncate(colName, maxColWidth, false)
str += fmt.Sprintf("%-12s", truncName)
}
str += "\n"
str := fmt.Sprintf(
" [%s]Droplets\n\n",
widget.settings.common.Colors.Subheading,
)
for idx, droplet := range widget.droplets {
// This defines the formatting for the row, one tab-seperated string for each defined column
fmtStr := " [%s]"
dropletName := droplet.Name
for range columnSet {
fmtStr += "%-12s"
}
vals := []interface{}{
row := fmt.Sprintf(
"[%s] %-8s %-24s %s",
widget.RowColor(idx),
}
droplet.Status,
dropletName,
utils.Truncate(strings.Join(droplet.Tags, ","), 24, true),
)
// Dynamically access the droplet to get the requested columns values
for _, colName := range columnSet {
val, err := droplet.StringValueForProperty(colName)
if err != nil {
val = "???"
}
truncVal := utils.Truncate(val, maxColWidth, false)
vals = append(vals, truncVal)
}
// And format, print, and color the row
row := fmt.Sprintf(fmtStr, vals...)
str += utils.HighlightableHelper(widget.View, row, idx, 33)
}

View File

@ -1,80 +0,0 @@
package digitalocean
import (
"fmt"
"reflect"
"strings"
"github.com/digitalocean/godo"
"github.com/wtfutil/wtf/utils"
)
// Droplet represents WTF's view of a DigitalOcean droplet
type Droplet struct {
godo.Droplet
Image Image
Region Region
}
// Image represents WTF's view of a DigitalOcean droplet image
type Image struct {
godo.Image
utils.Reflective
}
// Region represents WTF's view of a DigitalOcean region
type Region struct {
godo.Region
utils.Reflective
}
// NewDroplet creates and returns an instance of Droplet
func NewDroplet(doDroplet godo.Droplet) *Droplet {
droplet := &Droplet{
doDroplet,
Image{
*doDroplet.Image,
utils.Reflective{},
},
Region{
*doDroplet.Region,
utils.Reflective{},
},
}
return droplet
}
/* -------------------- Exported Functions -------------------- */
// StringValueForProperty returns a string value for the given column
func (drop *Droplet) StringValueForProperty(propName string) (string, error) {
var strVal string
var err error
// Figure out if we should forward this property to a sub-object
// Lets us support "Region.Name" column definitions
split := strings.Split(propName, ".")
switch split[0] {
case "Image":
strVal, err = drop.Image.StringValueForProperty(split[1])
case "Region":
strVal, err = drop.Region.StringValueForProperty(split[1])
default:
v := reflect.ValueOf(drop)
refVal := reflect.Indirect(v).FieldByName(propName)
if !refVal.IsValid() {
err = fmt.Errorf("invalid property name: %s", propName)
} else {
strVal = fmt.Sprintf("%v", refVal)
}
}
return strVal, err
}

View File

@ -5,12 +5,13 @@ import (
"strconv"
"strings"
"github.com/digitalocean/godo"
"github.com/wtfutil/wtf/utils"
"github.com/wtfutil/wtf/view"
)
type dropletPropertiesTable struct {
droplet *Droplet
droplet *godo.Droplet
propertyMap map[string]string
colWidth0 int
@ -19,7 +20,7 @@ type dropletPropertiesTable struct {
}
// newDropletPropertiesTable creates and returns an instance of DropletPropertiesTable
func newDropletPropertiesTable(droplet *Droplet) *dropletPropertiesTable {
func newDropletPropertiesTable(droplet *godo.Droplet) *dropletPropertiesTable {
propTable := &dropletPropertiesTable{
droplet: droplet,

View File

@ -3,8 +3,7 @@ package digitalocean
import "github.com/gdamore/tcell"
func (widget *Widget) initializeKeyboardControls() {
widget.InitializeHelpTextKeyboardControl(widget.ShowHelp)
widget.InitializeRefreshKeyboardControl(widget.Refresh)
widget.InitializeCommonControls(widget.Refresh)
widget.SetKeyboardChar("?", widget.showInfo, "Show info about the selected droplet")

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