Browse Source

auto-generate completions for bash/fish/zsh

noisegate-plugins
Alexandros Theodotou 2 years ago
parent
commit
0a7da0775f
Signed by: alex
GPG Key ID: 022EAE42313D70F3
  1. 8
      data/meson.build
  2. 35
      doc/man/meson.build
  3. 9
      ext/sh-manpage-completions/.gitignore
  4. 278
      ext/sh-manpage-completions/LICENSE.GPL2
  5. 21
      ext/sh-manpage-completions/LICENSE.MIT
  6. 20
      ext/sh-manpage-completions/Makefile
  7. 56
      ext/sh-manpage-completions/README.md
  8. 158
      ext/sh-manpage-completions/fish-completions.l
  9. 979
      ext/sh-manpage-completions/fish-tools/create_manpage_completions.py
  10. 1100
      ext/sh-manpage-completions/fish-tools/deroff.py
  11. 41
      ext/sh-manpage-completions/include/BashConverter.hpp
  12. 14
      ext/sh-manpage-completions/include/Converter.hpp
  13. 24
      ext/sh-manpage-completions/include/ZshConverter.hpp
  14. 125
      ext/sh-manpage-completions/run.sh
  15. 60
      ext/sh-manpage-completions/src/BashConverter.cpp
  16. 80
      ext/sh-manpage-completions/src/ZshConverter.cpp
  17. 32
      ext/sh-manpage-completions/templates/bash
  18. 22
      ext/sh-manpage-completions/templates/bash_no_descriptions
  19. 32
      ext/sh-manpage-completions/templates/bash_use_selector
  20. 5
      ext/sh-manpage-completions/templates/zsh
  21. 3
      meson.build
  22. 6
      meson_options.txt
  23. 33
      scripts/gen_completions.sh
  24. 8
      scripts/meson.build

8
data/meson.build

