7fe52b3884e69efe859d3241d00689a61c73b4d5
[alexxy/gromacs.git] / src / gromacs / commandline / shellcompletions.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 /*! \internal \file
38  * \brief
39  * Implements gmx::ShellCompletionWriter.
40  *
41  * \author Teemu Murtola <teemu.murtola@gmail.com>
42  * \ingroup module_commandline
43  */
44 #include "gmxpre.h"
45
46 #include "shellcompletions.h"
47
48 #include <cstdio>
49
50 #include <algorithm>
51 #include <memory>
52 #include <string>
53
54 #include "gromacs/commandline/cmdlinehelpcontext.h"
55 #include "gromacs/commandline/pargs.h"
56 #include "gromacs/compat/make_unique.h"
57 #include "gromacs/fileio/filetypes.h"
58 #include "gromacs/options/basicoptions.h"
59 #include "gromacs/options/filenameoption.h"
60 #include "gromacs/options/options.h"
61 #include "gromacs/options/optionsvisitor.h"
62 #include "gromacs/utility/arrayref.h"
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/gmxassert.h"
65 #include "gromacs/utility/stringutil.h"
66 #include "gromacs/utility/textwriter.h"
67
68 namespace gmx
69 {
70
71 namespace
72 {
73
74 class OptionsListWriter : public OptionsVisitor
75 {
76     public:
77         const std::string &optionList() const { return optionList_; }
78
79         void visitSection(const OptionSectionInfo &section) override
80         {
81             OptionsIterator iterator(section);
82             iterator.acceptSections(this);
83             iterator.acceptOptions(this);
84         }
85         void visitOption(const OptionInfo &option) override
86         {
87             if (option.isHidden())
88             {
89                 return;
90             }
91             if (!optionList_.empty())
92             {
93                 optionList_.append("\\n");
94             }
95             optionList_.append("-");
96             const BooleanOptionInfo *booleanOption
97                 = option.toType<BooleanOptionInfo>();
98             if (booleanOption != nullptr && booleanOption->defaultValue())
99             {
100                 optionList_.append("no");
101             }
102             optionList_.append(option.name());
103         }
104
105     private:
106         std::string optionList_;
107 };
108
109 class OptionCompletionWriter : public OptionsVisitor
110 {
111     public:
112         explicit OptionCompletionWriter(TextWriter *out) : out_(*out) {}
113
114         void visitSection(const OptionSectionInfo &section) override
115         {
116             OptionsIterator iterator(section);
117             iterator.acceptSections(this);
118             iterator.acceptOptions(this);
119         }
120         void visitOption(const OptionInfo &option) override;
121
122     private:
123         void writeOptionCompletion(const OptionInfo  &option,
124                                    const std::string &completion);
125
126         TextWriter &out_;
127 };
128
129 void OptionCompletionWriter::visitOption(const OptionInfo &option)
130 {
131     if (option.isHidden())
132     {
133         return;
134     }
135     const FileNameOptionInfo *fileOption = option.toType<FileNameOptionInfo>();
136     if (fileOption != nullptr)
137     {
138         if (fileOption->isDirectoryOption())
139         {
140             writeOptionCompletion(option, "compgen -S ' ' -d $c");
141             return;
142         }
143         const FileNameOptionInfo::ExtensionList &extensionList = fileOption->extensions();
144         if (extensionList.empty())
145         {
146             return;
147         }
148         std::string completion("compgen -S ' ' -X '!*");
149         std::string extensions(joinStrings(extensionList, "|"));
150         if (extensionList.size() > 1)
151         {
152             extensions = "@(" + extensions + ")";
153         }
154         completion.append(extensions);
155         // TODO: Don't duplicate this from filenm.c/futil.c.
156         completion.append("?(.gz|.Z)' -f -- $c ; compgen -S '/' -d $c");
157         writeOptionCompletion(option, completion);
158         return;
159     }
160     const StringOptionInfo *stringOption = option.toType<StringOptionInfo>();
161     if (stringOption != nullptr && stringOption->isEnumerated())
162     {
163         std::string completion("compgen -S ' ' -W $'");
164         completion.append(joinStrings(stringOption->allowedValues(), "\\n"));
165         completion.append("' -- $c");
166         writeOptionCompletion(option, completion);
167         return;
168     }
169 }
170
171 void OptionCompletionWriter::writeOptionCompletion(
172         const OptionInfo &option, const std::string &completion)
173 {
174     std::string result(formatString("-%s) ", option.name().c_str()));
175     if (option.maxValueCount() >= 0)
176     {
177         result.append(formatString("(( $n <= %d )) && ", option.maxValueCount()));
178     }
179     result.append("COMPREPLY=( $(");
180     result.append(completion);
181     result.append("));;");
182     out_.writeLine(result);
183 }
184
185 }   // namespace
186
187 class ShellCompletionWriter::Impl
188 {
189     public:
190         Impl(const std::string &binaryName, ShellCompletionFormat /*format*/)
191             : binaryName_(binaryName)
192         {
193         }
194
195         std::string completionFunctionName(const char *moduleName) const
196         {
197             std::string result =
198                 formatString("_%s_%s_compl", binaryName_.c_str(), moduleName);
199             std::replace(result.begin(), result.end(), '-', '_');
200             return result;
201         }
202
203         std::string                   binaryName_;
204         // Never releases ownership.
205         std::unique_ptr<TextWriter>   file_;
206 };
207
208 ShellCompletionWriter::ShellCompletionWriter(const std::string     &binaryName,
209                                              ShellCompletionFormat  format)
210     : impl_(new Impl(binaryName, format))
211 {
212 }
213
214 ShellCompletionWriter::~ShellCompletionWriter()
215 {
216 }
217
218 TextWriter &ShellCompletionWriter::outputWriter()
219 {
220     return *impl_->file_;
221 }
222
223 void ShellCompletionWriter::startCompletions()
224 {
225     impl_->file_ = compat::make_unique<TextWriter>(impl_->binaryName_ + "-completion.bash");
226 }
227
228 void ShellCompletionWriter::writeModuleCompletions(
229         const char    *moduleName,
230         const Options &options)
231 {
232     TextWriter &out = *impl_->file_;
233     out.writeLine(formatString("%s() {", impl_->completionFunctionName(moduleName).c_str()));
234     out.writeLine("local IFS=$'\\n'");
235     out.writeLine("local c=${COMP_WORDS[COMP_CWORD]}");
236     out.writeLine("local n");
237     out.writeLine("for ((n=1;n<COMP_CWORD;++n)) ; do [[ \"${COMP_WORDS[COMP_CWORD-n]}\" == -* ]] && break ; done");
238     out.writeLine("local p=${COMP_WORDS[COMP_CWORD-n]}");
239     out.writeLine("COMPREPLY=()");
240
241     OptionsListWriter listWriter;
242     listWriter.visitSection(options.rootSection());
243     out.writeLine(formatString("if (( $COMP_CWORD <= 1 )) || [[ $c == -* ]]; then COMPREPLY=( $(compgen -S ' '  -W $'%s' -- $c)); return 0; fi", listWriter.optionList().c_str()));
244
245     out.writeLine("case \"$p\" in");
246     OptionCompletionWriter optionWriter(&out);
247     optionWriter.visitSection(options.rootSection());
248     out.writeLine("esac }");
249 }
250
251 void ShellCompletionWriter::writeWrapperCompletions(
252         const ModuleNameList &modules, const Options &options)
253 {
254     impl_->file_->writeLine("_" + impl_->binaryName_ + "_compl() {");
255     impl_->file_->writeLine("local i c m");
256     impl_->file_->writeLine("local IFS=$'\\n'\n");
257     impl_->file_->writeLine("COMPREPLY=()");
258     impl_->file_->writeLine("unset COMP_WORDS[0]");
259     impl_->file_->writeLine("for ((i=1;i<COMP_CWORD;++i)) ; do");
260     impl_->file_->writeLine("[[ \"${COMP_WORDS[i]}\" != -* ]] && break");
261     impl_->file_->writeLine("unset COMP_WORDS[i]");
262     impl_->file_->writeLine("done");
263     impl_->file_->writeLine("if (( i == COMP_CWORD )); then");
264     impl_->file_->writeLine("c=${COMP_WORDS[COMP_CWORD]}");
265     OptionsListWriter lister;
266     lister.visitSection(options.rootSection());
267     std::string       completions(lister.optionList());
268     for (ModuleNameList::const_iterator i = modules.begin();
269          i != modules.end(); ++i)
270     {
271         completions.append("\\n");
272         completions.append(*i);
273     }
274     impl_->file_->writeLine("COMPREPLY=( $(compgen -S ' ' -W $'" + completions + "' -- $c) )");
275     impl_->file_->writeLine("return 0");
276     impl_->file_->writeLine("fi");
277     impl_->file_->writeLine("m=${COMP_WORDS[i]}");
278     impl_->file_->writeLine("COMP_WORDS=( \"${COMP_WORDS[@]}\" )");
279     impl_->file_->writeLine("COMP_CWORD=$((COMP_CWORD-i))");
280     impl_->file_->writeLine("case \"$m\" in");
281     for (ModuleNameList::const_iterator i = modules.begin();
282          i != modules.end(); ++i)
283     {
284         const char *const name = i->c_str();
285         impl_->file_->writeLine(formatString("%s) %s ;;", name,
286                                              impl_->completionFunctionName(name).c_str()));
287     }
288     impl_->file_->writeLine("esac }");
289 }
290
291 void ShellCompletionWriter::finishCompletions()
292 {
293     impl_->file_->close();
294     impl_->file_.reset();
295 }
296
297 } // namespace gmx