mirror of
https://codeberg.org/scip/tablizer.git
synced 2025-12-18 21:11:03 +01:00
Compare commits
62 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9dd2a49d9b | |||
| 90872e0c60 | |||
| baac74eb47 | |||
| 360dd28e20 | |||
| 1e36c148ff | |||
| 399620de98 | |||
| 5d10875a3f | |||
| 4481f59eda | |||
| 1b2f51dcaf | |||
| 0d6de3fe5b | |||
| ec23ae2e76 | |||
| 76930ab45a | |||
| a77e4dbc5a | |||
| 9305f48639 | |||
| da276a1b50 | |||
| dfd3ab9b77 | |||
| d53b32b95e | |||
| 3edbd53ef8 | |||
| 9c49b78593 | |||
| ca87c339b0 | |||
| fd74628259 | |||
| 839f33a7fc | |||
| ebd391df63 | |||
| 752406815c | |||
| 4ec6ccd0fd | |||
| aef545d51e | |||
| 3249e1719f | |||
| f830cc6256 | |||
| 7e01d54b08 | |||
| 487ba6253d | |||
| 745d15b459 | |||
| 8e2ba58ddb | |||
| 6eedb60a6a | |||
| 81fac864f1 | |||
| e868b50c0f | |||
| b9ed7d8cb7 | |||
| 6ae4a1b6d9 | |||
| f890596b4c | |||
| 22ee24cfdf | |||
| 34e2b8d855 | |||
| 196833ed3c | |||
| 85277bbf5e | |||
| 26e50cf908 | |||
| 5be18e27c9 | |||
| 2c410e1cb3 | |||
| 1b622284a1 | |||
| 404481c3dc | |||
| 15f437314a | |||
| 3746c7f326 | |||
| b7b638636d | |||
| dd13300c8b | |||
| a59a6cb7d8 | |||
| d7ea0017b7 | |||
| 09dc1f3e60 | |||
| 43dc4ff031 | |||
| 4596d9d589 | |||
|
|
f2acd2c1b1 | ||
| 76f49a532f | |||
| 3fd2e6ac2f | |||
| 65cbaddd5f | |||
| 9f5fc6924e | |||
| 07b65bcff5 |
@@ -1,38 +0,0 @@
|
|||||||
---
|
|
||||||
version: 2.1
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
compile:
|
|
||||||
docker:
|
|
||||||
- image: cimg/go:1.18
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: make
|
|
||||||
|
|
||||||
test:
|
|
||||||
parameters:
|
|
||||||
go_version:
|
|
||||||
type: string
|
|
||||||
run_test:
|
|
||||||
type: boolean
|
|
||||||
default: true
|
|
||||||
docker:
|
|
||||||
- image: cimg/go:<< parameters.go_version >>
|
|
||||||
steps:
|
|
||||||
- checkout
|
|
||||||
- run: make test
|
|
||||||
|
|
||||||
workflows:
|
|
||||||
version: 2
|
|
||||||
unit-test:
|
|
||||||
jobs:
|
|
||||||
- compile
|
|
||||||
- test:
|
|
||||||
name: testing
|
|
||||||
matrix:
|
|
||||||
parameters:
|
|
||||||
go_version:
|
|
||||||
- "1.16"
|
|
||||||
- "1.17"
|
|
||||||
- "1.18"
|
|
||||||
- "1.19"
|
|
||||||
58
.github/workflows/ci.yaml
vendored
Normal file
58
.github/workflows/ci.yaml
vendored
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
name: build-and-test-tablizer
|
||||||
|
on: [push, pull_request]
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
version: [1.17, 1.18, 1.19]
|
||||||
|
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||||
|
name: Build
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
steps:
|
||||||
|
- name: Set up Go 1.18
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: ${{ matrix.version }}
|
||||||
|
id: go
|
||||||
|
|
||||||
|
- name: checkout
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: build
|
||||||
|
run: make
|
||||||
|
|
||||||
|
- name: test
|
||||||
|
run: make test
|
||||||
|
|
||||||
|
golangci:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v3
|
||||||
|
#with:
|
||||||
|
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
|
||||||
|
# version: v1.29
|
||||||
|
|
||||||
|
# Optional: working directory, useful for monorepos
|
||||||
|
# working-directory: somedir
|
||||||
|
|
||||||
|
# Optional: golangci-lint command line arguments.
|
||||||
|
# args: --issues-exit-code=0
|
||||||
|
|
||||||
|
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||||
|
# only-new-issues: true
|
||||||
|
|
||||||
|
# Optional: if set to true then the all caching functionality will be complete disabled,
|
||||||
|
# takes precedence over all other caching options.
|
||||||
|
# skip-cache: true
|
||||||
|
|
||||||
|
# Optional: if set to true then the action don't cache or restore ~/go/pkg.
|
||||||
|
# skip-pkg-cache: true
|
||||||
|
|
||||||
|
# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
|
||||||
|
# skip-build-cache: true
|
||||||
205
CHANGELOG.md
Normal file
205
CHANGELOG.md
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org).
|
||||||
|
|
||||||
|
## [v1.0.11](https://github.com/TLINDEN/tablizer/tree/v1.0.11) - 2022-10-19
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.10...v1.0.11)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added CI job golinter to regularly check for common mistakes.
|
||||||
|
|
||||||
|
- Added YAML output mode.
|
||||||
|
|
||||||
|
- Added more unit tests, we're over 95% in the lib module.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- do not use any global variables anymore, makes the code easier to
|
||||||
|
maintain, understand and test
|
||||||
|
|
||||||
|
- using io.Writer in print* functions, which is easier to test, also
|
||||||
|
re-implemented the print tests.
|
||||||
|
|
||||||
|
- replaced go-str2duration with my own implementation `duration2int()`.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.10](https://github.com/TLINDEN/tablizer/tree/v1.0.10) - 2022-10-15
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.9...v1.0.10)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added various sort modes: sort by time, by duration, numerical (-a -t -i)
|
||||||
|
|
||||||
|
- Added possibility to modify sort order to descending (-D)
|
||||||
|
|
||||||
|
- Added support to specify a regexp in column selector -c, which can
|
||||||
|
also be mixed with numerical column spec
|
||||||
|
|
||||||
|
- More unit tests
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Column specification allowed to specify duplicate columns like `-c
|
||||||
|
1,2,1,2` unchecked. Now this list will be deduplicated before use.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.9](https://github.com/TLINDEN/tablizer/tree/v1.0.9) - 2022-10-14
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.8...v1.0.9)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added Changelog, Contribution guidelines and no COC.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- some minor changes to satisfy linter.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.8](https://github.com/TLINDEN/tablizer/tree/v1.0.8) - 2022-10-13
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.7...v1.0.8)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added sort support with the new parameter -k (like sort(1)).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.7](https://github.com/TLINDEN/tablizer/tree/v1.0.7) - 2022-10-11
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.6...v1.0.7)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added pattern highlighting support.
|
||||||
|
|
||||||
|
- Added more unit tests.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed extended more output in combination with -c.
|
||||||
|
|
||||||
|
- Fixed issue #4, the version string was missing.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.6](https://github.com/TLINDEN/tablizer/tree/v1.0.6) - 2022-10-05
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.5...v1.0.6)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added documentation about regexp syntax in the manpage.
|
||||||
|
|
||||||
|
- Added more unit tests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Rewrote the input parser.
|
||||||
|
|
||||||
|
- Some more refactoring work has been done.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.5](https://github.com/TLINDEN/tablizer/tree/v1.0.5) - 2022-10-05
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.4...v1.0.5)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- A new option has been added: --invert-match -v which behaves like
|
||||||
|
the same option in grep(1): it inverts the pattern match.
|
||||||
|
|
||||||
|
- A few more unit tests have been added.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Pattern matching did not work, because the (new) help subcommand
|
||||||
|
lead to cobra taking care of the first arg to the program
|
||||||
|
(argv[1]). So now there's a new parameter -m which displays the
|
||||||
|
manpage and no more subcommands.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.4](https://github.com/TLINDEN/tablizer/tree/v1.0.4) - 2022-10-04
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.3...v1.0.4)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Development version of the compiled binary now uses git vars
|
||||||
|
in addition to program version.
|
||||||
|
|
||||||
|
- Added an option to display the manual page (compiled in) as text:
|
||||||
|
--help, for cases where a user just installed the binary.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Fixed go module namespace.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.3](https://github.com/TLINDEN/tablizer/tree/v1.0.3) - 2022-10-03
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.2...v1.0.3)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added a new output mode: shell mode, which allows the user
|
||||||
|
to use the output in a shell eval loop to further process
|
||||||
|
the data.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- More refactoring work has been done.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.2](https://github.com/TLINDEN/tablizer/tree/v1.0.2) - 2022-10-02
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.1...v1.0.2)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added some basic unit tests.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Code has been refactored to be more efficient.
|
||||||
|
|
||||||
|
- Replaced table generation code with Tablewriter.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.1](https://github.com/TLINDEN/tablizer/tree/v1.0.1) - 2022-09-30
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/v1.0.0...v1.0.1)
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Added a unix manual page.
|
||||||
|
|
||||||
|
- Added release builder to Makefile
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Various minor fixes.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [v1.0.0](https://github.com/TLINDEN/tablizer/tree/v1.0.0) - 2022-09-28
|
||||||
|
|
||||||
|
[Full Changelog](https://github.com/TLINDEN/tablizer/compare/02a64a5c3fe4220df2c791ff1421d16ebd428c19...v1.0.0)
|
||||||
|
|
||||||
|
Initial release.
|
||||||
113
CODE_OF_CONDUCT.md
Normal file
113
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
# No Code of Conduct
|
||||||
|
|
||||||
|
*TL;DR:* This project does **NOT** have a so called Code of Conduct,
|
||||||
|
nor will it ever have one.
|
||||||
|
|
||||||
|
## The Rant
|
||||||
|
|
||||||
|
The reasons are somewhat complicated and I'll try my best to document
|
||||||
|
them here.
|
||||||
|
|
||||||
|
Ethical codes or rules come along like laws. But how is ethical or
|
||||||
|
moral behavior defined? And who defines which behavior is ethical and
|
||||||
|
which is not? Certainly not me.
|
||||||
|
|
||||||
|
Unless you live in a dictatorship (and more than half of the
|
||||||
|
population of planet earth do as of this writing), laws come into
|
||||||
|
existence by democratic procedures. Laws cover almost every aspect of
|
||||||
|
live in a society. Laws allow and forbid behavior and laws sanction
|
||||||
|
infringements.
|
||||||
|
|
||||||
|
A software project like this one on the other hand is not a society.
|
||||||
|
There are not enough people involved to form democratic
|
||||||
|
structures. And there will always be a minority of users who have the
|
||||||
|
right to commit or reject code. How could any maintainer of a software
|
||||||
|
project dare to decree rules upon others? Actually, am I, the current
|
||||||
|
maintainer of this very project authorized to do so?
|
||||||
|
|
||||||
|
I think the anser to this question clearly is NO.
|
||||||
|
|
||||||
|
The issue is being complicated by the fact, that open source
|
||||||
|
development these days happens on planetary scale. And this planet
|
||||||
|
houses hundreds if not thousands of different cultures, philosophies,
|
||||||
|
ideologies and worldviews. The answer to many ethical questions will
|
||||||
|
in most cases vague and nebulous.
|
||||||
|
|
||||||
|
Ones joke will always be another ones insult.
|
||||||
|
|
||||||
|
Then there is the problem of language. I myself am not an english
|
||||||
|
native, but I publish everyting using the english language. I am able
|
||||||
|
to communicate with most people in the open source community because
|
||||||
|
of that. But I am certainly not able to understand everything and
|
||||||
|
everyone. There might be nuances to a sentence I don't sense, there
|
||||||
|
might be sarcastic connotations I don't understand or references to
|
||||||
|
historical figures, events or traditions I don't know and never have
|
||||||
|
heard of.
|
||||||
|
|
||||||
|
Judging over other peoples online behavior looks like a titanic task
|
||||||
|
to me. It is just not my job to judge others, I am not legitimized or
|
||||||
|
authorized to do so and I am not interested in this kind of business.
|
||||||
|
|
||||||
|
Another huge problem with ethical rules is that you need to outline
|
||||||
|
and enforce sanctions on those who violate the rules. But since I am
|
||||||
|
not an elected authority how would I be able to do this? I don't
|
||||||
|
know. And what happens if someone complains about myself? Shall I
|
||||||
|
remove myself from my own project? Come on!
|
||||||
|
|
||||||
|
Last but not least there's the law. So, let's say someone in india
|
||||||
|
says something insulting to some other developer in an issue. Of
|
||||||
|
course german law does not apply to indian people. More, the insult
|
||||||
|
might actually not be an insult in india. In the end, nothing would
|
||||||
|
happen. Under normal circumstances, maintainers would delete the
|
||||||
|
posting, ban the user or remove push privileges etc.
|
||||||
|
|
||||||
|
But then, is there a way for the offending user to defend himself? Of
|
||||||
|
course not, since neither indian or german law alone applies. I cannot
|
||||||
|
go to a german court and sue the guy and he cannot do the same in
|
||||||
|
india. Or - we possibly could but the judges on both countries would
|
||||||
|
just laugh and close the case.
|
||||||
|
|
||||||
|
That being said, I don't have the power nor the tools, nor the
|
||||||
|
authority to enforce serious sanctions of any meaningful kind against
|
||||||
|
others. Therefore I cannot outline any rules whatsoever.
|
||||||
|
|
||||||
|
And let's not even start talking about there undemocratic "comitees"
|
||||||
|
many projects are forming to circumvent this problem. Some projects
|
||||||
|
even include external entities like a lawer or some bureaucrat
|
||||||
|
somewhere just to have the ability to complain against a comitee
|
||||||
|
member. What a mess!
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## So, which are the ethical rules within this project then?
|
||||||
|
|
||||||
|
Well, there are none.
|
||||||
|
|
||||||
|
This project is about code, not society. It doesn't matter where you
|
||||||
|
come from, how you look, how you think, what you believe, who your
|
||||||
|
friends are, whay you said or did sometime in the past. I don't even
|
||||||
|
care if you are a human being. You are an alien so bored that you need
|
||||||
|
to submit code on github? Fine with me. You're a convicted criminal? I
|
||||||
|
don't give a shit!
|
||||||
|
|
||||||
|
**The only thing I am interested here is Code and only Code.**
|
||||||
|
|
||||||
|
So if anyhing happens here I don't like or I am obliged by law to act
|
||||||
|
on, I will decide on a case to case basis what to do. And
|
||||||
|
unfortunately, since this is the nature of a github project, you
|
||||||
|
cannot complain, object or protest. I am very sorry!
|
||||||
|
|
||||||
|
If you will, let's at least outline these:
|
||||||
|
|
||||||
|
- Please - just please - behave towards others as you'd expect others
|
||||||
|
to behave towards yourself.
|
||||||
|
|
||||||
|
- Don't judge others for any reason.
|
||||||
|
|
||||||
|
- Only judge the code.
|
||||||
|
|
||||||
|
But these are not rules, only a friendly appeal to you as a developer
|
||||||
|
and user.
|
||||||
|
|
||||||
|
|
||||||
|
Thanks a lot!
|
||||||
94
CONTRIBUTING.md
Normal file
94
CONTRIBUTING.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
## Project Goals
|
||||||
|
|
||||||
|
The goal of this project is to build a small tool which helps in day
|
||||||
|
to day work with tabular output of various commandline programs. It
|
||||||
|
should be small, fast and easy to understand. The idea is to replace
|
||||||
|
multiline shell pipes using awk, sed and grep with just one
|
||||||
|
binary.
|
||||||
|
|
||||||
|
There will be no GUI, no web interface, no public API of some sort, no
|
||||||
|
builtin interpreter.
|
||||||
|
|
||||||
|
The programming language used for this project will always be
|
||||||
|
[GOLANG](https://go.dev/) with the exception of the documentation
|
||||||
|
([Perl POD](https://perldoc.perl.org/perlpod)) and the Makefile.
|
||||||
|
|
||||||
|
# Contributing
|
||||||
|
|
||||||
|
You can contribute to this project in various ways:
|
||||||
|
|
||||||
|
## Open an issue
|
||||||
|
|
||||||
|
If you encounter a problem or don't understand how the program works
|
||||||
|
or if you think the documentation is unclear, please don't hesitate to
|
||||||
|
open an issue.
|
||||||
|
|
||||||
|
Please add as much information about the case as possible, such as:
|
||||||
|
|
||||||
|
- Your environment (operating system etc)
|
||||||
|
- tablizer version (`tablizer --version`)
|
||||||
|
- Input data. Please replace sensitive information with mock data!
|
||||||
|
- Actual program output.
|
||||||
|
- Expected program output.
|
||||||
|
- Error message - if any.
|
||||||
|
|
||||||
|
Be aware that I am working on this (and some other) project in my
|
||||||
|
spare time which is scarce. Therefore please don't expect me to
|
||||||
|
respond to your query within hours or even days. Be patient, but I
|
||||||
|
WILL respond.
|
||||||
|
|
||||||
|
## Pull Requests
|
||||||
|
|
||||||
|
Code and documentation help is always much appreciated! Please follow
|
||||||
|
thes guidelines to successfully contribute:
|
||||||
|
|
||||||
|
- Every pull request shall be based on latest `development`
|
||||||
|
branch. `main` is only used for releases.
|
||||||
|
|
||||||
|
- Execute the unit tests before committing: `make test`. There shall
|
||||||
|
be no errors.
|
||||||
|
|
||||||
|
- Strive to be backwards compatible so that users who are already
|
||||||
|
using the program don't have to change their habits - unless it is
|
||||||
|
really neccessary.
|
||||||
|
|
||||||
|
- Try to add a unit test for your addition.
|
||||||
|
|
||||||
|
- Don't ever change existing unit tests!
|
||||||
|
|
||||||
|
- Add a meaningful and comprehensive rationale about your contribution:
|
||||||
|
- Why do you think it might be useful for others?
|
||||||
|
- What did you actually change or add?
|
||||||
|
- Is there an open issue which this PR fixes and if so, please link
|
||||||
|
to that issue.
|
||||||
|
|
||||||
|
- [Re-]format your code with `gofmt -s`.
|
||||||
|
|
||||||
|
- Avoid unneccesary dependencies, especially for very small functions.
|
||||||
|
|
||||||
|
- **If** a new dependency is being added, it must be compatible with
|
||||||
|
our [license agreement](LICENSE).
|
||||||
|
|
||||||
|
- You need to accept that the code or documentation you contribute
|
||||||
|
will be redistributed under the terms of said license agreement. If
|
||||||
|
your contribution is considerably large or if you contribute
|
||||||
|
regularly, then feel free to add your name and if you want your
|
||||||
|
email address to the *AUTHORS* section of the
|
||||||
|
[manpage](tablizer.pod).
|
||||||
|
|
||||||
|
- Adhere to the above mentioned project goals.
|
||||||
|
|
||||||
|
- If you are unsure if your addition or change will be accepted,
|
||||||
|
better ask before starting coding. Open an issue about your proposal
|
||||||
|
and let's discuss it! That way we avoid doing unnessesary work on
|
||||||
|
both sides.
|
||||||
|
|
||||||
|
Each pull request will be carefully reviewed and if it is a useful
|
||||||
|
addition it will be accepted. However, please be prepared that
|
||||||
|
sometimes a PR will be rejected. The reasons may vary and will be
|
||||||
|
documented. Perhaps the above guidelines are not matched, or the
|
||||||
|
addition seems to be not so useful from my perspective, maybe there
|
||||||
|
are too much changes or there might be changes I don't even
|
||||||
|
understand.
|
||||||
|
|
||||||
|
But whatever happens: your contribution is always welcome!
|
||||||
38
Makefile
38
Makefile
@@ -18,23 +18,35 @@
|
|||||||
#
|
#
|
||||||
# no need to modify anything below
|
# no need to modify anything below
|
||||||
tool = tablizer
|
tool = tablizer
|
||||||
version = $(shell egrep "^var Version = " lib/common.go | cut -d'=' -f2 | cut -d'"' -f 2)
|
version = $(shell egrep "= .v" cfg/config.go | cut -d'=' -f2 | cut -d'"' -f 2)
|
||||||
archs = android darwin freebsd linux netbsd openbsd windows
|
archs = android darwin freebsd linux netbsd openbsd windows
|
||||||
PREFIX = /usr/local
|
PREFIX = /usr/local
|
||||||
UID = root
|
UID = root
|
||||||
GID = 0
|
GID = 0
|
||||||
|
BRANCH = $(shell git branch --show-current)
|
||||||
|
COMMIT = $(shell git rev-parse --short=8 HEAD)
|
||||||
|
BUILD = $(shell date +%Y.%m.%d.%H%M%S)
|
||||||
|
VERSION:= $(if $(filter $(BRANCH), development),$(version)-$(BRANCH)-$(COMMIT)-$(BUILD),$(version))
|
||||||
|
|
||||||
all: buildlocal $(tool).1
|
|
||||||
|
all: $(tool).1 cmd/$(tool).go buildlocal
|
||||||
|
|
||||||
%.1: %.pod
|
%.1: %.pod
|
||||||
pod2man -c "User Commands" -r 1 -s 1 $*.pod > $*.1
|
pod2man -c "User Commands" -r 1 -s 1 $*.pod > $*.1
|
||||||
|
|
||||||
|
cmd/%.go: %.pod
|
||||||
|
echo "package cmd" > cmd/$*.go
|
||||||
|
echo >> cmd/$*.go
|
||||||
|
echo "var manpage = \`" >> cmd/$*.go
|
||||||
|
pod2text $*.pod >> cmd/$*.go
|
||||||
|
echo "\`" >> cmd/$*.go
|
||||||
|
|
||||||
buildlocal:
|
buildlocal:
|
||||||
go build
|
go build -ldflags "-X 'github.com/tlinden/tablizer/cfg.VERSION=$(VERSION)'"
|
||||||
|
|
||||||
release:
|
release:
|
||||||
mkdir -p releases
|
./mkrel.sh $(tool) $(version)
|
||||||
$(foreach arch,$(archs), GOOS=$(arch) GOARCH=amd64 go build -x -o releases/$(tool)-$(arch)-amd64-$(version); sha256sum releases/$(tool)-$(arch)-amd64-$(version) | cut -d' ' -f1 > releases/$(tool)-$(arch)-amd64-$(version).sha256sum;)
|
gh release create $(version) --generate-notes releases/*
|
||||||
|
|
||||||
install: buildlocal
|
install: buildlocal
|
||||||
install -d -o $(UID) -g $(GID) $(PREFIX)/bin
|
install -d -o $(UID) -g $(GID) $(PREFIX)/bin
|
||||||
@@ -43,7 +55,15 @@ install: buildlocal
|
|||||||
install -o $(UID) -g $(GID) -m 444 $(tool).1 $(PREFIX)/man/man1/
|
install -o $(UID) -g $(GID) -m 444 $(tool).1 $(PREFIX)/man/man1/
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(tool) $(tool).1 releases
|
rm -rf $(tool) releases coverage.out
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -v ./...
|
go test -v ./...
|
||||||
|
|
||||||
|
singletest:
|
||||||
|
@echo "Call like this: ''make singletest TEST=TestPrepareColumns MOD=lib"
|
||||||
|
go test -run $(TEST) github.com/tlinden/tablizer/$(MOD)
|
||||||
|
|
||||||
|
cover-report:
|
||||||
|
go test ./... -cover -coverprofile=coverage.out
|
||||||
|
go tool cover -html=coverage.out
|
||||||
|
|||||||
46
README.md
46
README.md
@@ -1,4 +1,6 @@
|
|||||||
[](https://app.circleci.com/pipelines/github/TLINDEN/tablizer)
|
[](https://github.com/tlinden/tablizer/actions)
|
||||||
|
[](https://github.com/tlinden/tablizer/blob/master/LICENSE)
|
||||||
|
[](https://goreportcard.com/report/github.com/tlinden/tablizer)
|
||||||
|
|
||||||
## tablizer - Manipulate tabular output of other programs
|
## tablizer - Manipulate tabular output of other programs
|
||||||
|
|
||||||
@@ -19,13 +21,13 @@ But you're only interested in the NAME and STATUS columns. Here's how
|
|||||||
to do this with tablizer:
|
to do this with tablizer:
|
||||||
|
|
||||||
```
|
```
|
||||||
% kubectl get pods | ./tablizer
|
% kubectl get pods | tablizer
|
||||||
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
||||||
repldepl-7bcd8d5b64-7zq4l 1/1 Running 1 (69m ago) 5h26m
|
repldepl-7bcd8d5b64-7zq4l 1/1 Running 1 (69m ago) 5h26m
|
||||||
repldepl-7bcd8d5b64-m48n8 1/1 Running 1 (69m ago) 5h26m
|
repldepl-7bcd8d5b64-m48n8 1/1 Running 1 (69m ago) 5h26m
|
||||||
repldepl-7bcd8d5b64-q2bf4 1/1 Running 1 (69m ago) 5h26m
|
repldepl-7bcd8d5b64-q2bf4 1/1 Running 1 (69m ago) 5h26m
|
||||||
|
|
||||||
% kubectl get pods | ./tablizer -c 1,3
|
% kubectl get pods | tablizer -c 1,3
|
||||||
NAME(1) STATUS(3)
|
NAME(1) STATUS(3)
|
||||||
repldepl-7bcd8d5b64-7zq4l Running
|
repldepl-7bcd8d5b64-7zq4l Running
|
||||||
repldepl-7bcd8d5b64-m48n8 Running
|
repldepl-7bcd8d5b64-m48n8 Running
|
||||||
@@ -33,27 +35,28 @@ repldepl-7bcd8d5b64-q2bf4 Running
|
|||||||
```
|
```
|
||||||
|
|
||||||
Another use case is when the tabular output is so wide that lines are
|
Another use case is when the tabular output is so wide that lines are
|
||||||
being broken and the whole output is completely distorted. In such a
|
being broken and the whole output is completely distorted. In such a
|
||||||
case you can use the `-x` flag to get an output similar to `\x` in `psql`:
|
case you can use the `-o extended | -X` flag to get an output similar
|
||||||
|
to `\x` in `psql`:
|
||||||
|
|
||||||
```
|
```
|
||||||
% kubectl get pods | ./tablizer -x
|
% kubectl get pods | tablizer -X
|
||||||
NAME: repldepl-7bcd8d5b64-7zq4l
|
NAME: repldepl-7bcd8d5b64-7zq4l
|
||||||
READY: 1/1
|
READY: 1/1
|
||||||
STATUS: Running
|
STATUS: Running
|
||||||
RESTARTS: 1 (71m ago)
|
RESTARTS: 1 (71m ago)
|
||||||
AGE: 5h28m
|
AGE: 5h28m
|
||||||
|
|
||||||
NAME: repldepl-7bcd8d5b64-m48n8
|
NAME: repldepl-7bcd8d5b64-m48n8
|
||||||
READY: 1/1
|
READY: 1/1
|
||||||
STATUS: Running
|
STATUS: Running
|
||||||
RESTARTS: 1 (71m ago)
|
RESTARTS: 1 (71m ago)
|
||||||
AGE: 5h28m
|
AGE: 5h28m
|
||||||
|
|
||||||
NAME: repldepl-7bcd8d5b64-q2bf4
|
NAME: repldepl-7bcd8d5b64-q2bf4
|
||||||
READY: 1/1
|
READY: 1/1
|
||||||
STATUS: Running
|
STATUS: Running
|
||||||
RESTARTS: 1 (71m ago)
|
RESTARTS: 1 (71m ago)
|
||||||
AGE: 5h28m
|
AGE: 5h28m
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -62,11 +65,12 @@ Tablize can read one or more files or - if none specified - from STDIN.
|
|||||||
You can also specify a regex pattern to reduce the output:
|
You can also specify a regex pattern to reduce the output:
|
||||||
|
|
||||||
```
|
```
|
||||||
% kubectl get pods | ./tablizer q2bf4
|
% kubectl get pods | tablizer q2bf4
|
||||||
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
||||||
repldepl-7bcd8d5b64-q2bf4 1/1 Running 1 (69m ago) 5h26m
|
repldepl-7bcd8d5b64-q2bf4 1/1 Running 1 (69m ago) 5h26m
|
||||||
```
|
```
|
||||||
|
|
||||||
|
There are more output modes like org-mode (orgtbl) and markdown.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -105,6 +109,10 @@ https://github.com/TLINDEN/tablizer/blob/main/tablizer.pod
|
|||||||
Or if you cloned the repository you can read it this way (perl needs
|
Or if you cloned the repository you can read it this way (perl needs
|
||||||
to be installed though): `perldoc tablizer.pod`.
|
to be installed though): `perldoc tablizer.pod`.
|
||||||
|
|
||||||
|
If you have the binary installed, you can also read the man page with
|
||||||
|
this command:
|
||||||
|
|
||||||
|
tablizer --man
|
||||||
|
|
||||||
## Getting help
|
## Getting help
|
||||||
|
|
||||||
|
|||||||
5
TODO
5
TODO
@@ -1,5 +0,0 @@
|
|||||||
Add a mode like FreeBSD stat(1):
|
|
||||||
|
|
||||||
stat -s dead.letter
|
|
||||||
st_dev=170671546954750497 st_ino=159667 st_mode=0100644 st_nlink=1 st_uid=1001 st_gid=1001 st_rdev=18446744073709551615 st_size=573 st_atime=1661994007 st_mtime=1661961878 st_ctime=1661961878 st_birthtime=1658394900 st_blksize=4096 st_blocks=3 st_flags=2048
|
|
||||||
|
|
||||||
15
TODO.md
Normal file
15
TODO.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
## Fixes to be implemented
|
||||||
|
|
||||||
|
- rm printYamlData() log.Fatal(), maybe return error on all printers?
|
||||||
|
|
||||||
|
- printShellData() checks Columns unnecessarily (compare to yaml or extended)
|
||||||
|
|
||||||
|
## Features to be implemented
|
||||||
|
|
||||||
|
- add output mode csv
|
||||||
|
|
||||||
|
- add --no-headers option
|
||||||
|
|
||||||
|
- add input parsing support for CSV including unquoting of stuff
|
||||||
|
like: `"xxx","1919 b"` etc, maybe an extra option for unquoting
|
||||||
|
|
||||||
144
cfg/config.go
Normal file
144
cfg/config.go
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
/*
|
||||||
|
Copyright © 2022 Thomas von Dein
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
package cfg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"github.com/gookit/color"
|
||||||
|
"regexp"
|
||||||
|
)
|
||||||
|
|
||||||
|
const DefaultSeparator string = `(\s\s+|\t)`
|
||||||
|
const ValidOutputModes string = "(orgtbl|markdown|extended|ascii|yaml|shell)"
|
||||||
|
const Version string = "v1.0.11"
|
||||||
|
|
||||||
|
var VERSION string // maintained by -x
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Debug bool
|
||||||
|
NoNumbering bool
|
||||||
|
Columns string
|
||||||
|
UseColumns []int
|
||||||
|
Separator string
|
||||||
|
OutputMode string
|
||||||
|
InvertMatch bool
|
||||||
|
Pattern string
|
||||||
|
|
||||||
|
SortMode string
|
||||||
|
SortDescending bool
|
||||||
|
SortByColumn int
|
||||||
|
|
||||||
|
/*
|
||||||
|
FIXME: make configurable somehow, config file or ENV
|
||||||
|
see https://github.com/gookit/color will be set by
|
||||||
|
io.ProcessFiles() according to currently supported
|
||||||
|
color mode.
|
||||||
|
*/
|
||||||
|
MatchFG string
|
||||||
|
MatchBG string
|
||||||
|
NoColor bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// maps outputmode short flags to output mode, ie. -O => -o orgtbl
|
||||||
|
type Modeflag struct {
|
||||||
|
X bool
|
||||||
|
O bool
|
||||||
|
M bool
|
||||||
|
S bool
|
||||||
|
Y bool
|
||||||
|
A bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// various sort types
|
||||||
|
type Sortmode struct {
|
||||||
|
Numeric bool
|
||||||
|
Time bool
|
||||||
|
Age bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func Colors() map[color.Level]map[string]string {
|
||||||
|
// default color schemes
|
||||||
|
return map[color.Level]map[string]string{
|
||||||
|
color.Level16: {
|
||||||
|
"bg": "green", "fg": "black",
|
||||||
|
},
|
||||||
|
color.Level256: {
|
||||||
|
"bg": "lightGreen", "fg": "black",
|
||||||
|
},
|
||||||
|
color.LevelRgb: {
|
||||||
|
// FIXME: maybe use something nicer
|
||||||
|
"bg": "lightGreen", "fg": "black",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Getversion() string {
|
||||||
|
// main program version
|
||||||
|
|
||||||
|
// generated version string, used by -v contains lib.Version on
|
||||||
|
// main branch, and lib.Version-$branch-$lastcommit-$date on
|
||||||
|
// development branch
|
||||||
|
|
||||||
|
return fmt.Sprintf("This is tablizer version %s", VERSION)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conf *Config) PrepareModeFlags(flag Modeflag, mode string) error {
|
||||||
|
if len(mode) == 0 {
|
||||||
|
// associate short flags like -X with mode selector
|
||||||
|
switch {
|
||||||
|
case flag.X:
|
||||||
|
conf.OutputMode = "extended"
|
||||||
|
case flag.M:
|
||||||
|
conf.OutputMode = "markdown"
|
||||||
|
case flag.O:
|
||||||
|
conf.OutputMode = "orgtbl"
|
||||||
|
case flag.S:
|
||||||
|
conf.OutputMode = "shell"
|
||||||
|
conf.NoNumbering = true
|
||||||
|
case flag.Y:
|
||||||
|
conf.OutputMode = "yaml"
|
||||||
|
conf.NoNumbering = true
|
||||||
|
default:
|
||||||
|
conf.OutputMode = "ascii"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
r, _ := regexp.Compile(ValidOutputModes) // hardcoded, no fail expected
|
||||||
|
match := r.MatchString(mode)
|
||||||
|
|
||||||
|
if !match {
|
||||||
|
return errors.New("Invalid output mode!")
|
||||||
|
}
|
||||||
|
|
||||||
|
conf.OutputMode = mode
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (conf *Config) PrepareSortFlags(flag Sortmode) {
|
||||||
|
switch {
|
||||||
|
case flag.Numeric:
|
||||||
|
conf.SortMode = "numeric"
|
||||||
|
case flag.Age:
|
||||||
|
conf.SortMode = "duration"
|
||||||
|
case flag.Time:
|
||||||
|
conf.SortMode = "time"
|
||||||
|
default:
|
||||||
|
conf.SortMode = "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
98
cfg/config_test.go
Normal file
98
cfg/config_test.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
/*
|
||||||
|
Copyright © 2022 Thomas von Dein
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package cfg
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
// "reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPrepareModeFlags(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
flag Modeflag
|
||||||
|
mode string // input, if any
|
||||||
|
expect string // output
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
// short commandline flags like -M
|
||||||
|
{Modeflag{X: true}, "", "extended", false},
|
||||||
|
{Modeflag{S: true}, "", "shell", false},
|
||||||
|
{Modeflag{O: true}, "", "orgtbl", false},
|
||||||
|
{Modeflag{Y: true}, "", "yaml", false},
|
||||||
|
{Modeflag{M: true}, "", "markdown", false},
|
||||||
|
{Modeflag{}, "", "ascii", false},
|
||||||
|
|
||||||
|
// long flags like -o yaml
|
||||||
|
{Modeflag{}, "extended", "extended", false},
|
||||||
|
{Modeflag{}, "shell", "shell", false},
|
||||||
|
{Modeflag{}, "orgtbl", "orgtbl", false},
|
||||||
|
{Modeflag{}, "yaml", "yaml", false},
|
||||||
|
{Modeflag{}, "markdown", "markdown", false},
|
||||||
|
|
||||||
|
// failing
|
||||||
|
{Modeflag{}, "blah", "", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("PrepareModeFlags-flags-mode-%s-expect-%s-want-%t",
|
||||||
|
tt.mode, tt.expect, tt.want)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := Config{OutputMode: tt.mode}
|
||||||
|
|
||||||
|
// check either flag or pre filled mode, whatever is defined in tt
|
||||||
|
err := c.PrepareModeFlags(tt.flag, tt.mode)
|
||||||
|
if err != nil {
|
||||||
|
if !tt.want {
|
||||||
|
// expect to fail
|
||||||
|
t.Fatalf("PrepareModeFlags returned unexpected error: %s", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if c.OutputMode != tt.expect {
|
||||||
|
t.Errorf("got: %s, expect: %s", c.OutputMode, tt.expect)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrepareSortFlags(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
flag Sortmode
|
||||||
|
expect string // output
|
||||||
|
}{
|
||||||
|
// short commandline flags like -M
|
||||||
|
{Sortmode{Numeric: true}, "numeric"},
|
||||||
|
{Sortmode{Age: true}, "duration"},
|
||||||
|
{Sortmode{Time: true}, "time"},
|
||||||
|
{Sortmode{}, "string"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("PrepareSortFlags-expect-%s", tt.expect)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := Config{}
|
||||||
|
|
||||||
|
c.PrepareSortFlags(tt.flag)
|
||||||
|
|
||||||
|
if c.SortMode != tt.expect {
|
||||||
|
t.Errorf("got: %s, expect: %s", c.SortMode, tt.expect)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
127
cmd/root.go
127
cmd/root.go
@@ -17,59 +17,106 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"daemon.de/tablizer/lib"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
|
"github.com/tlinden/tablizer/lib"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
)
|
)
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
func man() {
|
||||||
Use: "tablizer [regex] [file, ...]",
|
man := exec.Command("less", "-")
|
||||||
Short: "[Re-]tabularize tabular data",
|
|
||||||
Long: `Manipulate tabular output of other programs`,
|
|
||||||
RunE: func(cmd *cobra.Command, args []string) error {
|
|
||||||
if lib.ShowVersion {
|
|
||||||
fmt.Printf("This is tablizer version %s\n", lib.Version)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
err := lib.PrepareColumns()
|
var b bytes.Buffer
|
||||||
if err != nil {
|
b.Write([]byte(manpage))
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = lib.PrepareModeFlags()
|
man.Stdout = os.Stdout
|
||||||
if err != nil {
|
man.Stdin = &b
|
||||||
return err
|
man.Stderr = os.Stderr
|
||||||
}
|
|
||||||
|
|
||||||
return lib.ProcessFiles(args)
|
err := man.Run()
|
||||||
},
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Execute() {
|
func Execute() {
|
||||||
|
var (
|
||||||
|
conf cfg.Config
|
||||||
|
ShowManual bool
|
||||||
|
Outputmode string
|
||||||
|
ShowVersion bool
|
||||||
|
modeflag cfg.Modeflag
|
||||||
|
sortmode cfg.Sortmode
|
||||||
|
)
|
||||||
|
|
||||||
|
var rootCmd = &cobra.Command{
|
||||||
|
Use: "tablizer [regex] [file, ...]",
|
||||||
|
Short: "[Re-]tabularize tabular data",
|
||||||
|
Long: `Manipulate tabular output of other programs`,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
if ShowVersion {
|
||||||
|
fmt.Println(cfg.Getversion())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if ShowManual {
|
||||||
|
man()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepare flags
|
||||||
|
err := conf.PrepareModeFlags(modeflag, Outputmode)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
conf.PrepareSortFlags(sortmode)
|
||||||
|
|
||||||
|
// actual execution starts here
|
||||||
|
return lib.ProcessFiles(conf, args)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// options
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&conf.Debug, "debug", "d", false, "Enable debugging")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&conf.NoNumbering, "no-numbering", "n", false, "Disable header numbering")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&conf.NoColor, "no-color", "N", false, "Disable pattern highlighting")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&ShowVersion, "version", "V", false, "Print program version")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&conf.InvertMatch, "invert-match", "v", false, "select non-matching rows")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&ShowManual, "man", "m", false, "Display manual page")
|
||||||
|
rootCmd.PersistentFlags().StringVarP(&conf.Separator, "separator", "s", cfg.DefaultSeparator, "Custom field separator")
|
||||||
|
rootCmd.PersistentFlags().StringVarP(&conf.Columns, "columns", "c", "", "Only show the speficied columns (separated by ,)")
|
||||||
|
|
||||||
|
// sort options
|
||||||
|
rootCmd.PersistentFlags().IntVarP(&conf.SortByColumn, "sort-by", "k", 0, "Sort by column (default: 1)")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&conf.SortDescending, "sort-desc", "D", false, "Sort in descending order (default: ascending)")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&sortmode.Numeric, "sort-numeric", "i", false, "sort according to string numerical value")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&sortmode.Time, "sort-time", "t", false, "sort according to time string")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&sortmode.Age, "sort-age", "a", false, "sort according to age (duration) string")
|
||||||
|
|
||||||
|
// output flags, only 1 allowed, hidden, since just short cuts
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&modeflag.X, "extended", "X", false, "Enable extended output")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&modeflag.M, "markdown", "M", false, "Enable markdown table output")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&modeflag.O, "orgtbl", "O", false, "Enable org-mode table output")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&modeflag.S, "shell", "S", false, "Enable shell mode output")
|
||||||
|
rootCmd.PersistentFlags().BoolVarP(&modeflag.Y, "yaml", "Y", false, "Enable yaml output")
|
||||||
|
rootCmd.MarkFlagsMutuallyExclusive("extended", "markdown", "orgtbl", "shell", "yaml")
|
||||||
|
_ = rootCmd.Flags().MarkHidden("extended")
|
||||||
|
_ = rootCmd.Flags().MarkHidden("orgtbl")
|
||||||
|
_ = rootCmd.Flags().MarkHidden("markdown")
|
||||||
|
_ = rootCmd.Flags().MarkHidden("shell")
|
||||||
|
_ = rootCmd.Flags().MarkHidden("yaml")
|
||||||
|
|
||||||
|
// same thing but more common, takes precedence over above group
|
||||||
|
rootCmd.PersistentFlags().StringVarP(&Outputmode, "output", "o", "", "Output mode - one of: orgtbl, markdown, extended, shell, ascii(default)")
|
||||||
|
|
||||||
err := rootCmd.Execute()
|
err := rootCmd.Execute()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.Debug, "debug", "d", false, "Enable debugging")
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.NoNumbering, "no-numbering", "n", false, "Disable header numbering")
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.ShowVersion, "version", "v", false, "Print program version")
|
|
||||||
rootCmd.PersistentFlags().StringVarP(&lib.Separator, "separator", "s", "", "Custom field separator")
|
|
||||||
rootCmd.PersistentFlags().StringVarP(&lib.Columns, "columns", "c", "", "Only show the speficied columns (separated by ,)")
|
|
||||||
|
|
||||||
// output flags, only 1 allowed, hidden, since just short cuts
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.OutflagExtended, "extended", "X", false, "Enable extended output")
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.OutflagMarkdown, "markdown", "M", false, "Enable markdown table output")
|
|
||||||
rootCmd.PersistentFlags().BoolVarP(&lib.OutflagOrgtable, "orgtbl", "O", false, "Enable org-mode table output")
|
|
||||||
rootCmd.MarkFlagsMutuallyExclusive("extended", "markdown", "orgtbl")
|
|
||||||
rootCmd.Flags().MarkHidden("extended")
|
|
||||||
rootCmd.Flags().MarkHidden("orgtbl")
|
|
||||||
rootCmd.Flags().MarkHidden("markdown")
|
|
||||||
|
|
||||||
// same thing but more common, takes precedence over above group
|
|
||||||
rootCmd.PersistentFlags().StringVarP(&lib.OutputMode, "output", "o", "", "Output mode - one of: orgtbl, markdown, extended, ascii(default)")
|
|
||||||
}
|
|
||||||
|
|||||||
207
cmd/tablizer.go
Normal file
207
cmd/tablizer.go
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
package cmd
|
||||||
|
|
||||||
|
var manpage = `
|
||||||
|
NAME
|
||||||
|
tablizer - Manipulate tabular output of other programs
|
||||||
|
|
||||||
|
SYNOPSIS
|
||||||
|
Usage:
|
||||||
|
tablizer [regex] [file, ...] [flags]
|
||||||
|
|
||||||
|
Flags:
|
||||||
|
-c, --columns string Only show the speficied columns (separated by ,)
|
||||||
|
-d, --debug Enable debugging
|
||||||
|
-h, --help help for tablizer
|
||||||
|
-v, --invert-match select non-matching rows
|
||||||
|
-m, --man Display manual page
|
||||||
|
-n, --no-numbering Disable header numbering
|
||||||
|
-N, --no-color Disable pattern highlighting
|
||||||
|
-o, --output string Output mode - one of: orgtbl, markdown, extended, yaml, ascii(default)
|
||||||
|
-X, --extended Enable extended output
|
||||||
|
-M, --markdown Enable markdown table output
|
||||||
|
-O, --orgtbl Enable org-mode table output
|
||||||
|
-s, --separator string Custom field separator
|
||||||
|
-a, --sort-age sort according to age (duration) string
|
||||||
|
-k, --sort-by int Sort by column (default: 1)
|
||||||
|
-D, --sort-desc Sort in descending order (default: ascending)
|
||||||
|
-i, --sort-numeric sort according to string numerical value
|
||||||
|
-t, --sort-time sort according to time string
|
||||||
|
-v, --version Print program version
|
||||||
|
|
||||||
|
DESCRIPTION
|
||||||
|
Many programs generate tabular output. But sometimes you need to
|
||||||
|
post-process these tables, you may need to remove one or more columns or
|
||||||
|
you may want to filter for some pattern (See PATTERNS) or you may need
|
||||||
|
the output in another program and need to parse it somehow. Standard
|
||||||
|
unix tools such as awk(1), grep(1) or column(1) may help, but sometimes
|
||||||
|
it's a tedious business.
|
||||||
|
|
||||||
|
Let's take the output of the tool kubectl. It contains cells with
|
||||||
|
withespace and they do not separate columns by TAB characters. This is
|
||||||
|
not easy to process.
|
||||||
|
|
||||||
|
You can use tablizer to do these and more things.
|
||||||
|
|
||||||
|
tablizer analyses the header fields of a table, registers the column
|
||||||
|
positions of each header field and separates columns by those positions.
|
||||||
|
|
||||||
|
Without any options it reads its input from "STDIN", but you can also
|
||||||
|
specify a file as a parameter. If you want to reduce the output by some
|
||||||
|
regular expression, just specify it as its first parameter. You may also
|
||||||
|
use the -v option to exclude all rows which match the pattern. Hence:
|
||||||
|
|
||||||
|
# read from STDIN
|
||||||
|
kubectl get pods | tablizer
|
||||||
|
|
||||||
|
# read a file
|
||||||
|
tablizer filename
|
||||||
|
|
||||||
|
# search for pattern in a file (works like grep)
|
||||||
|
tablizer regex filename
|
||||||
|
|
||||||
|
# search for pattern in STDIN
|
||||||
|
kubectl get pods | tablizer regex
|
||||||
|
|
||||||
|
The output looks like the original one but every header field will have
|
||||||
|
a numer associated with it, e.g.:
|
||||||
|
|
||||||
|
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
||||||
|
|
||||||
|
These numbers denote the column and you can use them to specify which
|
||||||
|
columns you want to have in your output (see COLUMNS:
|
||||||
|
|
||||||
|
kubectl get pods | tablizer -c1,3
|
||||||
|
|
||||||
|
You can specify the numbers in any order but output will always follow
|
||||||
|
the original order.
|
||||||
|
|
||||||
|
The numbering can be suppressed by using the -n option.
|
||||||
|
|
||||||
|
By default, if a pattern has been speficied, matches will be
|
||||||
|
highlighted. You can disable this behavior with the -N option.
|
||||||
|
|
||||||
|
Use the -k option to specify by which column to sort the tabular data
|
||||||
|
(as in GNU sort(1)). The default sort column is the first one. To
|
||||||
|
disable sorting at all, supply 0 (Zero) to -k. The default sort order is
|
||||||
|
ascending. You can change this to descending order using the option -D.
|
||||||
|
The default sort order is by string, but there are other sort modes:
|
||||||
|
|
||||||
|
-a --sort-age
|
||||||
|
Sorts duration strings like "1d4h32m51s".
|
||||||
|
|
||||||
|
-i --sort-numeric
|
||||||
|
Sorts numeric fields.
|
||||||
|
|
||||||
|
-t --sort-time
|
||||||
|
Sorts timestamps.
|
||||||
|
|
||||||
|
Finally the -d option enables debugging output which is mostly useful
|
||||||
|
for the developer.
|
||||||
|
|
||||||
|
PATTERNS
|
||||||
|
You can reduce the rows being displayed by using a regular expression
|
||||||
|
pattern. The regexp is PCRE compatible, refer to the syntax cheat sheet
|
||||||
|
here: <https://github.com/google/re2/wiki/Syntax>. If you want to read a
|
||||||
|
more comprehensive documentation about the topic and have perl installed
|
||||||
|
you can read it with:
|
||||||
|
|
||||||
|
perldoc perlre
|
||||||
|
|
||||||
|
Or read it online: <https://perldoc.perl.org/perlre>.
|
||||||
|
|
||||||
|
A note on modifiers: the regexp engine used in tablizer uses another
|
||||||
|
modifier syntax:
|
||||||
|
|
||||||
|
(?MODIFIER)
|
||||||
|
|
||||||
|
The most important modifiers are:
|
||||||
|
|
||||||
|
"i" ignore case "m" multiline mode "s" single line mode
|
||||||
|
|
||||||
|
Example for a case insensitive search:
|
||||||
|
|
||||||
|
kubectl get pods -A | tablizer "(?i)account"
|
||||||
|
|
||||||
|
COLUMNS
|
||||||
|
The parameter -c can be used to specify, which columns to display. By
|
||||||
|
default tablizer numerizes the header names and these numbers can be
|
||||||
|
used to specify which header to display, see example above.
|
||||||
|
|
||||||
|
However, beside numbers, you can also use regular expressions with -c,
|
||||||
|
also separated by comma. And you can mix column numbers with regexps.
|
||||||
|
|
||||||
|
Lets take this table:
|
||||||
|
|
||||||
|
PID TTY TIME CMD
|
||||||
|
14001 pts/0 00:00:00 bash
|
||||||
|
42871 pts/0 00:00:00 ps
|
||||||
|
42872 pts/0 00:00:00 sed
|
||||||
|
|
||||||
|
We want to see only the CMD column and use a regex for this:
|
||||||
|
|
||||||
|
ps | tablizer -s '\s+' -c C
|
||||||
|
CMD(4)
|
||||||
|
bash
|
||||||
|
ps
|
||||||
|
tablizer
|
||||||
|
sed
|
||||||
|
|
||||||
|
where "C" is our regexp which matches CMD.
|
||||||
|
|
||||||
|
OUTPUT MODES
|
||||||
|
There might be cases when the tabular output of a program is way too
|
||||||
|
large for your current terminal but you still need to see every column.
|
||||||
|
In such cases the -o extended or -X option can be useful which enables
|
||||||
|
*extended mode*. In this mode, each row will be printed vertically,
|
||||||
|
header left, value right, aligned by the field widths. Here's an
|
||||||
|
example:
|
||||||
|
|
||||||
|
kubectl get pods | ./tablizer -o extended
|
||||||
|
NAME: repldepl-7bcd8d5b64-7zq4l
|
||||||
|
READY: 1/1
|
||||||
|
STATUS: Running
|
||||||
|
RESTARTS: 1 (71m ago)
|
||||||
|
AGE: 5h28m
|
||||||
|
|
||||||
|
You can of course still use a regex to reduce the number of rows
|
||||||
|
displayed.
|
||||||
|
|
||||||
|
The option -o shell can be used if the output has to be processed by the
|
||||||
|
shell, it prints variable assignments for each cell, one line per row:
|
||||||
|
|
||||||
|
kubectl get pods | ./tablizer -o extended ./tablizer -o shell
|
||||||
|
NAME="repldepl-7bcd8d5b64-7zq4l" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
NAME="repldepl-7bcd8d5b64-m48n8" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
NAME="repldepl-7bcd8d5b64-q2bf4" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
|
||||||
|
You can use this in an eval loop.
|
||||||
|
|
||||||
|
Beside normal ascii mode (the default) and extended mode there are more
|
||||||
|
output modes available: orgtbl which prints an Emacs org-mode table and
|
||||||
|
markdown which prints a Markdown table and yaml, which prints yaml
|
||||||
|
encoding.
|
||||||
|
|
||||||
|
BUGS
|
||||||
|
In order to report a bug, unexpected behavior, feature requests or to
|
||||||
|
submit a patch, please open an issue on github:
|
||||||
|
<https://github.com/TLINDEN/tablizer/issues>.
|
||||||
|
|
||||||
|
LICENSE
|
||||||
|
This software is licensed under the GNU GENERAL PUBLIC LICENSE version
|
||||||
|
3.
|
||||||
|
|
||||||
|
Copyright (c) 2022 by Thomas von Dein
|
||||||
|
|
||||||
|
This software uses the following GO libraries:
|
||||||
|
|
||||||
|
repr (https://github.com/alecthomas/repr)
|
||||||
|
Released under the MIT License, Copyright (c) 2016 Alec Thomas
|
||||||
|
|
||||||
|
cobra (https://github.com/spf13/cobra)
|
||||||
|
Released under the Apache 2.0 license, Copyright 2013-2022 The Cobra
|
||||||
|
Authors
|
||||||
|
|
||||||
|
AUTHORS
|
||||||
|
Thomas von Dein tom AT vondein DOT org
|
||||||
|
|
||||||
|
`
|
||||||
11
go.mod
11
go.mod
@@ -1,16 +1,21 @@
|
|||||||
module daemon.de/tablizer
|
module github.com/tlinden/tablizer
|
||||||
|
|
||||||
go 1.18
|
go 1.18
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897
|
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897
|
||||||
|
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de
|
||||||
|
github.com/gookit/color v1.5.2
|
||||||
github.com/olekukonko/tablewriter v0.0.5
|
github.com/olekukonko/tablewriter v0.0.5
|
||||||
github.com/spf13/cobra v1.5.0
|
github.com/spf13/cobra v1.5.0
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.9 // indirect
|
github.com/mattn/go-runewidth v0.0.10 // indirect
|
||||||
|
github.com/rivo/uniseg v0.1.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.5 // indirect
|
github.com/spf13/pflag v1.0.5 // indirect
|
||||||
github.com/stretchr/testify v1.8.0 // indirect
|
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
16
go.sum
16
go.sum
@@ -1,27 +1,41 @@
|
|||||||
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY=
|
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY=
|
||||||
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ=
|
github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ=
|
||||||
|
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
|
||||||
|
github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/gookit/color v1.5.2 h1:uLnfXcaFjlrDnQDT+NCBcfhrXqYTx/rcCa6xn01Y8yI=
|
||||||
|
github.com/gookit/color v1.5.2/go.mod h1:w8h4bGiHeeBpvQVePTutdbERIUf3oJE5lZ8HM0UgXyg=
|
||||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||||
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
|
|
||||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||||
|
github.com/mattn/go-runewidth v0.0.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRRpdGg=
|
||||||
|
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||||
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
|
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
|
||||||
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
|
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY=
|
||||||
|
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
|
||||||
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
|
||||||
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
|
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
|
||||||
|
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44 h1:Bli41pIlzTzf3KEY06n+xnzK/BESIg2ze4Pgfh/aI8c=
|
||||||
|
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -17,18 +17,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||||||
|
|
||||||
package lib
|
package lib
|
||||||
|
|
||||||
// command line flags
|
// contains a whole parsed table
|
||||||
var Debug bool
|
type Tabdata struct {
|
||||||
var XtendedOut bool
|
maxwidthHeader int // longest header
|
||||||
var NoNumbering bool
|
maxwidthPerCol []int // max width per column
|
||||||
var ShowVersion bool
|
columns int // count
|
||||||
var Columns string
|
headers []string // [ "ID", "NAME", ...]
|
||||||
var UseColumns []int
|
entries [][]string
|
||||||
var Separator string
|
}
|
||||||
var OutflagExtended bool
|
|
||||||
var OutflagMarkdown bool
|
|
||||||
var OutflagOrgtable bool
|
|
||||||
var OutputMode string
|
|
||||||
|
|
||||||
var Version = "v1.0.2"
|
|
||||||
var validOutputmodes = "(orgtbl|markdown|extended|ascii)"
|
|
||||||
|
|||||||
159
lib/helpers.go
159
lib/helpers.go
@@ -20,17 +20,15 @@ package lib
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gookit/color"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func die(v ...interface{}) {
|
|
||||||
fmt.Fprintln(os.Stderr, v...)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func contains(s []int, e int) bool {
|
func contains(s []int, e int) bool {
|
||||||
for _, a := range s {
|
for _, a := range s {
|
||||||
if a == e {
|
if a == e {
|
||||||
@@ -40,45 +38,134 @@ func contains(s []int, e int) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func PrepareColumns() error {
|
// parse columns list given with -c, modifies config.UseColumns based
|
||||||
if len(Columns) > 0 {
|
// on eventually given regex
|
||||||
for _, use := range strings.Split(Columns, ",") {
|
func PrepareColumns(c *cfg.Config, data *Tabdata) error {
|
||||||
usenum, err := strconv.Atoi(use)
|
if len(c.Columns) > 0 {
|
||||||
if err != nil {
|
for _, use := range strings.Split(c.Columns, ",") {
|
||||||
msg := fmt.Sprintf("Could not parse columns list %s: %v", Columns, err)
|
if len(use) == 0 {
|
||||||
|
msg := fmt.Sprintf("Could not parse columns list %s: empty column", c.Columns)
|
||||||
return errors.New(msg)
|
return errors.New(msg)
|
||||||
}
|
}
|
||||||
UseColumns = append(UseColumns, usenum)
|
|
||||||
|
usenum, err := strconv.Atoi(use)
|
||||||
|
if err != nil {
|
||||||
|
// might be a regexp
|
||||||
|
colPattern, err := regexp.Compile(use)
|
||||||
|
if err != nil {
|
||||||
|
msg := fmt.Sprintf("Could not parse columns list %s: %v", c.Columns, err)
|
||||||
|
return errors.New(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// find matching header fields
|
||||||
|
for i, head := range data.headers {
|
||||||
|
if colPattern.MatchString(head) {
|
||||||
|
c.UseColumns = append(c.UseColumns, i+1)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// we digress from go best practises here, because if
|
||||||
|
// a colum spec is not a number, we process them above
|
||||||
|
// inside the err handler for atoi(). so only add the
|
||||||
|
// number, if it's really just a number.
|
||||||
|
c.UseColumns = append(c.UseColumns, usenum)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// deduplicate: put all values into a map (value gets map key)
|
||||||
|
// thereby removing duplicates, extract keys into new slice
|
||||||
|
// and sort it
|
||||||
|
imap := make(map[int]int, len(c.UseColumns))
|
||||||
|
for _, i := range c.UseColumns {
|
||||||
|
imap[i] = 0
|
||||||
|
}
|
||||||
|
c.UseColumns = nil
|
||||||
|
for k := range imap {
|
||||||
|
c.UseColumns = append(c.UseColumns, k)
|
||||||
|
}
|
||||||
|
sort.Ints(c.UseColumns)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func PrepareModeFlags() error {
|
// prepare headers: add numbers to headers
|
||||||
if len(OutputMode) == 0 {
|
func numberizeAndReduceHeaders(c cfg.Config, data *Tabdata) {
|
||||||
switch {
|
numberedHeaders := []string{}
|
||||||
case OutflagExtended:
|
maxwidth := 0 // start from scratch, so we only look at displayed column widths
|
||||||
OutputMode = "extended"
|
|
||||||
case OutflagMarkdown:
|
for i, head := range data.headers {
|
||||||
OutputMode = "markdown"
|
headlen := 0
|
||||||
case OutflagOrgtable:
|
if len(c.Columns) > 0 {
|
||||||
OutputMode = "orgtbl"
|
// -c specified
|
||||||
default:
|
if !contains(c.UseColumns, i+1) {
|
||||||
OutputMode = "ascii"
|
// ignore this one
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if c.NoNumbering {
|
||||||
|
numberedHeaders = append(numberedHeaders, head)
|
||||||
|
headlen = len(head)
|
||||||
|
} else {
|
||||||
|
numhead := fmt.Sprintf("%s(%d)", head, i+1)
|
||||||
|
headlen = len(numhead)
|
||||||
|
numberedHeaders = append(numberedHeaders, numhead)
|
||||||
|
}
|
||||||
|
|
||||||
|
if headlen > maxwidth {
|
||||||
|
maxwidth = headlen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.headers = numberedHeaders
|
||||||
|
if data.maxwidthHeader != maxwidth && maxwidth > 0 {
|
||||||
|
data.maxwidthHeader = maxwidth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// exclude columns, if any
|
||||||
|
func reduceColumns(c cfg.Config, data *Tabdata) {
|
||||||
|
if len(c.Columns) > 0 {
|
||||||
|
reducedEntries := [][]string{}
|
||||||
|
var reducedEntry []string
|
||||||
|
for _, entry := range data.entries {
|
||||||
|
reducedEntry = nil
|
||||||
|
for i, value := range entry {
|
||||||
|
if !contains(c.UseColumns, i+1) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
reducedEntry = append(reducedEntry, value)
|
||||||
|
}
|
||||||
|
reducedEntries = append(reducedEntries, reducedEntry)
|
||||||
|
}
|
||||||
|
data.entries = reducedEntries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimRow(row []string) []string {
|
||||||
|
// FIXME: remove this when we only use Tablewriter and strip in ParseFile()!
|
||||||
|
var fixedrow []string
|
||||||
|
for _, cell := range row {
|
||||||
|
fixedrow = append(fixedrow, strings.TrimSpace(cell))
|
||||||
|
}
|
||||||
|
|
||||||
|
return fixedrow
|
||||||
|
}
|
||||||
|
|
||||||
|
func colorizeData(c cfg.Config, output string) string {
|
||||||
|
if len(c.Pattern) > 0 && !c.NoColor && color.IsConsole(os.Stdout) {
|
||||||
|
r := regexp.MustCompile("(" + c.Pattern + ")")
|
||||||
|
return r.ReplaceAllString(output, "<bg="+c.MatchBG+";fg="+c.MatchFG+">$1</>")
|
||||||
} else {
|
} else {
|
||||||
r, err := regexp.Compile(validOutputmodes)
|
return output
|
||||||
|
}
|
||||||
if err != nil {
|
}
|
||||||
return errors.New("Failed to validate output mode spec!")
|
|
||||||
}
|
func isTerminal(f *os.File) bool {
|
||||||
|
o, _ := f.Stat()
|
||||||
match := r.MatchString(OutputMode)
|
if (o.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
|
||||||
|
return true
|
||||||
if !match {
|
} else {
|
||||||
return errors.New("Invalid output mode!")
|
return false
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,11 +19,12 @@ package lib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Testcontains(t *testing.T) {
|
func TestContains(t *testing.T) {
|
||||||
var tests = []struct {
|
var tests = []struct {
|
||||||
list []int
|
list []int
|
||||||
search int
|
search int
|
||||||
@@ -45,6 +46,24 @@ func Testcontains(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPrepareColumns(t *testing.T) {
|
func TestPrepareColumns(t *testing.T) {
|
||||||
|
data := Tabdata{
|
||||||
|
maxwidthHeader: 5,
|
||||||
|
maxwidthPerCol: []int{
|
||||||
|
5,
|
||||||
|
5,
|
||||||
|
8,
|
||||||
|
},
|
||||||
|
columns: 3,
|
||||||
|
headers: []string{
|
||||||
|
"ONE", "TWO", "THREE",
|
||||||
|
},
|
||||||
|
entries: [][]string{
|
||||||
|
{
|
||||||
|
"2", "3", "4",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
var tests = []struct {
|
var tests = []struct {
|
||||||
input string
|
input string
|
||||||
exp []int
|
exp []int
|
||||||
@@ -52,22 +71,92 @@ func TestPrepareColumns(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{"1,2,3", []int{1, 2, 3}, false},
|
{"1,2,3", []int{1, 2, 3}, false},
|
||||||
{"1,2,", []int{}, true},
|
{"1,2,", []int{}, true},
|
||||||
|
{"T", []int{2, 3}, false},
|
||||||
|
{"T,2,3", []int{2, 3}, false},
|
||||||
|
{"[a-z,4,5", []int{4, 5}, true}, // invalid regexp
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
testname := fmt.Sprintf("PrepareColumns-%s-%t", tt.input, tt.wanterror)
|
testname := fmt.Sprintf("PrepareColumns-%s-%t", tt.input, tt.wanterror)
|
||||||
t.Run(testname, func(t *testing.T) {
|
t.Run(testname, func(t *testing.T) {
|
||||||
Columns = tt.input
|
c := cfg.Config{Columns: tt.input}
|
||||||
err := PrepareColumns()
|
err := PrepareColumns(&c, &data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !tt.wanterror {
|
if !tt.wanterror {
|
||||||
t.Errorf("got error: %v", err)
|
t.Errorf("got error: %v", err)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if !reflect.DeepEqual(UseColumns, tt.exp) {
|
if !reflect.DeepEqual(c.UseColumns, tt.exp) {
|
||||||
t.Errorf("got: %v, expected: %v", UseColumns, tt.exp)
|
t.Errorf("got: %v, expected: %v", c.UseColumns, tt.exp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReduceColumns(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
expect [][]string
|
||||||
|
columns []int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
expect: [][]string{{"a", "b"}},
|
||||||
|
columns: []int{1, 2},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
expect: [][]string{{"a", "c"}},
|
||||||
|
columns: []int{1, 3},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
expect: [][]string{{"a"}},
|
||||||
|
columns: []int{1},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
expect: [][]string{nil},
|
||||||
|
columns: []int{4},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
input := [][]string{{"a", "b", "c"}}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("reduce-columns-by-%+v", tt.columns)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := cfg.Config{Columns: "x", UseColumns: tt.columns}
|
||||||
|
data := Tabdata{entries: input}
|
||||||
|
reduceColumns(c, &data)
|
||||||
|
if !reflect.DeepEqual(data.entries, tt.expect) {
|
||||||
|
t.Errorf("reduceColumns returned invalid data:\ngot: %+v\nexp: %+v", data.entries, tt.expect)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNumberizeHeaders(t *testing.T) {
|
||||||
|
data := Tabdata{
|
||||||
|
headers: []string{"ONE", "TWO", "THREE"},
|
||||||
|
}
|
||||||
|
|
||||||
|
var tests = []struct {
|
||||||
|
expect []string
|
||||||
|
columns []int
|
||||||
|
nonum bool
|
||||||
|
}{
|
||||||
|
{[]string{"ONE(1)", "TWO(2)", "THREE(3)"}, []int{1, 2, 3}, false},
|
||||||
|
{[]string{"ONE(1)", "TWO(2)"}, []int{1, 2}, false},
|
||||||
|
{[]string{"ONE", "TWO"}, []int{1, 2}, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("numberize-headers-columns-%+v-nonum-%t", tt.columns, tt.nonum)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := cfg.Config{Columns: "x", UseColumns: tt.columns, NoNumbering: tt.nonum}
|
||||||
|
usedata := data
|
||||||
|
numberizeAndReduceHeaders(c, &usedata)
|
||||||
|
if !reflect.DeepEqual(usedata.headers, tt.expect) {
|
||||||
|
t.Errorf("numberizeAndReduceHeaders returned invalid data:\ngot: %+v\nexp: %+v",
|
||||||
|
usedata.headers, tt.expect)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
35
lib/io.go
35
lib/io.go
@@ -19,25 +19,51 @@ package lib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"github.com/gookit/color"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ProcessFiles(args []string) error {
|
func ProcessFiles(c cfg.Config, args []string) error {
|
||||||
fds, pattern, err := determineIO(args)
|
fds, pattern, err := determineIO(&c, args)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
determineColormode(&c)
|
||||||
|
|
||||||
for _, fd := range fds {
|
for _, fd := range fds {
|
||||||
printData(parseFile(fd, pattern))
|
data, err := parseFile(c, fd, pattern)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = PrepareColumns(&c, &data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
printData(os.Stdout, c, &data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func determineIO(args []string) ([]io.Reader, string, error) {
|
// find supported color mode, modifies config based on constants
|
||||||
|
func determineColormode(c *cfg.Config) {
|
||||||
|
if !isTerminal(os.Stdout) {
|
||||||
|
color.Disable()
|
||||||
|
} else {
|
||||||
|
level := color.TermColorLevel()
|
||||||
|
colors := cfg.Colors()
|
||||||
|
c.MatchFG = colors[level]["fg"]
|
||||||
|
c.MatchBG = colors[level]["bg"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func determineIO(c *cfg.Config, args []string) ([]io.Reader, string, error) {
|
||||||
var pattern string
|
var pattern string
|
||||||
var fds []io.Reader
|
var fds []io.Reader
|
||||||
var havefiles bool
|
var havefiles bool
|
||||||
@@ -48,6 +74,7 @@ func determineIO(args []string) ([]io.Reader, string, error) {
|
|||||||
// first one is not a file, consider it as regexp and
|
// first one is not a file, consider it as regexp and
|
||||||
// shift arg list
|
// shift arg list
|
||||||
pattern = args[0]
|
pattern = args[0]
|
||||||
|
c.Pattern = args[0] // used for colorization by printData()
|
||||||
args = args[1:]
|
args = args[1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,58 +19,38 @@ package lib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/alecthomas/repr"
|
"github.com/alecthomas/repr"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"io"
|
"io"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// contains a whole parsed table
|
|
||||||
type Tabdata struct {
|
|
||||||
maxwidthHeader int // longest header
|
|
||||||
maxwidthPerCol []int // max width per column
|
|
||||||
columns int
|
|
||||||
headerIndices []map[string]int // [ {beg=>0, end=>17}, ... ]
|
|
||||||
headers []string // [ "ID", "NAME", ...]
|
|
||||||
entries [][]string
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Parse tabular input. We split the header (first line) by 2 or more
|
Parse tabular input.
|
||||||
spaces, remember the positions of the header fields. We then split
|
|
||||||
the data (everything after the first line) by those positions. That
|
|
||||||
way we can turn "tabular data" (with fields containing whitespaces)
|
|
||||||
into real tabular data. We re-tabulate our input if you will.
|
|
||||||
*/
|
*/
|
||||||
func parseFile(input io.Reader, pattern string) Tabdata {
|
func parseFile(c cfg.Config, input io.Reader, pattern string) (Tabdata, error) {
|
||||||
data := Tabdata{}
|
data := Tabdata{}
|
||||||
|
|
||||||
var scanner *bufio.Scanner
|
var scanner *bufio.Scanner
|
||||||
var spaces = `\s\s+|$`
|
|
||||||
|
|
||||||
if len(Separator) > 0 {
|
|
||||||
spaces = Separator
|
|
||||||
}
|
|
||||||
|
|
||||||
hadFirst := false
|
hadFirst := false
|
||||||
spacefinder := regexp.MustCompile(spaces)
|
separate := regexp.MustCompile(c.Separator)
|
||||||
beg := 0
|
patternR, err := regexp.Compile(pattern)
|
||||||
|
if err != nil {
|
||||||
|
return data, errors.Unwrap(fmt.Errorf("Regexp pattern %s is invalid: %w", pattern, err))
|
||||||
|
}
|
||||||
|
|
||||||
scanner = bufio.NewScanner(input)
|
scanner = bufio.NewScanner(input)
|
||||||
|
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
line := strings.TrimSpace(scanner.Text())
|
line := strings.TrimSpace(scanner.Text())
|
||||||
values := []string{}
|
parts := separate.Split(line, -1)
|
||||||
|
|
||||||
patternR, err := regexp.Compile(pattern)
|
|
||||||
if err != nil {
|
|
||||||
die(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !hadFirst {
|
if !hadFirst {
|
||||||
// header processing
|
// header processing
|
||||||
parts := spacefinder.FindAllStringIndex(line, -1)
|
|
||||||
data.columns = len(parts)
|
data.columns = len(parts)
|
||||||
// if Debug {
|
// if Debug {
|
||||||
// fmt.Println(parts)
|
// fmt.Println(parts)
|
||||||
@@ -82,30 +62,14 @@ func parseFile(input io.Reader, pattern string) Tabdata {
|
|||||||
// fmt.Printf("Part: <%s>\n", string(line[beg:part[0]]))
|
// fmt.Printf("Part: <%s>\n", string(line[beg:part[0]]))
|
||||||
//}
|
//}
|
||||||
|
|
||||||
// current field
|
|
||||||
head := string(line[beg:part[0]])
|
|
||||||
|
|
||||||
// register begin and end of field within line
|
|
||||||
indices := make(map[string]int)
|
|
||||||
indices["beg"] = beg
|
|
||||||
if part[0] == part[1] {
|
|
||||||
indices["end"] = 0
|
|
||||||
} else {
|
|
||||||
indices["end"] = part[1] - 1
|
|
||||||
}
|
|
||||||
|
|
||||||
// register widest header field
|
// register widest header field
|
||||||
headerlen := len(head)
|
headerlen := len(part)
|
||||||
if headerlen > data.maxwidthHeader {
|
if headerlen > data.maxwidthHeader {
|
||||||
data.maxwidthHeader = headerlen
|
data.maxwidthHeader = headerlen
|
||||||
}
|
}
|
||||||
|
|
||||||
// register fields data
|
// register fields data
|
||||||
data.headerIndices = append(data.headerIndices, indices)
|
data.headers = append(data.headers, strings.TrimSpace(part))
|
||||||
data.headers = append(data.headers, head)
|
|
||||||
|
|
||||||
// end of current field == begin of next one
|
|
||||||
beg = part[1]
|
|
||||||
|
|
||||||
// done
|
// done
|
||||||
hadFirst = true
|
hadFirst = true
|
||||||
@@ -113,22 +77,19 @@ func parseFile(input io.Reader, pattern string) Tabdata {
|
|||||||
} else {
|
} else {
|
||||||
// data processing
|
// data processing
|
||||||
if len(pattern) > 0 {
|
if len(pattern) > 0 {
|
||||||
if !patternR.MatchString(line) {
|
if patternR.MatchString(line) == c.InvertMatch {
|
||||||
|
// by default -v is false, so if a line does NOT
|
||||||
|
// match the pattern, we will ignore it. However,
|
||||||
|
// if the user specified -v, the matching is inverted,
|
||||||
|
// so we ignore all lines, which DO match.
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
idx := 0 // we cannot use the header index, because we could exclude columns
|
idx := 0 // we cannot use the header index, because we could exclude columns
|
||||||
for _, index := range data.headerIndices {
|
values := []string{}
|
||||||
value := ""
|
for _, part := range parts {
|
||||||
|
width := len(strings.TrimSpace(part))
|
||||||
if index["end"] == 0 {
|
|
||||||
value = string(line[index["beg"]:])
|
|
||||||
} else {
|
|
||||||
value = string(line[index["beg"]:index["end"]])
|
|
||||||
}
|
|
||||||
|
|
||||||
width := len(strings.TrimSpace(value))
|
|
||||||
|
|
||||||
if len(data.maxwidthPerCol)-1 < idx {
|
if len(data.maxwidthPerCol)-1 < idx {
|
||||||
data.maxwidthPerCol = append(data.maxwidthPerCol, width)
|
data.maxwidthPerCol = append(data.maxwidthPerCol, width)
|
||||||
@@ -141,24 +102,27 @@ func parseFile(input io.Reader, pattern string) Tabdata {
|
|||||||
// if Debug {
|
// if Debug {
|
||||||
// fmt.Printf("<%s> ", value)
|
// fmt.Printf("<%s> ", value)
|
||||||
// }
|
// }
|
||||||
values = append(values, strings.TrimSpace(value))
|
values = append(values, strings.TrimSpace(part))
|
||||||
|
|
||||||
idx++
|
idx++
|
||||||
}
|
}
|
||||||
if Debug {
|
|
||||||
fmt.Println()
|
// fill up missing fields, if any
|
||||||
|
for i := len(values); i < len(data.headers); i++ {
|
||||||
|
values = append(values, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
data.entries = append(data.entries, values)
|
data.entries = append(data.entries, values)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if scanner.Err() != nil {
|
if scanner.Err() != nil {
|
||||||
die(scanner.Err())
|
return data, errors.Unwrap(fmt.Errorf("Failed to read from io.Reader: %w", scanner.Err()))
|
||||||
}
|
}
|
||||||
|
|
||||||
if Debug {
|
if c.Debug {
|
||||||
repr.Print(data)
|
repr.Print(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
return data
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||||||
package lib
|
package lib
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -27,40 +29,18 @@ func TestParser(t *testing.T) {
|
|||||||
data := Tabdata{
|
data := Tabdata{
|
||||||
maxwidthHeader: 5,
|
maxwidthHeader: 5,
|
||||||
maxwidthPerCol: []int{
|
maxwidthPerCol: []int{
|
||||||
5,
|
5, 5, 8,
|
||||||
5,
|
|
||||||
8,
|
|
||||||
},
|
},
|
||||||
columns: 3,
|
columns: 3,
|
||||||
headerIndices: []map[string]int{
|
|
||||||
map[string]int{
|
|
||||||
"beg": 0,
|
|
||||||
"end": 6,
|
|
||||||
},
|
|
||||||
map[string]int{
|
|
||||||
"end": 13,
|
|
||||||
"beg": 7,
|
|
||||||
},
|
|
||||||
map[string]int{
|
|
||||||
"beg": 14,
|
|
||||||
"end": 0,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
headers: []string{
|
headers: []string{
|
||||||
"ONE",
|
"ONE", "TWO", "THREE",
|
||||||
"TWO",
|
|
||||||
"THREE",
|
|
||||||
},
|
},
|
||||||
entries: [][]string{
|
entries: [][]string{
|
||||||
[]string{
|
{
|
||||||
"asd",
|
"asd", "igig", "cxxxncnc",
|
||||||
"igig",
|
|
||||||
"cxxxncnc",
|
|
||||||
},
|
},
|
||||||
[]string{
|
{
|
||||||
"19191",
|
"19191", "EDD 1", "X",
|
||||||
"EDD 1",
|
|
||||||
"X",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -70,8 +50,114 @@ asd igig cxxxncnc
|
|||||||
19191 EDD 1 X`
|
19191 EDD 1 X`
|
||||||
|
|
||||||
readFd := strings.NewReader(table)
|
readFd := strings.NewReader(table)
|
||||||
gotdata := parseFile(readFd, "")
|
c := cfg.Config{Separator: cfg.DefaultSeparator}
|
||||||
|
gotdata, err := parseFile(c, readFd, "")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Parser returned error: %s\nData processed so far: %+v", err, gotdata)
|
||||||
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(data, gotdata) {
|
if !reflect.DeepEqual(data, gotdata) {
|
||||||
t.Errorf("Parser returned invalid data\nExp: %+v\nGot: %+v\n", data, gotdata)
|
t.Errorf("Parser returned invalid data, Regex: %s\nExp: %+v\nGot: %+v\n", c.Separator, data, gotdata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParserPatternmatching(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
entries [][]string
|
||||||
|
pattern string
|
||||||
|
invert bool
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
entries: [][]string{
|
||||||
|
{
|
||||||
|
"asd", "igig", "cxxxncnc",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pattern: "ig",
|
||||||
|
invert: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
entries: [][]string{
|
||||||
|
{
|
||||||
|
"19191", "EDD 1", "X",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pattern: "ig",
|
||||||
|
invert: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
entries: [][]string{
|
||||||
|
{
|
||||||
|
"asd", "igig", "cxxxncnc",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pattern: "[a-z",
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
table := `ONE TWO THREE
|
||||||
|
asd igig cxxxncnc
|
||||||
|
19191 EDD 1 X`
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("parse-with-pattern-%s-inverted-%t", tt.pattern, tt.invert)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := cfg.Config{InvertMatch: tt.invert, Pattern: tt.pattern, Separator: cfg.DefaultSeparator}
|
||||||
|
|
||||||
|
readFd := strings.NewReader(table)
|
||||||
|
gotdata, err := parseFile(c, readFd, tt.pattern)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if !tt.want {
|
||||||
|
t.Errorf("Parser returned error: %s\nData processed so far: %+v", err, gotdata)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if !reflect.DeepEqual(tt.entries, gotdata.entries) {
|
||||||
|
t.Errorf("Parser returned invalid data (pattern: %s, invert: %t)\nExp: %+v\nGot: %+v\n",
|
||||||
|
tt.pattern, tt.invert, tt.entries, gotdata.entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParserIncompleteRows(t *testing.T) {
|
||||||
|
data := Tabdata{
|
||||||
|
maxwidthHeader: 5,
|
||||||
|
maxwidthPerCol: []int{
|
||||||
|
5, 5, 1,
|
||||||
|
},
|
||||||
|
columns: 3,
|
||||||
|
headers: []string{
|
||||||
|
"ONE", "TWO", "THREE",
|
||||||
|
},
|
||||||
|
entries: [][]string{
|
||||||
|
{
|
||||||
|
"asd", "igig", "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"19191", "EDD 1", "X",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
table := `ONE TWO THREE
|
||||||
|
asd igig
|
||||||
|
19191 EDD 1 X`
|
||||||
|
|
||||||
|
readFd := strings.NewReader(table)
|
||||||
|
c := cfg.Config{Separator: cfg.DefaultSeparator}
|
||||||
|
gotdata, err := parseFile(c, readFd, "")
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("Parser returned error: %s\nData processed so far: %+v", err, gotdata)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !reflect.DeepEqual(data, gotdata) {
|
||||||
|
t.Errorf("Parser returned invalid data, Regex: %s\nExp: %+v\nGot: %+v\n",
|
||||||
|
c.Separator, data, gotdata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
174
lib/printer.go
174
lib/printer.go
@@ -19,74 +19,55 @@ package lib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/gookit/color"
|
||||||
"github.com/olekukonko/tablewriter"
|
"github.com/olekukonko/tablewriter"
|
||||||
"os"
|
"github.com/tlinden/tablizer/cfg"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func printData(data Tabdata) {
|
func printData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
// prepare headers
|
// some output preparations:
|
||||||
// FIXME: maybe do this already in parseFile()?
|
|
||||||
if !NoNumbering {
|
|
||||||
numberedHeaders := []string{}
|
|
||||||
for i, head := range data.headers {
|
|
||||||
if len(Columns) > 0 {
|
|
||||||
if !contains(UseColumns, i+1) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
numberedHeaders = append(numberedHeaders, fmt.Sprintf("%s(%d)", head, i+1))
|
|
||||||
}
|
|
||||||
data.headers = numberedHeaders
|
|
||||||
}
|
|
||||||
|
|
||||||
// prepare data
|
// add numbers to headers and remove this we're not interested in
|
||||||
if len(Columns) > 0 {
|
numberizeAndReduceHeaders(c, data)
|
||||||
reducedEntries := [][]string{}
|
|
||||||
reducedEntry := []string{}
|
|
||||||
for _, entry := range data.entries {
|
|
||||||
reducedEntry = nil
|
|
||||||
for i, value := range entry {
|
|
||||||
if !contains(UseColumns, i+1) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
reducedEntry = append(reducedEntry, value)
|
// remove unwanted columns, if any
|
||||||
}
|
reduceColumns(c, data)
|
||||||
reducedEntries = append(reducedEntries, reducedEntry)
|
|
||||||
}
|
|
||||||
data.entries = reducedEntries
|
|
||||||
}
|
|
||||||
|
|
||||||
switch OutputMode {
|
// sort the data
|
||||||
|
sortTable(c, data)
|
||||||
|
|
||||||
|
switch c.OutputMode {
|
||||||
case "extended":
|
case "extended":
|
||||||
printExtendedData(data)
|
printExtendedData(w, c, data)
|
||||||
case "ascii":
|
case "ascii":
|
||||||
printAsciiData(data)
|
printAsciiData(w, c, data)
|
||||||
case "orgtbl":
|
case "orgtbl":
|
||||||
printOrgmodeData(data)
|
printOrgmodeData(w, c, data)
|
||||||
case "markdown":
|
case "markdown":
|
||||||
printMarkdownData(data)
|
printMarkdownData(w, c, data)
|
||||||
|
case "shell":
|
||||||
|
printShellData(w, c, data)
|
||||||
|
case "yaml":
|
||||||
|
printYamlData(w, c, data)
|
||||||
default:
|
default:
|
||||||
printAsciiData(data)
|
printAsciiData(w, c, data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func trimRow(row []string) []string {
|
func output(w io.Writer, str string) {
|
||||||
// FIXME: remove this when we only use Tablewriter and strip in ParseFile()!
|
fmt.Fprint(w, str)
|
||||||
var fixedrow []string
|
|
||||||
for _, cell := range row {
|
|
||||||
fixedrow = append(fixedrow, strings.TrimSpace(cell))
|
|
||||||
}
|
|
||||||
|
|
||||||
return fixedrow
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Emacs org-mode compatible table (also orgtbl-mode)
|
Emacs org-mode compatible table (also orgtbl-mode)
|
||||||
*/
|
*/
|
||||||
func printOrgmodeData(data Tabdata) {
|
func printOrgmodeData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
tableString := &strings.Builder{}
|
tableString := &strings.Builder{}
|
||||||
table := tablewriter.NewWriter(tableString)
|
table := tablewriter.NewWriter(tableString)
|
||||||
|
|
||||||
@@ -109,17 +90,21 @@ func printOrgmodeData(data Tabdata) {
|
|||||||
| cell | cell |
|
| cell | cell |
|
||||||
|------+------|
|
|------+------|
|
||||||
*/
|
*/
|
||||||
leftR := regexp.MustCompile("(?m)^\\+")
|
leftR := regexp.MustCompile(`(?m)^\\+`)
|
||||||
rightR := regexp.MustCompile("\\+(?m)$")
|
rightR := regexp.MustCompile(`\\+(?m)$`)
|
||||||
|
|
||||||
fmt.Print(rightR.ReplaceAllString(leftR.ReplaceAllString(tableString.String(), "|"), "|"))
|
output(w, color.Sprint(
|
||||||
|
colorizeData(c,
|
||||||
|
rightR.ReplaceAllString(
|
||||||
|
leftR.ReplaceAllString(tableString.String(), "|"), "|"))))
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Markdown table
|
Markdown table
|
||||||
*/
|
*/
|
||||||
func printMarkdownData(data Tabdata) {
|
func printMarkdownData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
table := tablewriter.NewWriter(os.Stdout)
|
tableString := &strings.Builder{}
|
||||||
|
table := tablewriter.NewWriter(tableString)
|
||||||
|
|
||||||
table.SetHeader(data.headers)
|
table.SetHeader(data.headers)
|
||||||
|
|
||||||
@@ -131,13 +116,15 @@ func printMarkdownData(data Tabdata) {
|
|||||||
table.SetCenterSeparator("|")
|
table.SetCenterSeparator("|")
|
||||||
|
|
||||||
table.Render()
|
table.Render()
|
||||||
|
output(w, color.Sprint(colorizeData(c, tableString.String())))
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Simple ASCII table without any borders etc, just like the input we expect
|
Simple ASCII table without any borders etc, just like the input we expect
|
||||||
*/
|
*/
|
||||||
func printAsciiData(data Tabdata) {
|
func printAsciiData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
table := tablewriter.NewWriter(os.Stdout)
|
tableString := &strings.Builder{}
|
||||||
|
table := tablewriter.NewWriter(tableString)
|
||||||
|
|
||||||
table.SetHeader(data.headers)
|
table.SetHeader(data.headers)
|
||||||
table.AppendBulk(data.entries)
|
table.AppendBulk(data.entries)
|
||||||
@@ -159,30 +146,81 @@ func printAsciiData(data Tabdata) {
|
|||||||
table.SetNoWhiteSpace(true)
|
table.SetNoWhiteSpace(true)
|
||||||
|
|
||||||
table.Render()
|
table.Render()
|
||||||
|
output(w, color.Sprint(colorizeData(c, tableString.String())))
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
We simulate the \x command of psql (the PostgreSQL client)
|
We simulate the \x command of psql (the PostgreSQL client)
|
||||||
*/
|
*/
|
||||||
func printExtendedData(data Tabdata) {
|
func printExtendedData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
// needed for data output
|
// needed for data output
|
||||||
format := fmt.Sprintf("%%%ds: %%s\n", data.maxwidthHeader) // FIXME: re-calculate if -c has been set
|
format := fmt.Sprintf("%%%ds: %%s\n", data.maxwidthHeader)
|
||||||
|
out := ""
|
||||||
if len(data.entries) > 0 {
|
if len(data.entries) > 0 {
|
||||||
var idx int
|
|
||||||
for _, entry := range data.entries {
|
for _, entry := range data.entries {
|
||||||
idx = 0
|
|
||||||
for i, value := range entry {
|
for i, value := range entry {
|
||||||
if len(Columns) > 0 {
|
out += color.Sprintf(format, data.headers[i], value)
|
||||||
if !contains(UseColumns, i+1) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fmt.Printf(format, data.headers[idx], value)
|
|
||||||
idx++
|
|
||||||
}
|
}
|
||||||
fmt.Println()
|
|
||||||
|
out += "\n"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
output(w, colorizeData(c, out))
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Shell output, ready to be eval'd. Just like FreeBSD stat(1)
|
||||||
|
*/
|
||||||
|
func printShellData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
|
out := ""
|
||||||
|
if len(data.entries) > 0 {
|
||||||
|
for _, entry := range data.entries {
|
||||||
|
shentries := []string{}
|
||||||
|
for i, value := range entry {
|
||||||
|
shentries = append(shentries, fmt.Sprintf("%s=\"%s\"",
|
||||||
|
data.headers[i], value))
|
||||||
|
}
|
||||||
|
out += fmt.Sprint(strings.Join(shentries, " ")) + "\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// no colrization here
|
||||||
|
output(w, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printYamlData(w io.Writer, c cfg.Config, data *Tabdata) {
|
||||||
|
type D struct {
|
||||||
|
Entries []map[string]interface{} `yaml:"entries"`
|
||||||
|
}
|
||||||
|
|
||||||
|
d := D{}
|
||||||
|
|
||||||
|
for _, entry := range data.entries {
|
||||||
|
ml := map[string]interface{}{}
|
||||||
|
|
||||||
|
for i, entry := range entry {
|
||||||
|
style := yaml.TaggedStyle
|
||||||
|
_, err := strconv.Atoi(entry)
|
||||||
|
if err != nil {
|
||||||
|
style = yaml.DoubleQuotedStyle
|
||||||
|
}
|
||||||
|
|
||||||
|
ml[strings.ToLower(data.headers[i])] =
|
||||||
|
&yaml.Node{
|
||||||
|
Kind: yaml.ScalarNode,
|
||||||
|
Style: style,
|
||||||
|
Value: entry}
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Entries = append(d.Entries, ml)
|
||||||
|
}
|
||||||
|
|
||||||
|
yamlstr, err := yaml.Marshal(&d)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
output(w, string(yamlstr))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,59 +18,271 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||||||
package lib
|
package lib
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
//"github.com/alecthomas/repr"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestPrinter(t *testing.T) {
|
func newData() Tabdata {
|
||||||
table := `ONE TWO THREE
|
return Tabdata{
|
||||||
asd igig cxxxncnc
|
maxwidthHeader: 8,
|
||||||
19191 EDD 1 X`
|
maxwidthPerCol: []int{
|
||||||
|
5,
|
||||||
expects := map[string]string{
|
9,
|
||||||
"ascii": `ONE(1) TWO(2) THREE(3)
|
3,
|
||||||
asd igig cxxxncnc
|
26,
|
||||||
19191 EDD 1 X`,
|
},
|
||||||
"orgtbl": `|--------+--------+----------|
|
columns: 4,
|
||||||
| ONE(1) | TWO(2) | THREE(3) |
|
headers: []string{
|
||||||
|--------+--------+----------|
|
"NAME",
|
||||||
| asd | igig | cxxxncnc |
|
"DURATION",
|
||||||
| 19191 | EDD 1 | X |
|
"COUNT",
|
||||||
|--------+--------+----------|`,
|
"WHEN",
|
||||||
"markdown": `| ONE(1) | TWO(2) | THREE(3) |
|
},
|
||||||
|--------|--------|----------|
|
entries: [][]string{
|
||||||
| asd | igig | cxxxncnc |
|
{
|
||||||
| 19191 | EDD 1 | X |`,
|
"beta",
|
||||||
|
"1d10h5m1s",
|
||||||
|
"33",
|
||||||
|
"3/1/2014",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"alpha",
|
||||||
|
"4h35m",
|
||||||
|
"170",
|
||||||
|
"2013-Feb-03",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ceta",
|
||||||
|
"33d12h",
|
||||||
|
"9",
|
||||||
|
"06/Jan/2008 15:04:05 -0700",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var tests = []struct {
|
||||||
|
name string // so we can identify which one fails, can be the same
|
||||||
|
// for multiple tests, because flags will be appended to the name
|
||||||
|
sortby string // empty == default
|
||||||
|
column int // sort by this column, 0 == default first or NO Sort
|
||||||
|
desc bool // sort in descending order, default == ascending
|
||||||
|
nonum bool // hide numbering
|
||||||
|
mode string // shell, orgtbl, etc. empty == default: ascii
|
||||||
|
usecol []int // columns to display, empty == display all
|
||||||
|
usecolstr string // for testname, must match usecol
|
||||||
|
expect string // rendered output we expect
|
||||||
|
}{
|
||||||
|
// --------------------- Default settings mode tests ``
|
||||||
|
{
|
||||||
|
mode: "ascii",
|
||||||
|
name: "default",
|
||||||
|
expect: `
|
||||||
|
NAME(1) DURATION(2) COUNT(3) WHEN(4)
|
||||||
|
beta 1d10h5m1s 33 3/1/2014
|
||||||
|
alpha 4h35m 170 2013-Feb-03
|
||||||
|
ceta 33d12h 9 06/Jan/2008 15:04:05 -0700`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
mode: "orgtbl",
|
||||||
|
expect: `
|
||||||
|
+---------+-------------+----------+----------------------------+
|
||||||
|
| NAME(1) | DURATION(2) | COUNT(3) | WHEN(4) |
|
||||||
|
+---------+-------------+----------+----------------------------+
|
||||||
|
| beta | 1d10h5m1s | 33 | 3/1/2014 |
|
||||||
|
| alpha | 4h35m | 170 | 2013-Feb-03 |
|
||||||
|
| ceta | 33d12h | 9 | 06/Jan/2008 15:04:05 -0700 |
|
||||||
|
+---------+-------------+----------+----------------------------+`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
mode: "markdown",
|
||||||
|
expect: `
|
||||||
|
| NAME(1) | DURATION(2) | COUNT(3) | WHEN(4) |
|
||||||
|
|---------|-------------|----------|----------------------------|
|
||||||
|
| beta | 1d10h5m1s | 33 | 3/1/2014 |
|
||||||
|
| alpha | 4h35m | 170 | 2013-Feb-03 |
|
||||||
|
| ceta | 33d12h | 9 | 06/Jan/2008 15:04:05 -0700 |`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
mode: "shell",
|
||||||
|
nonum: true,
|
||||||
|
expect: `
|
||||||
|
NAME="beta" DURATION="1d10h5m1s" COUNT="33" WHEN="3/1/2014"
|
||||||
|
NAME="alpha" DURATION="4h35m" COUNT="170" WHEN="2013-Feb-03"
|
||||||
|
NAME="ceta" DURATION="33d12h" COUNT="9" WHEN="06/Jan/2008 15:04:05 -0700"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
mode: "yaml",
|
||||||
|
nonum: true,
|
||||||
|
expect: `
|
||||||
|
entries:
|
||||||
|
- count: 33
|
||||||
|
duration: "1d10h5m1s"
|
||||||
|
name: "beta"
|
||||||
|
when: "3/1/2014"
|
||||||
|
- count: 170
|
||||||
|
duration: "4h35m"
|
||||||
|
name: "alpha"
|
||||||
|
when: "2013-Feb-03"
|
||||||
|
- count: 9
|
||||||
|
duration: "33d12h"
|
||||||
|
name: "ceta"
|
||||||
|
when: "06/Jan/2008 15:04:05 -0700"`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "default",
|
||||||
|
mode: "extended",
|
||||||
|
expect: `
|
||||||
|
NAME(1): beta
|
||||||
|
DURATION(2): 1d10h5m1s
|
||||||
|
COUNT(3): 33
|
||||||
|
WHEN(4): 3/1/2014
|
||||||
|
|
||||||
|
NAME(1): alpha
|
||||||
|
DURATION(2): 4h35m
|
||||||
|
COUNT(3): 170
|
||||||
|
WHEN(4): 2013-Feb-03
|
||||||
|
|
||||||
|
NAME(1): ceta
|
||||||
|
DURATION(2): 33d12h
|
||||||
|
COUNT(3): 9
|
||||||
|
WHEN(4): 06/Jan/2008 15:04:05 -0700`,
|
||||||
|
},
|
||||||
|
|
||||||
|
//------------------------ SORT TESTS
|
||||||
|
{
|
||||||
|
name: "sortbycolumn",
|
||||||
|
column: 3,
|
||||||
|
sortby: "numeric",
|
||||||
|
desc: false,
|
||||||
|
expect: `
|
||||||
|
NAME(1) DURATION(2) COUNT(3) WHEN(4)
|
||||||
|
ceta 33d12h 9 06/Jan/2008 15:04:05 -0700
|
||||||
|
beta 1d10h5m1s 33 3/1/2014
|
||||||
|
alpha 4h35m 170 2013-Feb-03`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sortbycolumn",
|
||||||
|
column: 4,
|
||||||
|
sortby: "time",
|
||||||
|
desc: false,
|
||||||
|
expect: `
|
||||||
|
NAME(1) DURATION(2) COUNT(3) WHEN(4)
|
||||||
|
ceta 33d12h 9 06/Jan/2008 15:04:05 -0700
|
||||||
|
alpha 4h35m 170 2013-Feb-03
|
||||||
|
beta 1d10h5m1s 33 3/1/2014`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sortbycolumn",
|
||||||
|
column: 2,
|
||||||
|
sortby: "duration",
|
||||||
|
desc: false,
|
||||||
|
expect: `
|
||||||
|
NAME(1) DURATION(2) COUNT(3) WHEN(4)
|
||||||
|
alpha 4h35m 170 2013-Feb-03
|
||||||
|
beta 1d10h5m1s 33 3/1/2014
|
||||||
|
ceta 33d12h 9 06/Jan/2008 15:04:05 -0700`,
|
||||||
|
},
|
||||||
|
|
||||||
|
// ----------------------- UseColumns Tests
|
||||||
|
{
|
||||||
|
name: "usecolumns",
|
||||||
|
usecol: []int{1, 4},
|
||||||
|
usecolstr: "1,4",
|
||||||
|
expect: `
|
||||||
|
NAME(1) WHEN(4)
|
||||||
|
beta 3/1/2014
|
||||||
|
alpha 2013-Feb-03
|
||||||
|
ceta 06/Jan/2008 15:04:05 -0700`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "usecolumns",
|
||||||
|
usecol: []int{2},
|
||||||
|
usecolstr: "2",
|
||||||
|
expect: `
|
||||||
|
DURATION(2)
|
||||||
|
1d10h5m1s
|
||||||
|
4h35m
|
||||||
|
33d12h`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "usecolumns",
|
||||||
|
usecol: []int{3},
|
||||||
|
usecolstr: "3",
|
||||||
|
expect: `
|
||||||
|
COUNT(3)
|
||||||
|
33
|
||||||
|
170
|
||||||
|
9`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "usecolumns",
|
||||||
|
column: 0,
|
||||||
|
usecol: []int{1, 3},
|
||||||
|
usecolstr: "1,3",
|
||||||
|
expect: `
|
||||||
|
NAME(1) COUNT(3)
|
||||||
|
beta 33
|
||||||
|
alpha 170
|
||||||
|
ceta 9`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "usecolumns",
|
||||||
|
usecol: []int{2, 4},
|
||||||
|
usecolstr: "2,4",
|
||||||
|
expect: `
|
||||||
|
DURATION(2) WHEN(4)
|
||||||
|
1d10h5m1s 3/1/2014
|
||||||
|
4h35m 2013-Feb-03
|
||||||
|
33d12h 06/Jan/2008 15:04:05 -0700`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrinter(t *testing.T) {
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("print-sortcol-%d-desc-%t-sortby-%s-mode-%s-usecolumns-%s",
|
||||||
|
tt.column, tt.desc, tt.sortby, tt.mode, tt.usecolstr)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
// replaces os.Stdout, but we ignore it
|
||||||
|
var w bytes.Buffer
|
||||||
|
|
||||||
|
// cmd flags
|
||||||
|
c := cfg.Config{
|
||||||
|
SortByColumn: tt.column,
|
||||||
|
SortDescending: tt.desc,
|
||||||
|
SortMode: tt.sortby,
|
||||||
|
OutputMode: tt.mode,
|
||||||
|
NoNumbering: tt.nonum,
|
||||||
|
UseColumns: tt.usecol,
|
||||||
|
NoColor: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// the test checks the len!
|
||||||
|
if len(tt.usecol) > 0 {
|
||||||
|
c.Columns = "yes"
|
||||||
|
} else {
|
||||||
|
c.Columns = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
testdata := newData()
|
||||||
|
exp := strings.TrimSpace(tt.expect)
|
||||||
|
|
||||||
|
printData(&w, c, &testdata)
|
||||||
|
|
||||||
|
got := strings.TrimSpace(w.String())
|
||||||
|
|
||||||
|
if got != exp {
|
||||||
|
t.Errorf("not rendered correctly:\n+++ got:\n%s\n+++ want:\n%s",
|
||||||
|
got, exp)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
r, w, err := os.Pipe()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
origStdout := os.Stdout
|
|
||||||
os.Stdout = w
|
|
||||||
|
|
||||||
for mode, expect := range expects {
|
|
||||||
OutputMode = mode
|
|
||||||
fd := strings.NewReader(table)
|
|
||||||
data := parseFile(fd, "")
|
|
||||||
printData(data)
|
|
||||||
|
|
||||||
buf := make([]byte, 1024)
|
|
||||||
n, err := r.Read(buf)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
buf = buf[:n]
|
|
||||||
output := strings.TrimSpace(string(buf))
|
|
||||||
|
|
||||||
if output != expect {
|
|
||||||
t.Errorf("output mode: %s, got:\n%s\nwant:\n%s\n (%d <=> %d)", mode, output, expect, len(output), len(expect))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore
|
|
||||||
os.Stdout = origStdout
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
121
lib/sort.go
Normal file
121
lib/sort.go
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
/*
|
||||||
|
Copyright © 2022 Thomas von Dein
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package lib
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/araddon/dateparse"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sortTable(c cfg.Config, data *Tabdata) {
|
||||||
|
if c.SortByColumn <= 0 {
|
||||||
|
// no sorting wanted
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// slightly modified here to match internal array indicies
|
||||||
|
col := c.SortByColumn
|
||||||
|
|
||||||
|
col-- // ui starts counting by 1, but use 0 internally
|
||||||
|
|
||||||
|
// sanity checks
|
||||||
|
if len(data.entries) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if col >= len(data.headers) {
|
||||||
|
// fall back to default column
|
||||||
|
col = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// actual sorting
|
||||||
|
sort.SliceStable(data.entries, func(i, j int) bool {
|
||||||
|
return compare(&c, data.entries[i][col], data.entries[j][col])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// config is not modified here, but it would be inefficient to copy it every loop
|
||||||
|
func compare(c *cfg.Config, a string, b string) bool {
|
||||||
|
var comp bool
|
||||||
|
|
||||||
|
switch c.SortMode {
|
||||||
|
case "numeric":
|
||||||
|
left, err := strconv.Atoi(a)
|
||||||
|
if err != nil {
|
||||||
|
left = 0
|
||||||
|
}
|
||||||
|
right, err := strconv.Atoi(b)
|
||||||
|
if err != nil {
|
||||||
|
right = 0
|
||||||
|
}
|
||||||
|
comp = left < right
|
||||||
|
case "duration":
|
||||||
|
left := duration2int(a)
|
||||||
|
right := duration2int(b)
|
||||||
|
comp = left < right
|
||||||
|
case "time":
|
||||||
|
left, _ := dateparse.ParseAny(a)
|
||||||
|
right, _ := dateparse.ParseAny(b)
|
||||||
|
comp = left.Unix() < right.Unix()
|
||||||
|
default:
|
||||||
|
comp = a < b
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.SortDescending {
|
||||||
|
comp = !comp
|
||||||
|
}
|
||||||
|
|
||||||
|
return comp
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
We could use time.ParseDuration(), but this doesn't support days.
|
||||||
|
|
||||||
|
We could also use github.com/xhit/go-str2duration/v2, which does
|
||||||
|
the job, but it's just another dependency, just for this little
|
||||||
|
gem. And we don't need a time.Time value. And int is good enough
|
||||||
|
for duration comparision.
|
||||||
|
|
||||||
|
Convert a durartion into an integer. Valid time units are "s",
|
||||||
|
"m", "h" and "d".
|
||||||
|
*/
|
||||||
|
func duration2int(duration string) int {
|
||||||
|
re := regexp.MustCompile(`(\d+)([dhms])`)
|
||||||
|
seconds := 0
|
||||||
|
|
||||||
|
for _, match := range re.FindAllStringSubmatch(duration, -1) {
|
||||||
|
if len(match) == 3 {
|
||||||
|
v, _ := strconv.Atoi(match[1])
|
||||||
|
switch match[2][0] {
|
||||||
|
case 'd':
|
||||||
|
seconds += v * 86400
|
||||||
|
case 'h':
|
||||||
|
seconds += v * 3600
|
||||||
|
case 'm':
|
||||||
|
seconds += v * 60
|
||||||
|
case 's':
|
||||||
|
seconds += v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return seconds
|
||||||
|
}
|
||||||
79
lib/sort_test.go
Normal file
79
lib/sort_test.go
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
/*
|
||||||
|
Copyright © 2022 Thomas von Dein
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package lib
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/tlinden/tablizer/cfg"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDuration2Seconds(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
dur string
|
||||||
|
expect int
|
||||||
|
}{
|
||||||
|
{"1d", 60 * 60 * 24},
|
||||||
|
{"1h", 60 * 60},
|
||||||
|
{"10m", 60 * 10},
|
||||||
|
{"2h4m10s", (60 * 120) + (4 * 60) + 10},
|
||||||
|
{"88u", 0},
|
||||||
|
{"19t77X what?4s", 4},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("duration-%s", tt.dur)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
seconds := duration2int(tt.dur)
|
||||||
|
if seconds != tt.expect {
|
||||||
|
t.Errorf("got %d, want %d", seconds, tt.expect)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompare(t *testing.T) {
|
||||||
|
var tests = []struct {
|
||||||
|
mode string
|
||||||
|
a string
|
||||||
|
b string
|
||||||
|
want bool
|
||||||
|
desc bool
|
||||||
|
}{
|
||||||
|
// ascending
|
||||||
|
{"numeric", "10", "20", true, false},
|
||||||
|
{"duration", "2d4h5m", "45m", false, false},
|
||||||
|
{"time", "12/24/2022", "1/1/1970", false, false},
|
||||||
|
|
||||||
|
// descending
|
||||||
|
{"numeric", "10", "20", false, true},
|
||||||
|
{"duration", "2d4h5m", "45m", true, true},
|
||||||
|
{"time", "12/24/2022", "1/1/1970", true, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
testname := fmt.Sprintf("compare-mode-%s-a-%s-b-%s-desc-%t", tt.mode, tt.a, tt.b, tt.desc)
|
||||||
|
t.Run(testname, func(t *testing.T) {
|
||||||
|
c := cfg.Config{SortMode: tt.mode, SortDescending: tt.desc}
|
||||||
|
got := compare(&c, tt.a, tt.b)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("got %t, want %t", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
2
main.go
2
main.go
@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"daemon.de/tablizer/cmd"
|
"github.com/tlinden/tablizer/cmd"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|||||||
2
mkrel.sh
2
mkrel.sh
@@ -43,7 +43,7 @@ for D in $DIST; do
|
|||||||
tardir="${tool}-${os}-${arch}-${version}"
|
tardir="${tool}-${os}-${arch}-${version}"
|
||||||
tarfile="releases/${tool}-${os}-${arch}-${version}.tar.gz"
|
tarfile="releases/${tool}-${os}-${arch}-${version}.tar.gz"
|
||||||
set -x
|
set -x
|
||||||
GOOS=${os} GOARCH=${arch} go build -o ${binfile}
|
GOOS=${os} GOARCH=${arch} go build -o ${binfile} -ldflags "-X 'github.com/tlinden/tablizer/lib.VERSION=${version}'"
|
||||||
mkdir -p ${tardir}
|
mkdir -p ${tardir}
|
||||||
cp ${binfile} README.md LICENSE ${tardir}/
|
cp ${binfile} README.md LICENSE ${tardir}/
|
||||||
echo 'tool = tablizer
|
echo 'tool = tablizer
|
||||||
|
|||||||
370
tablizer.1
Normal file
370
tablizer.1
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.42)
|
||||||
|
.\"
|
||||||
|
.\" Standard preamble:
|
||||||
|
.\" ========================================================================
|
||||||
|
.de Sp \" Vertical space (when we can't use .PP)
|
||||||
|
.if t .sp .5v
|
||||||
|
.if n .sp
|
||||||
|
..
|
||||||
|
.de Vb \" Begin verbatim text
|
||||||
|
.ft CW
|
||||||
|
.nf
|
||||||
|
.ne \\$1
|
||||||
|
..
|
||||||
|
.de Ve \" End verbatim text
|
||||||
|
.ft R
|
||||||
|
.fi
|
||||||
|
..
|
||||||
|
.\" Set up some character translations and predefined strings. \*(-- will
|
||||||
|
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
|
||||||
|
.\" double quote, and \*(R" will give a right double quote. \*(C+ will
|
||||||
|
.\" give a nicer C++. Capital omega is used to do unbreakable dashes and
|
||||||
|
.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,
|
||||||
|
.\" nothing in troff, for use with C<>.
|
||||||
|
.tr \(*W-
|
||||||
|
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
|
||||||
|
.ie n \{\
|
||||||
|
. ds -- \(*W-
|
||||||
|
. ds PI pi
|
||||||
|
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
|
||||||
|
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
|
||||||
|
. ds L" ""
|
||||||
|
. ds R" ""
|
||||||
|
. ds C` ""
|
||||||
|
. ds C' ""
|
||||||
|
'br\}
|
||||||
|
.el\{\
|
||||||
|
. ds -- \|\(em\|
|
||||||
|
. ds PI \(*p
|
||||||
|
. ds L" ``
|
||||||
|
. ds R" ''
|
||||||
|
. ds C`
|
||||||
|
. ds C'
|
||||||
|
'br\}
|
||||||
|
.\"
|
||||||
|
.\" Escape single quotes in literal strings from groff's Unicode transform.
|
||||||
|
.ie \n(.g .ds Aq \(aq
|
||||||
|
.el .ds Aq '
|
||||||
|
.\"
|
||||||
|
.\" If the F register is >0, we'll generate index entries on stderr for
|
||||||
|
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
|
||||||
|
.\" entries marked with X<> in POD. Of course, you'll have to process the
|
||||||
|
.\" output yourself in some meaningful fashion.
|
||||||
|
.\"
|
||||||
|
.\" Avoid warning from groff about undefined register 'F'.
|
||||||
|
.de IX
|
||||||
|
..
|
||||||
|
.nr rF 0
|
||||||
|
.if \n(.g .if rF .nr rF 1
|
||||||
|
.if (\n(rF:(\n(.g==0)) \{\
|
||||||
|
. if \nF \{\
|
||||||
|
. de IX
|
||||||
|
. tm Index:\\$1\t\\n%\t"\\$2"
|
||||||
|
..
|
||||||
|
. if !\nF==2 \{\
|
||||||
|
. nr % 0
|
||||||
|
. nr F 2
|
||||||
|
. \}
|
||||||
|
. \}
|
||||||
|
.\}
|
||||||
|
.rr rF
|
||||||
|
.\"
|
||||||
|
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
|
||||||
|
.\" Fear. Run. Save yourself. No user-serviceable parts.
|
||||||
|
. \" fudge factors for nroff and troff
|
||||||
|
.if n \{\
|
||||||
|
. ds #H 0
|
||||||
|
. ds #V .8m
|
||||||
|
. ds #F .3m
|
||||||
|
. ds #[ \f1
|
||||||
|
. ds #] \fP
|
||||||
|
.\}
|
||||||
|
.if t \{\
|
||||||
|
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
|
||||||
|
. ds #V .6m
|
||||||
|
. ds #F 0
|
||||||
|
. ds #[ \&
|
||||||
|
. ds #] \&
|
||||||
|
.\}
|
||||||
|
. \" simple accents for nroff and troff
|
||||||
|
.if n \{\
|
||||||
|
. ds ' \&
|
||||||
|
. ds ` \&
|
||||||
|
. ds ^ \&
|
||||||
|
. ds , \&
|
||||||
|
. ds ~ ~
|
||||||
|
. ds /
|
||||||
|
.\}
|
||||||
|
.if t \{\
|
||||||
|
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
|
||||||
|
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
|
||||||
|
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
|
||||||
|
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
|
||||||
|
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
|
||||||
|
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
|
||||||
|
.\}
|
||||||
|
. \" troff and (daisy-wheel) nroff accents
|
||||||
|
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
|
||||||
|
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
|
||||||
|
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
|
||||||
|
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
|
||||||
|
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
|
||||||
|
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
|
||||||
|
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
|
||||||
|
.ds ae a\h'-(\w'a'u*4/10)'e
|
||||||
|
.ds Ae A\h'-(\w'A'u*4/10)'E
|
||||||
|
. \" corrections for vroff
|
||||||
|
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
|
||||||
|
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
|
||||||
|
. \" for low resolution devices (crt and lpr)
|
||||||
|
.if \n(.H>23 .if \n(.V>19 \
|
||||||
|
\{\
|
||||||
|
. ds : e
|
||||||
|
. ds 8 ss
|
||||||
|
. ds o a
|
||||||
|
. ds d- d\h'-1'\(ga
|
||||||
|
. ds D- D\h'-1'\(hy
|
||||||
|
. ds th \o'bp'
|
||||||
|
. ds Th \o'LP'
|
||||||
|
. ds ae ae
|
||||||
|
. ds Ae AE
|
||||||
|
.\}
|
||||||
|
.rm #[ #] #H #V #F C
|
||||||
|
.\" ========================================================================
|
||||||
|
.\"
|
||||||
|
.IX Title "TABLIZER 1"
|
||||||
|
.TH TABLIZER 1 "2022-10-16" "1" "User Commands"
|
||||||
|
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
|
||||||
|
.\" way too many mistakes in technical documents.
|
||||||
|
.if n .ad l
|
||||||
|
.nh
|
||||||
|
.SH "NAME"
|
||||||
|
tablizer \- Manipulate tabular output of other programs
|
||||||
|
.SH "SYNOPSIS"
|
||||||
|
.IX Header "SYNOPSIS"
|
||||||
|
.Vb 2
|
||||||
|
\& Usage:
|
||||||
|
\& tablizer [regex] [file, ...] [flags]
|
||||||
|
\&
|
||||||
|
\& Flags:
|
||||||
|
\& \-c, \-\-columns string Only show the speficied columns (separated by ,)
|
||||||
|
\& \-d, \-\-debug Enable debugging
|
||||||
|
\& \-h, \-\-help help for tablizer
|
||||||
|
\& \-v, \-\-invert\-match select non\-matching rows
|
||||||
|
\& \-m, \-\-man Display manual page
|
||||||
|
\& \-n, \-\-no\-numbering Disable header numbering
|
||||||
|
\& \-N, \-\-no\-color Disable pattern highlighting
|
||||||
|
\& \-o, \-\-output string Output mode \- one of: orgtbl, markdown, extended, yaml, ascii(default)
|
||||||
|
\& \-X, \-\-extended Enable extended output
|
||||||
|
\& \-M, \-\-markdown Enable markdown table output
|
||||||
|
\& \-O, \-\-orgtbl Enable org\-mode table output
|
||||||
|
\& \-s, \-\-separator string Custom field separator
|
||||||
|
\& \-a, \-\-sort\-age sort according to age (duration) string
|
||||||
|
\& \-k, \-\-sort\-by int Sort by column (default: 1)
|
||||||
|
\& \-D, \-\-sort\-desc Sort in descending order (default: ascending)
|
||||||
|
\& \-i, \-\-sort\-numeric sort according to string numerical value
|
||||||
|
\& \-t, \-\-sort\-time sort according to time string
|
||||||
|
\& \-v, \-\-version Print program version
|
||||||
|
.Ve
|
||||||
|
.SH "DESCRIPTION"
|
||||||
|
.IX Header "DESCRIPTION"
|
||||||
|
Many programs generate tabular output. But sometimes you need to
|
||||||
|
post-process these tables, you may need to remove one or more columns
|
||||||
|
or you may want to filter for some pattern (See \s-1PATTERNS\s0) or you
|
||||||
|
may need the output in another program and need to parse it somehow.
|
||||||
|
Standard unix tools such as \fBawk\fR\|(1), \fBgrep\fR\|(1) or \fBcolumn\fR\|(1) may help, but
|
||||||
|
sometimes it's a tedious business.
|
||||||
|
.PP
|
||||||
|
Let's take the output of the tool kubectl. It contains cells with
|
||||||
|
withespace and they do not separate columns by \s-1TAB\s0 characters. This is
|
||||||
|
not easy to process.
|
||||||
|
.PP
|
||||||
|
You can use \fBtablizer\fR to do these and more things.
|
||||||
|
.PP
|
||||||
|
\&\fBtablizer\fR analyses the header fields of a table, registers the
|
||||||
|
column positions of each header field and separates columns by those
|
||||||
|
positions.
|
||||||
|
.PP
|
||||||
|
Without any options it reads its input from \f(CW\*(C`STDIN\*(C'\fR, but you can also
|
||||||
|
specify a file as a parameter. If you want to reduce the output by
|
||||||
|
some regular expression, just specify it as its first parameter. You
|
||||||
|
may also use the \fB\-v\fR option to exclude all rows which match the
|
||||||
|
pattern. Hence:
|
||||||
|
.PP
|
||||||
|
.Vb 2
|
||||||
|
\& # read from STDIN
|
||||||
|
\& kubectl get pods | tablizer
|
||||||
|
\&
|
||||||
|
\& # read a file
|
||||||
|
\& tablizer filename
|
||||||
|
\&
|
||||||
|
\& # search for pattern in a file (works like grep)
|
||||||
|
\& tablizer regex filename
|
||||||
|
\&
|
||||||
|
\& # search for pattern in STDIN
|
||||||
|
\& kubectl get pods | tablizer regex
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
The output looks like the original one but every header field will
|
||||||
|
have a numer associated with it, e.g.:
|
||||||
|
.PP
|
||||||
|
.Vb 1
|
||||||
|
\& NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
These numbers denote the column and you can use them to specify which
|
||||||
|
columns you want to have in your output (see \s-1COLUMNS\s0:
|
||||||
|
.PP
|
||||||
|
.Vb 1
|
||||||
|
\& kubectl get pods | tablizer \-c1,3
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
You can specify the numbers in any order but output will always follow
|
||||||
|
the original order.
|
||||||
|
.PP
|
||||||
|
The numbering can be suppressed by using the \fB\-n\fR option.
|
||||||
|
.PP
|
||||||
|
By default, if a \fBpattern\fR has been speficied, matches will be
|
||||||
|
highlighted. You can disable this behavior with the \fB\-N\fR option.
|
||||||
|
.PP
|
||||||
|
Use the \fB\-k\fR option to specify by which column to sort the tabular
|
||||||
|
data (as in \s-1GNU\s0 \fBsort\fR\|(1)). The default sort column is the first one. To
|
||||||
|
disable sorting at all, supply 0 (Zero) to \-k. The default sort order
|
||||||
|
is ascending. You can change this to descending order using the option
|
||||||
|
\&\fB\-D\fR. The default sort order is by string, but there are other sort
|
||||||
|
modes:
|
||||||
|
.IP "\fB\-a \-\-sort\-age\fR" 4
|
||||||
|
.IX Item "-a --sort-age"
|
||||||
|
Sorts duration strings like \*(L"1d4h32m51s\*(R".
|
||||||
|
.IP "\fB\-i \-\-sort\-numeric\fR" 4
|
||||||
|
.IX Item "-i --sort-numeric"
|
||||||
|
Sorts numeric fields.
|
||||||
|
.IP "\fB\-t \-\-sort\-time\fR" 4
|
||||||
|
.IX Item "-t --sort-time"
|
||||||
|
Sorts timestamps.
|
||||||
|
.PP
|
||||||
|
Finally the \fB\-d\fR option enables debugging output which is mostly
|
||||||
|
useful for the developer.
|
||||||
|
.SS "\s-1PATTERNS\s0"
|
||||||
|
.IX Subsection "PATTERNS"
|
||||||
|
You can reduce the rows being displayed by using a regular expression
|
||||||
|
pattern. The regexp is \s-1PCRE\s0 compatible, refer to the syntax cheat
|
||||||
|
sheet here: <https://github.com/google/re2/wiki/Syntax>. If you want
|
||||||
|
to read a more comprehensive documentation about the topic and have
|
||||||
|
perl installed you can read it with:
|
||||||
|
.PP
|
||||||
|
.Vb 1
|
||||||
|
\& perldoc perlre
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
Or read it online: <https://perldoc.perl.org/perlre>.
|
||||||
|
.PP
|
||||||
|
A note on modifiers: the regexp engine used in tablizer uses another
|
||||||
|
modifier syntax:
|
||||||
|
.PP
|
||||||
|
.Vb 1
|
||||||
|
\& (?MODIFIER)
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
The most important modifiers are:
|
||||||
|
.PP
|
||||||
|
\&\f(CW\*(C`i\*(C'\fR ignore case
|
||||||
|
\&\f(CW\*(C`m\*(C'\fR multiline mode
|
||||||
|
\&\f(CW\*(C`s\*(C'\fR single line mode
|
||||||
|
.PP
|
||||||
|
Example for a case insensitive search:
|
||||||
|
.PP
|
||||||
|
.Vb 1
|
||||||
|
\& kubectl get pods \-A | tablizer "(?i)account"
|
||||||
|
.Ve
|
||||||
|
.SS "\s-1COLUMNS\s0"
|
||||||
|
.IX Subsection "COLUMNS"
|
||||||
|
The parameter \fB\-c\fR can be used to specify, which columns to
|
||||||
|
display. By default tablizer numerizes the header names and these
|
||||||
|
numbers can be used to specify which header to display, see example
|
||||||
|
above.
|
||||||
|
.PP
|
||||||
|
However, beside numbers, you can also use regular expressions with
|
||||||
|
\&\fB\-c\fR, also separated by comma. And you can mix column numbers with
|
||||||
|
regexps.
|
||||||
|
.PP
|
||||||
|
Lets take this table:
|
||||||
|
.PP
|
||||||
|
.Vb 4
|
||||||
|
\& PID TTY TIME CMD
|
||||||
|
\& 14001 pts/0 00:00:00 bash
|
||||||
|
\& 42871 pts/0 00:00:00 ps
|
||||||
|
\& 42872 pts/0 00:00:00 sed
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
We want to see only the \s-1CMD\s0 column and use a regex for this:
|
||||||
|
.PP
|
||||||
|
.Vb 6
|
||||||
|
\& ps | tablizer \-s \*(Aq\es+\*(Aq \-c C
|
||||||
|
\& CMD(4)
|
||||||
|
\& bash
|
||||||
|
\& ps
|
||||||
|
\& tablizer
|
||||||
|
\& sed
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
where \*(L"C\*(R" is our regexp which matches \s-1CMD.\s0
|
||||||
|
.SS "\s-1OUTPUT MODES\s0"
|
||||||
|
.IX Subsection "OUTPUT MODES"
|
||||||
|
There might be cases when the tabular output of a program is way too
|
||||||
|
large for your current terminal but you still need to see every
|
||||||
|
column. In such cases the \fB\-o extended\fR or \fB\-X\fR option can be
|
||||||
|
useful which enables \fIextended mode\fR. In this mode, each row will be
|
||||||
|
printed vertically, header left, value right, aligned by the field
|
||||||
|
widths. Here's an example:
|
||||||
|
.PP
|
||||||
|
.Vb 6
|
||||||
|
\& kubectl get pods | ./tablizer \-o extended
|
||||||
|
\& NAME: repldepl\-7bcd8d5b64\-7zq4l
|
||||||
|
\& READY: 1/1
|
||||||
|
\& STATUS: Running
|
||||||
|
\& RESTARTS: 1 (71m ago)
|
||||||
|
\& AGE: 5h28m
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
You can of course still use a regex to reduce the number of rows
|
||||||
|
displayed.
|
||||||
|
.PP
|
||||||
|
The option \fB\-o shell\fR can be used if the output has to be processed
|
||||||
|
by the shell, it prints variable assignments for each cell, one line
|
||||||
|
per row:
|
||||||
|
.PP
|
||||||
|
.Vb 4
|
||||||
|
\& kubectl get pods | ./tablizer \-o extended ./tablizer \-o shell
|
||||||
|
\& NAME="repldepl\-7bcd8d5b64\-7zq4l" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
\& NAME="repldepl\-7bcd8d5b64\-m48n8" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
\& NAME="repldepl\-7bcd8d5b64\-q2bf4" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
.Ve
|
||||||
|
.PP
|
||||||
|
You can use this in an eval loop.
|
||||||
|
.PP
|
||||||
|
Beside normal ascii mode (the default) and extended mode there are
|
||||||
|
more output modes available: \fBorgtbl\fR which prints an Emacs org-mode
|
||||||
|
table and \fBmarkdown\fR which prints a Markdown table and \fByaml\fR, which
|
||||||
|
prints yaml encoding.
|
||||||
|
.SH "BUGS"
|
||||||
|
.IX Header "BUGS"
|
||||||
|
In order to report a bug, unexpected behavior, feature requests
|
||||||
|
or to submit a patch, please open an issue on github:
|
||||||
|
<https://github.com/TLINDEN/tablizer/issues>.
|
||||||
|
.SH "LICENSE"
|
||||||
|
.IX Header "LICENSE"
|
||||||
|
This software is licensed under the \s-1GNU GENERAL PUBLIC LICENSE\s0 version 3.
|
||||||
|
.PP
|
||||||
|
Copyright (c) 2022 by Thomas von Dein
|
||||||
|
.PP
|
||||||
|
This software uses the following \s-1GO\s0 libraries:
|
||||||
|
.IP "repr (https://github.com/alecthomas/repr)" 4
|
||||||
|
.IX Item "repr (https://github.com/alecthomas/repr)"
|
||||||
|
Released under the \s-1MIT\s0 License, Copyright (c) 2016 Alec Thomas
|
||||||
|
.IP "cobra (https://github.com/spf13/cobra)" 4
|
||||||
|
.IX Item "cobra (https://github.com/spf13/cobra)"
|
||||||
|
Released under the Apache 2.0 license, Copyright 2013\-2022 The Cobra Authors
|
||||||
|
.SH "AUTHORS"
|
||||||
|
.IX Header "AUTHORS"
|
||||||
|
Thomas von Dein \fBtom \s-1AT\s0 vondein \s-1DOT\s0 org\fR
|
||||||
138
tablizer.pod
138
tablizer.pod
@@ -11,23 +11,31 @@ tablizer - Manipulate tabular output of other programs
|
|||||||
-c, --columns string Only show the speficied columns (separated by ,)
|
-c, --columns string Only show the speficied columns (separated by ,)
|
||||||
-d, --debug Enable debugging
|
-d, --debug Enable debugging
|
||||||
-h, --help help for tablizer
|
-h, --help help for tablizer
|
||||||
|
-v, --invert-match select non-matching rows
|
||||||
|
-m, --man Display manual page
|
||||||
-n, --no-numbering Disable header numbering
|
-n, --no-numbering Disable header numbering
|
||||||
-o, --output string Output mode - one of: orgtbl, markdown, extended, ascii(default)
|
-N, --no-color Disable pattern highlighting
|
||||||
|
-o, --output string Output mode - one of: orgtbl, markdown, extended, yaml, ascii(default)
|
||||||
-X, --extended Enable extended output
|
-X, --extended Enable extended output
|
||||||
-M, --markdown Enable markdown table output
|
-M, --markdown Enable markdown table output
|
||||||
-O, --orgtbl Enable org-mode table output
|
-O, --orgtbl Enable org-mode table output
|
||||||
-s, --separator string Custom field separator
|
-s, --separator string Custom field separator
|
||||||
|
-a, --sort-age sort according to age (duration) string
|
||||||
|
-k, --sort-by int Sort by column (default: 1)
|
||||||
|
-D, --sort-desc Sort in descending order (default: ascending)
|
||||||
|
-i, --sort-numeric sort according to string numerical value
|
||||||
|
-t, --sort-time sort according to time string
|
||||||
-v, --version Print program version
|
-v, --version Print program version
|
||||||
|
|
||||||
|
|
||||||
=head1 DESCRIPTION
|
=head1 DESCRIPTION
|
||||||
|
|
||||||
Many programs generate tabular output. But sometimes you need to
|
Many programs generate tabular output. But sometimes you need to
|
||||||
post-process these tables, you may need to remove one or more columns
|
post-process these tables, you may need to remove one or more columns
|
||||||
or you may want to filter for some pattern or you may need the output
|
or you may want to filter for some pattern (See L<PATTERNS>) or you
|
||||||
in another program and need to parse it somehow. Standard unix tools
|
may need the output in another program and need to parse it somehow.
|
||||||
such as awk(1), grep(1) or column(1) may help, but sometimes it's a
|
Standard unix tools such as awk(1), grep(1) or column(1) may help, but
|
||||||
tedious business.
|
sometimes it's a tedious business.
|
||||||
|
|
||||||
Let's take the output of the tool kubectl. It contains cells with
|
Let's take the output of the tool kubectl. It contains cells with
|
||||||
withespace and they do not separate columns by TAB characters. This is
|
withespace and they do not separate columns by TAB characters. This is
|
||||||
@@ -35,14 +43,15 @@ not easy to process.
|
|||||||
|
|
||||||
You can use B<tablizer> to do these and more things.
|
You can use B<tablizer> to do these and more things.
|
||||||
|
|
||||||
B<tablizer> analyses the header fiels of a table, registers the column
|
B<tablizer> analyses the header fields of a table, registers the
|
||||||
positions of each header field and separates columns by those
|
column positions of each header field and separates columns by those
|
||||||
positions.
|
positions.
|
||||||
|
|
||||||
Without any options it reads its input from C<STDIN>, but you can also
|
Without any options it reads its input from C<STDIN>, but you can also
|
||||||
specify a file as a parameter. If you want to reduce the output by
|
specify a file as a parameter. If you want to reduce the output by
|
||||||
some regular expression, just specify it as its first
|
some regular expression, just specify it as its first parameter. You
|
||||||
parameters. Hence:
|
may also use the B<-v> option to exclude all rows which match the
|
||||||
|
pattern. Hence:
|
||||||
|
|
||||||
# read from STDIN
|
# read from STDIN
|
||||||
kubectl get pods | tablizer
|
kubectl get pods | tablizer
|
||||||
@@ -62,7 +71,7 @@ have a numer associated with it, e.g.:
|
|||||||
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
NAME(1) READY(2) STATUS(3) RESTARTS(4) AGE(5)
|
||||||
|
|
||||||
These numbers denote the column and you can use them to specify which
|
These numbers denote the column and you can use them to specify which
|
||||||
columns you want to have in your output:
|
columns you want to have in your output (see L<COLUMNS>:
|
||||||
|
|
||||||
kubectl get pods | tablizer -c1,3
|
kubectl get pods | tablizer -c1,3
|
||||||
|
|
||||||
@@ -71,19 +80,102 @@ the original order.
|
|||||||
|
|
||||||
The numbering can be suppressed by using the B<-n> option.
|
The numbering can be suppressed by using the B<-n> option.
|
||||||
|
|
||||||
Finally the B<-d> option enables debugging output which is mostly
|
By default, if a B<pattern> has been speficied, matches will be
|
||||||
usefull for the developer.
|
highlighted. You can disable this behavior with the B<-N> option.
|
||||||
|
|
||||||
?head2 OUTPUT MODES
|
Use the B<-k> option to specify by which column to sort the tabular
|
||||||
|
data (as in GNU sort(1)). The default sort column is the first one. To
|
||||||
|
disable sorting at all, supply 0 (Zero) to -k. The default sort order
|
||||||
|
is ascending. You can change this to descending order using the option
|
||||||
|
B<-D>. The default sort order is by string, but there are other sort
|
||||||
|
modes:
|
||||||
|
|
||||||
|
=over
|
||||||
|
|
||||||
|
=item B<-a --sort-age>
|
||||||
|
|
||||||
|
Sorts duration strings like "1d4h32m51s".
|
||||||
|
|
||||||
|
=item B<-i --sort-numeric>
|
||||||
|
|
||||||
|
Sorts numeric fields.
|
||||||
|
|
||||||
|
=item B<-t --sort-time>
|
||||||
|
|
||||||
|
Sorts timestamps.
|
||||||
|
|
||||||
|
=back
|
||||||
|
|
||||||
|
Finally the B<-d> option enables debugging output which is mostly
|
||||||
|
useful for the developer.
|
||||||
|
|
||||||
|
=head2 PATTERNS
|
||||||
|
|
||||||
|
You can reduce the rows being displayed by using a regular expression
|
||||||
|
pattern. The regexp is PCRE compatible, refer to the syntax cheat
|
||||||
|
sheet here: L<https://github.com/google/re2/wiki/Syntax>. If you want
|
||||||
|
to read a more comprehensive documentation about the topic and have
|
||||||
|
perl installed you can read it with:
|
||||||
|
|
||||||
|
perldoc perlre
|
||||||
|
|
||||||
|
Or read it online: L<https://perldoc.perl.org/perlre>.
|
||||||
|
|
||||||
|
A note on modifiers: the regexp engine used in tablizer uses another
|
||||||
|
modifier syntax:
|
||||||
|
|
||||||
|
(?MODIFIER)
|
||||||
|
|
||||||
|
The most important modifiers are:
|
||||||
|
|
||||||
|
C<i> ignore case
|
||||||
|
C<m> multiline mode
|
||||||
|
C<s> single line mode
|
||||||
|
|
||||||
|
Example for a case insensitive search:
|
||||||
|
|
||||||
|
kubectl get pods -A | tablizer "(?i)account"
|
||||||
|
|
||||||
|
|
||||||
|
=head2 COLUMNS
|
||||||
|
|
||||||
|
The parameter B<-c> can be used to specify, which columns to
|
||||||
|
display. By default tablizer numerizes the header names and these
|
||||||
|
numbers can be used to specify which header to display, see example
|
||||||
|
above.
|
||||||
|
|
||||||
|
However, beside numbers, you can also use regular expressions with
|
||||||
|
B<-c>, also separated by comma. And you can mix column numbers with
|
||||||
|
regexps.
|
||||||
|
|
||||||
|
Lets take this table:
|
||||||
|
|
||||||
|
PID TTY TIME CMD
|
||||||
|
14001 pts/0 00:00:00 bash
|
||||||
|
42871 pts/0 00:00:00 ps
|
||||||
|
42872 pts/0 00:00:00 sed
|
||||||
|
|
||||||
|
We want to see only the CMD column and use a regex for this:
|
||||||
|
|
||||||
|
ps | tablizer -s '\s+' -c C
|
||||||
|
CMD(4)
|
||||||
|
bash
|
||||||
|
ps
|
||||||
|
tablizer
|
||||||
|
sed
|
||||||
|
|
||||||
|
where "C" is our regexp which matches CMD.
|
||||||
|
|
||||||
|
=head2 OUTPUT MODES
|
||||||
|
|
||||||
There might be cases when the tabular output of a program is way too
|
There might be cases when the tabular output of a program is way too
|
||||||
large for your current terminal but you still need to see every
|
large for your current terminal but you still need to see every
|
||||||
column. In such cases the B<-o extended> or B<-X> option can be
|
column. In such cases the B<-o extended> or B<-X> option can be
|
||||||
usefull which enables I<extended mode>. In this mode, each row will be
|
useful which enables I<extended mode>. In this mode, each row will be
|
||||||
printed vertically, header left, value right, aligned by the field
|
printed vertically, header left, value right, aligned by the field
|
||||||
widths. Here's an example:
|
widths. Here's an example:
|
||||||
|
|
||||||
kubectl get pods | ./tablizer -X
|
kubectl get pods | ./tablizer -o extended
|
||||||
NAME: repldepl-7bcd8d5b64-7zq4l
|
NAME: repldepl-7bcd8d5b64-7zq4l
|
||||||
READY: 1/1
|
READY: 1/1
|
||||||
STATUS: Running
|
STATUS: Running
|
||||||
@@ -93,9 +185,21 @@ widths. Here's an example:
|
|||||||
You can of course still use a regex to reduce the number of rows
|
You can of course still use a regex to reduce the number of rows
|
||||||
displayed.
|
displayed.
|
||||||
|
|
||||||
|
The option B<-o shell> can be used if the output has to be processed
|
||||||
|
by the shell, it prints variable assignments for each cell, one line
|
||||||
|
per row:
|
||||||
|
|
||||||
|
kubectl get pods | ./tablizer -o extended ./tablizer -o shell
|
||||||
|
NAME="repldepl-7bcd8d5b64-7zq4l" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
NAME="repldepl-7bcd8d5b64-m48n8" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
NAME="repldepl-7bcd8d5b64-q2bf4" READY="1/1" STATUS="Running" RESTARTS="9 (47m ago)" AGE="4d23h"
|
||||||
|
|
||||||
|
You can use this in an eval loop.
|
||||||
|
|
||||||
Beside normal ascii mode (the default) and extended mode there are
|
Beside normal ascii mode (the default) and extended mode there are
|
||||||
more output modes available: B<orgtbl> which prints an Emacs org-mode
|
more output modes available: B<orgtbl> which prints an Emacs org-mode
|
||||||
table and B<markdown> which prints a Markdown table.
|
table and B<markdown> which prints a Markdown table and B<yaml>, which
|
||||||
|
prints yaml encoding.
|
||||||
|
|
||||||
=head1 BUGS
|
=head1 BUGS
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user