@ -112,14 +112,6 @@ install_data ( @@ -112,14 +112,6 @@ install_data (
'org.zrythm.Zrythm-mime.xml',
install_dir: datadir / 'mime/packages')
if not os_windows
install_data (
'zrythm-completion.bash',
install_dir: sysconfdir / 'bash_completion.d',
install_mode: 'r--r--r--',
rename: prog_name_lowercase)
endif
# GtkSourceView styles
install_data (
'gtksourceview-monokai-extended.xml',

35
doc/man/meson.build

@ -52,6 +52,41 @@ manpage = custom_target ( @@ -52,6 +52,41 @@ manpage = custom_target (
build_by_default: get_option ('manpage'),
)
# gen completions
bash_completion = custom_target (
'bash-completion',
output: 'zrythm',
input: manpage,
command: [
gen_completions_sh, manpage.full_path (), 'bash',
'@OUTPUT@',
],
install: get_option ('completions'),
install_dir: datadir / 'bash-completion/completions',
build_by_default: get_option ('completions'))
zsh_completion = custom_target (
'zsh-completion',
output: '_zrythm',
input: manpage,
command: [
gen_completions_sh, manpage.full_path (), 'zsh',
'@OUTPUT@',
],
install: get_option ('completions'),
install_dir: datadir / 'zsh/site-functions',
build_by_default: get_option ('completions'))
fish_completion = custom_target (
'fish-completion',
output: 'zrythm.fish',
input: manpage,
command: [
gen_completions_sh, manpage.full_path (), 'fish',
'@OUTPUT@',
],
install: get_option ('completions'),
install_dir: datadir / 'fish/vendor_completions.d',
build_by_default: get_option ('completions'))
run_target (
'build-manpage',
command: [

9
ext/sh-manpage-completions/.gitignore vendored

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
*.cc
*.out
completions/
scanner
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

278
ext/sh-manpage-completions/LICENSE.GPL2 vendored

@ -0,0 +1,278 @@ @@ -0,0 +1,278 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

21
ext/sh-manpage-completions/LICENSE.MIT vendored

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

20
ext/sh-manpage-completions/Makefile vendored

@ -0,0 +1,20 @@ @@ -0,0 +1,20 @@
LEXERS = $(wildcard *.l)
IDIR = include
INCS = $(wildcard $(IDIR)/*.hpp)
SRCS = $(wildcard src/*.cpp)
CC = g++
CFLAGS = --std=c++11
all: scanner
lex.yy.cc: $(LEXERS)
flex $^
scanner: lex.yy.cc $(SRCS) $(INCS)
$(CC) -I$(IDIR) $(CFLAGS) -o $@ lex.yy.cc $(SRCS)
clean:
$(RM) $(TARGET) lex.yy.cc
.PHONY: clean

56
ext/sh-manpage-completions/README.md vendored

@ -0,0 +1,56 @@ @@ -0,0 +1,56 @@
# sh-manpage-completions
Automatically generate bash and zsh completions from man pages.
Uses [fish-shell](https://github.com/fish-shell/fish-shell)'s `create_manpage_completions.py` to parse the pages, then converts the resulting fish completions.
## Example
```
./run.sh /usr/share/man/man1/tar.1.gz
```
You can then take the files from `completions/$shell/` and use them according to your configuration:
- **Bash**: Source them in an initialization file (e.g. `~/.bashrc`)
- **Zsh**: Add them to a directory in `$fpath`
## Limitations
Bash doesn't support descriptions in completions. There has been some [discussion about workarounds](https://stackoverflow.com/questions/7267185/bash-autocompletion-add-description-for-possible-completions). Two different strategies were implemented:
1. Separate descriptions
Consists on printing the completions with descriptions, before bash displays the completions again. It results in redundancy but doesn't break tab behaviour. Descriptions can be omitted like so:
```
BASH_NO_DESCRIPTIONS=1 ./run.sh /usr/share/man/man1/tar.1.gz
```
2. Filter through a selector
You can use a fuzzy selector to extract the right option, containg both the completion and its description. No redundancy, but relies on an external application. Can be used like so:
```
BASH_USE_SELECTOR=1 ./run.sh /usr/share/man/man1/tar.1.gz
```
Uses [fzf](https://github.com/junegunn/fzf) by default. You can pass another one, optionally with an argument that takes the current input as a query, filtering down the results:
```
BASH_USE_SELECTOR=1 SELECTOR=fzy SELECTOR_QUERY='-q' ./run.sh /usr/share/man/man1/tar.1.gz
```
## Related Work
- Built-in parsing of options output by `--help`:
- **Bash**: `complete -F _longopt`
- **Zsh**: `compdef _gnu_generic`
- [GitHub \- RobSis/zsh\-completion\-generator: Plugin that generates completion functions automatically from getopt\-style help texts](https://github.com/RobSis/zsh-completion-generator)
- [GitHub \- Aloxaf/fzf\-tab: Replace zsh's default completion selection menu with fzf!](https://github.com/Aloxaf/fzf-tab)
## License
Files in `fish-tools` were taken from fish-shell's source code, which is released under the GNU General Public License, version 2 (see LICENSE.GPL2).
The remaining source code is released under the MIT License (see LICENSE.MIT).

158
ext/sh-manpage-completions/fish-completions.l vendored

@ -0,0 +1,158 @@ @@ -0,0 +1,158 @@
%option c++ debug stack noyywrap yylineno
%{
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include "Converter.hpp"
#include "BashConverter.hpp"
#include "ZshConverter.hpp"
static std::string buffer,
command,
description;
static std::vector<std::string> short_option,
long_option,
old_option;
static std::vector<Converter*> converters;
void log(std::string s) {
//std::cout << s << std::endl;
}
%}
SPACE [ \t]+
%x X_line X_c X_d X_o X_s X_l X_s_quoted X_d_quoted
%%
complete {
yy_push_state(X_line);
log("begin line");
}
<X_line>(-c|--command){SPACE} yy_push_state(X_c);
<X_line>(-d|--description){SPACE} yy_push_state(X_d);
<X_line>(-o|--old-option){SPACE} yy_push_state(X_o);
<X_line>(-s|--short-option){SPACE} yy_push_state(X_s);
<X_line>(-l|--long-option){SPACE} yy_push_state(X_l);
<X_c,X_d,X_o,X_s,X_l>"\'" {
buffer += yytext;
yy_push_state(X_s_quoted);
}
<X_s_quoted>"\\\'" buffer += "\'\"\'\"\'";
<X_s_quoted>"\'" {
buffer += yytext;
yy_pop_state();
}
<X_c,X_d,X_o,X_s,X_l>"\"" {
buffer += yytext;
yy_push_state(X_d_quoted);
}
<X_d_quoted>"\\\"" buffer += "\"\'\"\'\"";
<X_d_quoted>"\"" {
buffer += yytext;
yy_pop_state();
}
<X_s_quoted,X_d_quoted>"\[" buffer += "\\\\[";
<X_s_quoted,X_d_quoted>"\]" buffer += "\\\\]";
<X_s_quoted,X_d_quoted>"\`" buffer += "\'\"\'\"\'";
<X_s_quoted,X_d_quoted>{SPACE} buffer += " ";
<X_s_quoted,X_d_quoted>. buffer += yytext;
<X_c>{SPACE}|\n {
command = buffer;
buffer = "";
yy_pop_state();
if (strcmp(yytext, "\n") == 0) {
yyless(0);
}
log("command: " + command);
}
<X_d>{SPACE}|\n {
description = buffer;
buffer = "";
yy_pop_state();
if (strcmp(yytext, "\n") == 0) {
yyless(0);
}
log("description: " + description);
}
<X_o>{SPACE}|\n {
old_option.push_back(buffer);
buffer = "";
yy_pop_state();
if (strcmp(yytext, "\n") == 0) {
yyless(0);
}
log("old_option: " + old_option.back());
}
<X_s>{SPACE}|\n {
short_option.push_back(buffer);
buffer = "";
yy_pop_state();
if (strcmp(yytext, "\n") == 0) {
yyless(0);
}
log("short_option: " + short_option.back());
}
<X_l>{SPACE}|\n {
long_option.push_back(buffer);
buffer = "";
yy_pop_state();
if (strcmp(yytext, "\n") == 0) {
yyless(0);
}
log("long_option: " + long_option.back());
}
<X_c,X_d,X_o,X_s,X_l>. buffer += yytext;
<X_line>\n {
yy_pop_state();
for (auto &it : converters) {
it->convert(
command,
description,
short_option,
long_option,
old_option);
}
buffer =
command =
description =
"";
short_option.clear();
long_option.clear();
old_option.clear();
log("end line");
}
.|\n {}
%%
int main() {
BashConverter bash_converter;
converters.push_back((Converter*)&bash_converter);
ZshConverter zsh_converter;
converters.push_back((Converter*)&zsh_converter);
FlexLexer* lexer = new yyFlexLexer;
//lexer->set_debug(1);
while(lexer->yylex() != 0)
;
return 0;
}

979
ext/sh-manpage-completions/fish-tools/create_manpage_completions.py vendored

@ -0,0 +1,979 @@ @@ -0,0 +1,979 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Run me like this: ./create_manpage_completions.py /usr/share/man/man{1,8}/* > man_completions.fish
"""
<OWNER> = Siteshwar Vashisht
<YEAR> = 2012
Copyright (c) 2012, Siteshwar Vashisht
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import string, sys, re, os.path, bz2, gzip, traceback, getopt, errno, codecs
from deroff import Deroffer
lzma_available = True
try:
try:
import lzma
except ImportError:
from backports import lzma
except ImportError:
lzma_available = False
# Whether we're Python 3
IS_PY3 = sys.version_info[0] >= 3
# This gets set to the name of the command that we are currently executing
CMDNAME = ""
# Information used to track which of our parsers were successful
PARSER_INFO = {}
# built_command writes into this global variable, yuck
built_command_output = []
# Diagnostic output
diagnostic_output = []
diagnostic_indent = 0
# Three diagnostic verbosity levels
VERY_VERBOSE, BRIEF_VERBOSE, NOT_VERBOSE = 2, 1, 0
# Pick some reasonable default values for settings
global VERBOSITY, WRITE_TO_STDOUT, DEROFF_ONLY
VERBOSITY, WRITE_TO_STDOUT, DEROFF_ONLY = NOT_VERBOSE, False, False
def add_diagnostic(dgn, msg_verbosity = VERY_VERBOSE):
# Add a diagnostic message, if msg_verbosity <= VERBOSITY
if msg_verbosity <= VERBOSITY:
diagnostic_output.append(' '*diagnostic_indent + dgn)
def flush_diagnostics(where):
if diagnostic_output:
output_str = '\n'.join(diagnostic_output) + '\n'
where.write(output_str)
diagnostic_output[:] = []
# Make sure we don't output the same completion multiple times, which can happen
# For example, xsubpp.1.gz and xsubpp5.10.1.gz
# This maps commands to lists of completions
already_output_completions = {}
def compile_and_search(regex, input):
options_section_regex = re.compile(regex , re.DOTALL)
options_section_matched = re.search( options_section_regex, input)
return options_section_matched
def unquote_double_quotes(data):
if (len(data) < 2):
return data
if data[0] == '"' and data[len(data)-1] == '"':
data = data[1:len(data)-1]
return data
def unquote_single_quotes(data):
if (len(data) < 2):
return data
if data[0] == '`' and data[len(data)-1] == '\'':
data = data[1:len(data)-1]
return data
# Make a string of characters that are deemed safe in fish without needing to be escaped
# Note that space is not included
g_fish_safe_chars = frozenset(string.ascii_letters + string.digits + '_+-|/:=@~')
def fish_escape_single_quote(str):
# Escape a string if necessary so that it can be put in single quotes
# If it has no non-safe chars, there's nothing to do
if g_fish_safe_chars.issuperset(str):
return str
str = str.replace('\\', '\\\\') # Replace one backslash with two
str = str.replace("'", "\\'") # Replace one single quote with a backslash-single-quote
return "'" + str + "'"
# Make a string Unicode by attempting to decode it as latin-1, or UTF8. See #658
def lossy_unicode(s):
# All strings are unicode in Python 3
if IS_PY3 or isinstance(s, unicode): return s
try:
return s.decode('latin-1')
except UnicodeEncodeError:
pass
try:
return s.decode('utf-8')
except UnicodeEncodeError:
pass
return s.decode('latin-1', 'ignore')
def output_complete_command(cmdname, args, description, output_list):
comps = ['complete -c', cmdname]
comps.extend(args)
if description:
comps.append('--description')
comps.append(description)
output_list.append(lossy_unicode(' ').join([lossy_unicode(c) for c in comps]))
def built_command(options, description):
# print "Options are: ", options
man_optionlist = re.split(" |,|\"|=|[|]", options)
fish_options = []
for optionstr in man_optionlist:
option = re.sub(r"(\[.*\])", "", optionstr)
option = option.strip(" \t\r\n[](){}.,:!")
# Skip some problematic cases
if option in ['-', '--']: continue
if any(c in "{}()" for c in option): continue
if option.startswith('--'):
# New style long option (--recursive)
fish_options.append('-l ' + fish_escape_single_quote(option[2:]))
elif option.startswith('-') and len(option) == 2:
# New style short option (-r)
fish_options.append('-s ' + fish_escape_single_quote(option[1:]))
elif option.startswith('-') and len(option) > 2:
# Old style long option (-recursive)
fish_options.append('-o ' + fish_escape_single_quote(option[1:]))
# Determine which options are new (not already in existing_options)
# Then add those to the existing options
existing_options = already_output_completions.setdefault(CMDNAME, set())
fish_options = [opt for opt in fish_options if opt not in existing_options]
existing_options.update(fish_options)
# Maybe it's all for naught
if not fish_options: return
# Here's what we'll use to truncate if necessary
max_description_width = 78
if IS_PY3:
truncation_suffix = 'โ€ฆ'
else:
ELLIPSIS_CODE_POINT = 0x2026
truncation_suffix = unichr(ELLIPSIS_CODE_POINT)
# Try to include as many whole sentences as will fit
# Clean up some probably bogus escapes in the process
clean_desc = description.replace("\\'", "'").replace("\\.", ".")
sentences = clean_desc.split('.')
# Clean up "sentences" that are just whitespace
# But don't let it be empty
sentences = [x for x in sentences if x.strip()]
if not sentences: sentences = ['']
udot = lossy_unicode('.')
uspace = lossy_unicode(' ')
truncated_description = lossy_unicode(sentences[0]) + udot
for line in sentences[1:]:
if not line: continue
proposed_description = lossy_unicode(truncated_description) + uspace + lossy_unicode(line) + udot
if len(proposed_description) <= max_description_width:
# It fits
truncated_description = proposed_description
else:
# No fit
break
# If the first sentence does not fit, truncate if necessary
if len(truncated_description) > max_description_width:
prefix_len = max_description_width - len(truncation_suffix)
truncated_description = truncated_description[:prefix_len] + truncation_suffix
# Escape some more things
truncated_description = fish_escape_single_quote(truncated_description)
escaped_cmd = fish_escape_single_quote(CMDNAME)
output_complete_command(escaped_cmd, fish_options, truncated_description, built_command_output)
def remove_groff_formatting(data):
data = data.replace("\\fI","")
data = data.replace("\\fP","")
data = data.replace("\\f1","")
data = data.replace("\\fB","")
data = data.replace("\\fR","")
data = data.replace("\\e","")
data = re.sub(".PD( \d+)","",data)
data = data.replace(".BI","")
data = data.replace(".BR","")
data = data.replace("0.5i","")
data = data.replace(".rb","")
data = data.replace("\\^","")
data = data.replace("{ ","")
data = data.replace(" }","")
data = data.replace("\ ","")
data = data.replace("\-","-")
data = data.replace("\&","")
data = data.replace(".B","")
data = data.replace("\-","-")
data = data.replace(".I","")
data = data.replace("\f","")
return data
class ManParser(object):
def is_my_type(self, manpage):
return False
def parse_man_page(self, manpage):
return False
class Type1ManParser(ManParser):
def is_my_type(self, manpage):
# print manpage
options_section_matched = compile_and_search("\.SH \"OPTIONS\"(.*?)", manpage)
if options_section_matched == None:
return False
else:
return True
def parse_man_page(self, manpage):
options_section_regex = re.compile( "\.SH \"OPTIONS\"(.*?)(\.SH|\Z)", re.DOTALL)
options_section_matched = re.search( options_section_regex, manpage)
options_section = options_section_matched.group(0)
# print options_section
options_parts_regex = re.compile("\.PP(.*?)\.RE", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
# print options_matched
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
add_diagnostic('Unable to find options')
if( self.fallback(options_section) ):
return True
elif (self.fallback2(options_section) ):
return True
return False
while (options_matched != None):
data = options_matched.group(1)
last_dotpp_index = data.rfind(".PP")
if (last_dotpp_index != -1):
data = data[last_dotpp_index+3:]
data = remove_groff_formatting(data)
data = data.split(".RS 4")
if (len (data) > 1): #and len(data[1]) <= 300):
optionName = data[0].strip()
if ( optionName.find("-") == -1):
add_diagnostic("%r doesn't contain '-' " % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
return False
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
def fallback(self, options_section):
add_diagnostic('Trying fallback')
options_parts_regex = re.compile("\.TP( \d+)?(.*?)\.TP", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
if options_matched == None:
add_diagnostic('Still not found')
return False
while options_matched != None:
data = options_matched.group(2)
data = remove_groff_formatting(data)
data = data.strip()
data = data.split("\n",1)
if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
optionName = data[0].strip()
if ( optionName.find("-") == -1):
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
return False
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
return True
def fallback2(self, options_section):
add_diagnostic('Trying last chance fallback')
ix_remover_regex = re.compile("\.IX.*")
trailing_num_regex = re.compile('\\d+$')
options_parts_regex = re.compile("\.IP (.*?)\.IP", re.DOTALL)
options_section = re.sub(ix_remover_regex, "", options_section)
options_matched = re.search(options_parts_regex, options_section)
if options_matched == None:
add_diagnostic('Still (still!) not found')
return False
while options_matched != None:
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
data = data.split("\n",1)
if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
optionName = re.sub(trailing_num_regex, "", data[0].strip())
if ('-' not in optionName):
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = optionName.strip()
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
return False
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
return True
class Type2ManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.SH OPTIONS(.*?)", manpage)
if options_section_matched == None:
return False
else:
return True
def parse_man_page(self, manpage):
options_section_regex = re.compile( "\.SH OPTIONS(.*?)(\.SH|\Z)", re.DOTALL)
options_section_matched = re.search( options_section_regex, manpage)
options_section = options_section_matched.group(1)
options_parts_regex = re.compile("\.[I|T]P( \d+(\.\d)?i?)?(.*?)\.([I|T]P|UNINDENT)", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
add_diagnostic('Command is %r' % CMDNAME)
if options_matched == None:
add_diagnostic("%r: Unable to find options" % self)
return False
while (options_matched != None):
data = options_matched.group(3)
data = remove_groff_formatting(data)
data = data.strip()
data = data.split("\n",1)
if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
optionName = data[0].strip()
if '-' not in optionName:
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
class Type3ManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.SH DESCRIPTION(.*?)", manpage)
if options_section_matched == None:
return False
else:
return True
def parse_man_page(self, manpage):
options_section_regex = re.compile( "\.SH DESCRIPTION(.*?)(\.SH|\Z)", re.DOTALL)
options_section_matched = re.search( options_section_regex, manpage)
options_section = options_section_matched.group(1)
options_parts_regex = re.compile("\.TP(.*?)\.TP", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
add_diagnostic('Unable to find options section')
return False
while (options_matched != None):
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
data = data.split("\n",1)
if (len(data)>1): # and len(data[1])<400):
optionName = data[0].strip()
if ( optionName.find("-") == -1):
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
return False
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
class Type4ManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.SH FUNCTION LETTERS(.*?)", manpage)
if options_section_matched == None:
return False
else:
return True
def parse_man_page(self, manpage):
options_section_regex = re.compile( "\.SH FUNCTION LETTERS(.*?)(\.SH|\Z)", re.DOTALL)
options_section_matched = re.search( options_section_regex, manpage)
options_section = options_section_matched.group(1)
options_parts_regex = re.compile("\.TP(.*?)\.TP", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
print >> sys.stderr, "Unable to find options section"
return False
while (options_matched != None):
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
data = data.split("\n",1)
if (len(data)>1): # and len(data[1])<400):
optionName = data[0].strip()
if ( optionName.find("-") == -1):
add_diagnostic("%r doesn't contain '-' " % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
optionDescription = data[1].strip().replace("\n"," ")
built_command(optionName, optionDescription)
else:
add_diagnostic('Unable to split option from description')
return False
options_section = options_section[options_matched.end()-3:]
options_matched = re.search(options_parts_regex, options_section)
return True
class TypeDarwinManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.S[hH] DESCRIPTION", manpage)
return options_section_matched != None
def trim_groff(self, line):
# Remove initial period
if line.startswith('.'):
line = line[1:]
# Skip leading groff crud
while re.match('[A-Z][a-z]\s', line):
line = line[3:]
# If the line ends with a space and then a period or comma, then erase the space
# This hack handles lines of the form '.Ar projectname .'
if line.endswith(' ,') or line.endswith(' .'):
line = line[:-2] + line[-1]
return line
def count_argument_dashes(self, line):
# Determine how many dashes the line has using the following regex hack
# Look for the start of a line, followed by a dot, then a sequence of
# one or more dashes ('Fl')
result = 0
if line.startswith('.'):
line = line[4:]
while line.startswith('Fl '):
result = result + 1
line = line[3:]
return result
# Replace some groff escapes. There's a lot we don't bother to handle.
def groff_replace_escapes(self, line):
line = line.replace('.Nm', CMDNAME)
line = line.replace('\\ ', ' ')
line = line.replace('\& ', '')
return line
def is_option(self, line):
return line.startswith('.It Fl')
def parse_man_page(self, manpage):
got_something = False
lines = manpage.splitlines()
# Discard lines until we get to ".sh Description"
while lines and not (lines[0].startswith('.Sh DESCRIPTION') or lines[0].startswith('.SH DESCRIPTION')):
lines.pop(0)
while lines:
# Pop until we get to the next option
while lines and not self.is_option(lines[0]):
lines.pop(0)
if not lines:
continue
# Get the line and clean it up
line = lines.pop(0)
# Try to guess how many dashes this argument has
dash_count = self.count_argument_dashes(line)
line = self.groff_replace_escapes(line)
line = self.trim_groff(line)
line = line.strip()
if not line: continue
# Extract the name
name = line.split(None, 2)[0]
# Extract the description
desc_lines = []
while lines and not self.is_option(lines[0]):
line = lossy_unicode(lines.pop(0).strip())
# Ignore comments
if line.startswith(r'.\"'):
continue
if line.startswith('.'):
line = self.groff_replace_escapes(line)
line = self.trim_groff(line).strip()
if line:
desc_lines.append(line)
desc = ' '.join(desc_lines)
if name == '-':
# Skip double -- arguments
continue
elif len(name) > 1:
# Output the command
built_command(('-' * dash_count) + name, desc)
got_something = True
elif len(name) == 1:
built_command('-' + name, desc)
got_something = True
return got_something
class TypeDeroffManParser(ManParser):
def is_my_type(self, manpage):
return True # We're optimists
def is_option(self, line):
return line.startswith('-')
def could_be_description(self, line):
return len(line) > 0 and not line.startswith('-')
def parse_man_page(self, manpage):
d = Deroffer()
d.deroff(manpage)
output = d.get_output()
lines = output.split('\n')
got_something = False
# Discard lines until we get to DESCRIPTION or OPTIONS
while lines and not (lines[0].startswith('DESCRIPTION') or lines[0].startswith('OPTIONS') or lines[0].startswith('COMMAND OPTIONS')):
lines.pop(0)
# Look for BUGS and stop there
for idx in range(len(lines)):
line = lines[idx]
if line.startswith('BUGS'):
# Drop remaining elements
lines[idx:] = []
break
while lines:
# Pop until we get to the next option
while lines and not self.is_option(lines[0]):
line = lines.pop(0)
if not lines:
continue
options = lines.pop(0)
# Pop until we get to either an empty line or a line starting with -
description = ''
while lines and self.could_be_description(lines[0]):
if description: description += ' '
description += lines.pop(0)
built_command(options, description)
got_something = True
return got_something
# Return whether the file at the given path is overwritable
# Raises IOError if it cannot be opened
def file_is_overwritable(path):
result = False
file = codecs.open(path, "r", encoding="utf-8")
for line in file:
# Skip leading empty lines
line = line.strip()
if not line:
continue
# We look in the initial run of lines that start with #
if not line.startswith('#'):
break
# See if this contains the magic word
if 'Autogenerated' in line:
result = True
break
file.close()
return result
# Remove any and all autogenerated completions in the given directory
def cleanup_autogenerated_completions_in_directory(dir):
try:
for filename in os.listdir(dir):
# Skip non .fish files
if not filename.endswith('.fish'): continue
path = os.path.join(dir, filename)
cleanup_autogenerated_file(path)
except OSError as err:
return False
# Delete the file if it is autogenerated
def cleanup_autogenerated_file(path):
try:
if file_is_overwritable(path):
os.remove(path)
except (OSError, IOError):
pass
def parse_manpage_at_path(manpage_path, output_directory):
filename = os.path.basename(manpage_path)
# Clear diagnostics
global diagnostic_indent
diagnostic_output[:] = []
diagnostic_indent = 0
# Set up some diagnostics
add_diagnostic('Considering ' + manpage_path)
diagnostic_indent += 1
if manpage_path.endswith('.gz'):
fd = gzip.open(manpage_path, 'r')
manpage = fd.read()
if IS_PY3: manpage = manpage.decode('latin-1')
elif manpage_path.endswith('.bz2'):
fd = bz2.BZ2File(manpage_path, 'r')
manpage = fd.read()
if IS_PY3: manpage = manpage.decode('latin-1')
elif manpage_path.endswith('.xz') or manpage_path.endswith('.lzma'):
if not lzma_available:
return
fd = lzma.LZMAFile(str(manpage_path), 'r')
manpage = fd.read()
if IS_PY3: manpage = manpage.decode('latin-1')
elif manpage_path.endswith((".1", ".2", ".3", ".4", ".5", ".6", ".7", ".8", ".9")):
if IS_PY3:
fd = open(manpage_path, 'r', encoding='latin-1')
else:
fd = open(manpage_path, 'r')
manpage = fd.read()
else:
return
fd.close()
manpage = str(manpage)
# Get the "base" command, e.g. gcc.1.gz -> gcc
cmd_base = CMDNAME.split('.', 1)[0]
ignoredcommands = ["cc", "g++", "gcc", "c++", "cpp", "emacs", "gprof", "wget", "ld", "awk"]
if cmd_base in ignoredcommands:
return
# Ignore perl's gazillion man pages
ignored_prefixes = ['perl', 'zsh']
for prefix in ignored_prefixes:
if cmd_base.startswith(prefix):
return
# Ignore the millions of links to BUILTIN(1)
if 'BUILTIN 1' in manpage or 'builtin.1' in manpage:
return
# Clear the output list
built_command_output[:] = []
if DEROFF_ONLY:
parsers = [TypeDeroffManParser()]
else:
parsers = [Type1ManParser(), Type2ManParser(), Type4ManParser(), Type3ManParser(), TypeDarwinManParser(), TypeDeroffManParser()]
parsersToTry = [p for p in parsers if p.is_my_type(manpage)]
success = False
if not parsersToTry:
add_diagnostic(manpage_path + ": Not supported")
else:
for parser in parsersToTry:
add_diagnostic('Trying %s' % parser.__class__.__name__)
diagnostic_indent += 1
success = parser.parse_man_page(manpage)
diagnostic_indent -= 1
# Make sure empty files aren't reported as success
if not built_command_output:
success = False
if success:
PARSER_INFO.setdefault(parser.__class__.__name__, []).append(CMDNAME)
break
if success:
if WRITE_TO_STDOUT:
output_file = sys.stdout
else:
fullpath = os.path.join(output_directory, CMDNAME + '.fish')
try:
output_file = codecs.open(fullpath, "w", encoding="utf-8")
except IOError as err:
add_diagnostic("Unable to open file '%s': error(%d): %s" % (fullpath, err.errno, err.strerror))
return False
built_command_output.insert(0, "# " + CMDNAME)
# Output the magic word Autogenerated so we can tell if we can overwrite this
built_command_output.insert(1, "# Autogenerated from man page " + manpage_path)
# built_command_output.insert(2, "# using " + parser.__class__.__name__) # XXX MISATTRIBUTES THE CULPABILE PARSER! Was really using Type2 but reporting TypeDeroffManParser
for line in built_command_output:
output_file.write(line)
output_file.write('\n')
output_file.write('\n')
add_diagnostic(manpage_path + ' parsed successfully')
if output_file != sys.stdout:
output_file.close()
else:
parser_names = ', '.join(p.__class__.__name__ for p in parsersToTry)
#add_diagnostic('%s contains no options or is unparsable' % manpage_path, BRIEF_VERBOSE)
add_diagnostic('%s contains no options or is unparsable (tried parser %s)' % (manpage_path, parser_names), BRIEF_VERBOSE)
return success
def parse_and_output_man_pages(paths, output_directory, show_progress):
global diagnostic_indent, CMDNAME
paths.sort()
total_count = len(paths)
successful_count, index = 0, 0
padding_len = len(str(total_count))
last_progress_string_length = 0
if show_progress and not WRITE_TO_STDOUT:
print("Parsing man pages and writing completions to {0}".format(output_directory))
man_page_suffixes = set([os.path.splitext(m)[1][1:] for m in paths])
lzma_xz_occurs = "xz" in man_page_suffixes or "lzma" in man_page_suffixes
if lzma_xz_occurs and not lzma_available:
add_diagnostic('At least one man page is compressed with lzma or xz, but the "lzma" module is not available.'
' Any man page compressed with either will be skipped.',
NOT_VERBOSE)
flush_diagnostics(sys.stderr)
for manpage_path in paths:
index += 1
# Get the "base" command, e.g. gcc.1.gz -> gcc
man_file_name = os.path.basename(manpage_path)
CMDNAME = man_file_name.split('.', 1)[0]
output_file_name = CMDNAME + '.fish'
# Show progress if we're doing that
if show_progress:
progress_str = ' {0} / {1} : {2}'.format((str(index).rjust(padding_len)), total_count, man_file_name)
# Pad on the right with spaces so we overwrite whatever we wrote last time
padded_progress_str = progress_str.ljust(last_progress_string_length)
last_progress_string_length = len(progress_str)
sys.stdout.write("\r{0}\r".format(padded_progress_str))
sys.stdout.flush()
# Maybe we want to skip this item
skip = False
if not WRITE_TO_STDOUT:
# Compute the path that we would write to
output_path = os.path.join(output_directory, output_file_name)
# Now skip if requested
if skip:
continue
try:
if parse_manpage_at_path(manpage_path, output_directory):
successful_count += 1
except IOError:
diagnostic_indent = 0
add_diagnostic('Cannot open ' + manpage_path)
except (KeyboardInterrupt, SystemExit):
raise
except:
add_diagnostic('Error parsing %s: %s' % (manpage_path, sys.exc_info()[0]), BRIEF_VERBOSE)
flush_diagnostics(sys.stderr)
traceback.print_exc(file=sys.stderr)
flush_diagnostics(sys.stderr)
print("") #Newline after loop
add_diagnostic("Successfully parsed %d / %d pages" % (successful_count, total_count), BRIEF_VERBOSE)
flush_diagnostics(sys.stderr)
def get_paths_from_man_locations():
# Return all the paths to man(1) and man(8) files in the manpath
import subprocess, os
proc = None
# $MANPATH takes precedence, just like with `man` on the CLI.
if os.getenv("MANPATH"):
parent_paths = os.getenv("MANPATH").strip().split(':')
else:
# Some systems have manpath, others have `man --path` (like Haiku).
for prog in [['manpath'], ['man', '--path']]:
try:
proc = subprocess.Popen(prog, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError: # Command does not exist, keep trying
continue
break # Command exists, use it.
manpath, err_data = proc.communicate()
parent_paths = manpath.decode().strip().split(':')
if (not parent_paths) or (proc and proc.returncode > 0):
# HACK: Use some fallbacks in case we can't get anything else.
# `mandoc` does not provide `manpath` or `man --path` and $MANPATH might not be set.
# The alternative is reading its config file (/etc/man.conf)
if os.path.isfile('/etc/man.conf'):
data = open('/etc/man.conf', 'r')
for line in data:
if ('manpath' in line or 'MANPATH' in line):
p = line.split(' ')[1]
p = p.split()[0]
parent_paths.append(p)
if (not parent_paths):
sys.stderr.write("Unable to get the manpath, falling back to /usr/share/man:/usr/local/share/man. Please set $MANPATH if that is not correct.\n")
parent_paths = ["/usr/share/man", "/usr/local/share/man"]
result = []
for parent_path in parent_paths:
for section in ['man1', 'man6', 'man8']:
directory_path = os.path.join(parent_path, section)
try:
names = os.listdir(directory_path)
except OSError as e:
names = []
names.sort()
for name in names:
result.append(os.path.join(directory_path, name))
return result
def usage(script_name):
print("Usage: {0} [-v, --verbose] [-s, --stdout] [-d, --directory] [-p, --progress] files...".format(script_name))