88d64ab8c627d2060d5abbedaabc4e905ff21177
[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, 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/fileio/filetypes.h"
57 #include "gromacs/options/basicoptions.h"
58 #include "gromacs/options/filenameoption.h"
59 #include "gromacs/options/options.h"
60 #include "gromacs/options/optionsvisitor.h"
61 #include "gromacs/utility/arrayref.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/stringutil.h"
65 #include "gromacs/utility/textwriter.h"
66
67 namespace gmx
68 {
69
70 namespace
71 {
72
73 class OptionsListWriter : public OptionsVisitor
74 {
75     public:
76         const std::string &optionList() const { return optionList_; }
77
78         virtual void visitSection(const OptionSectionInfo &section)
79         {
80             OptionsIterator iterator(section);
81             iterator.acceptSections(this);
82             iterator.acceptOptions(this);
83         }
84         virtual void visitOption(const OptionInfo &option)
85         {
86             if (option.isHidden())
87             {
88                 return;
89             }
90             if (!optionList_.empty())
91             {
92                 optionList_.append("\\n");
93             }
94             optionList_.append("-");
95             const BooleanOptionInfo *booleanOption
96                 = option.toType<BooleanOptionInfo>();
97             if (booleanOption != NULL && booleanOption->defaultValue())
98             {
99                 optionList_.append("no");
100             }
101             optionList_.append(option.name());
102         }
103
104     private:
105         std::string optionList_;
106 };
107
108 class OptionCompletionWriter : public OptionsVisitor
109 {
110     public:
111         explicit OptionCompletionWriter(TextWriter *out) : out_(*out) {}
112
113         virtual void visitSection(const OptionSectionInfo &section)
114         {
115             OptionsIterator iterator(section);
116             iterator.acceptSections(this);
117             iterator.acceptOptions(this);
118         }
119         virtual void visitOption(const OptionInfo &option);
120
121     private:
122         void writeOptionCompletion(const OptionInfo  &option,
123                                    const std::string &completion);
124
125         TextWriter &out_;
126 };
127
128 void OptionCompletionWriter::visitOption(const OptionInfo &option)
129 {
130     if (option.isHidden())
131     {
132         return;
133     }
134     const FileNameOptionInfo *fileOption = option.toType<FileNameOptionInfo>();
135     if (fileOption != NULL)
136     {
137         if (fileOption->isDirectoryOption())
138         {
139             writeOptionCompletion(option, "compgen -S ' ' -d $c");
140             return;
141         }
142         const FileNameOptionInfo::ExtensionList &extensionList = fileOption->extensions();
143         if (extensionList.empty())
144         {
145             return;
146         }
147         std::string completion("compgen -S ' ' -X '!*");
148         std::string extensions(joinStrings(extensionList, "|"));
149         if (extensionList.size() > 1)
150         {
151             extensions = "@(" + extensions + ")";
152         }
153         completion.append(extensions);
154         // TODO: Don't duplicate this from filenm.c/futil.c.
155         completion.append("?(.gz|.Z)' -f -- $c ; compgen -S '/' -d $c");
156         writeOptionCompletion(option, completion);
157         return;
158     }
159     const StringOptionInfo *stringOption = option.toType<StringOptionInfo>();
160     if (stringOption != NULL && stringOption->isEnumerated())
161     {
162         std::string completion("compgen -S ' ' -W $'");
163         completion.append(joinStrings(stringOption->allowedValues(), "\\n"));
164         completion.append("' -- $c");
165         writeOptionCompletion(option, completion);
166         return;
167     }
168 }
169
170 void OptionCompletionWriter::writeOptionCompletion(
171         const OptionInfo &option, const std::string &completion)
172 {
173     std::string result(formatString("-%s) ", option.name().c_str()));
174     if (option.maxValueCount() >= 0)
175     {
176         result.append(formatString("(( $n <= %d )) && ", option.maxValueCount()));
177     }
178     result.append("COMPREPLY=( $(");
179     result.append(completion);
180     result.append("));;");
181     out_.writeLine(result);
182 }
183
184 }   // namespace
185
186 class ShellCompletionWriter::Impl
187 {
188     public:
189         Impl(const std::string &binaryName, ShellCompletionFormat /*format*/)
190             : binaryName_(binaryName)
191         {
192         }
193
194         std::string completionFunctionName(const char *moduleName) const
195         {
196             std::string result =
197                 formatString("_%s_%s_compl", binaryName_.c_str(), moduleName);
198             std::replace(result.begin(), result.end(), '-', '_');
199             return result;
200         }
201
202         std::string                   binaryName_;
203         // Never releases ownership.
204         std::unique_ptr<TextWriter>   file_;
205 };
206
207 ShellCompletionWriter::ShellCompletionWriter(const std::string     &binaryName,
208                                              ShellCompletionFormat  format)
209     : impl_(new Impl(binaryName, format))
210 {
211 }
212
213 ShellCompletionWriter::~ShellCompletionWriter()
214 {
215 }
216
217 TextWriter &ShellCompletionWriter::outputWriter()
218 {
219     return *impl_->file_;
220 }
221
222 void ShellCompletionWriter::startCompletions()
223 {
224     impl_->file_.reset(new TextWriter(impl_->binaryName_ + "-completion.bash"));
225 }
226
227 void ShellCompletionWriter::writeModuleCompletions(
228         const char    *moduleName,
229         const Options &options)
230 {
231     TextWriter &out = *impl_->file_;
232     out.writeLine(formatString("%s() {", impl_->completionFunctionName(moduleName).c_str()));
233     out.writeLine("local IFS=$'\\n'");
234     out.writeLine("local c=${COMP_WORDS[COMP_CWORD]}");
235     out.writeLine("local n");
236     out.writeLine("for ((n=1;n<COMP_CWORD;++n)) ; do [[ \"${COMP_WORDS[COMP_CWORD-n]}\" == -* ]] && break ; done");
237     out.writeLine("local p=${COMP_WORDS[COMP_CWORD-n]}");
238     out.writeLine("COMPREPLY=()");
239
240     OptionsListWriter listWriter;
241     listWriter.visitSection(options.rootSection());
242     out.writeLine(formatString("if (( $COMP_CWORD <= 1 )) || [[ $c == -* ]]; then COMPREPLY=( $(compgen -S ' '  -W $'%s' -- $c)); return 0; fi", listWriter.optionList().c_str()));
243
244     out.writeLine("case \"$p\" in");
245     OptionCompletionWriter optionWriter(&out);
246     optionWriter.visitSection(options.rootSection());
247     out.writeLine("esac }");
248 }
249
250 void ShellCompletionWriter::writeWrapperCompletions(
251         const ModuleNameList &modules, const Options &options)
252 {
253     impl_->file_->writeLine("_" + impl_->binaryName_ + "_compl() {");
254     impl_->file_->writeLine("local i c m");
255     impl_->file_->writeLine("local IFS=$'\\n'\n");
256     impl_->file_->writeLine("COMPREPLY=()");
257     impl_->file_->writeLine("unset COMP_WORDS[0]");
258     impl_->file_->writeLine("for ((i=1;i<COMP_CWORD;++i)) ; do");
259     impl_->file_->writeLine("[[ \"${COMP_WORDS[i]}\" != -* ]] && break");
260     impl_->file_->writeLine("unset COMP_WORDS[i]");
261     impl_->file_->writeLine("done");
262     impl_->file_->writeLine("if (( i == COMP_CWORD )); then");
263     impl_->file_->writeLine("c=${COMP_WORDS[COMP_CWORD]}");
264     OptionsListWriter lister;
265     lister.visitSection(options.rootSection());
266     std::string       completions(lister.optionList());
267     for (ModuleNameList::const_iterator i = modules.begin();
268          i != modules.end(); ++i)
269     {
270         completions.append("\\n");
271         completions.append(*i);
272     }
273     impl_->file_->writeLine("COMPREPLY=( $(compgen -S ' ' -W $'" + completions + "' -- $c) )");
274     impl_->file_->writeLine("return 0");
275     impl_->file_->writeLine("fi");
276     impl_->file_->writeLine("m=${COMP_WORDS[i]}");
277     impl_->file_->writeLine("COMP_WORDS=( \"${COMP_WORDS[@]}\" )");
278     impl_->file_->writeLine("COMP_CWORD=$((COMP_CWORD-i))");
279     impl_->file_->writeLine("case \"$m\" in");
280     for (ModuleNameList::const_iterator i = modules.begin();
281          i != modules.end(); ++i)
282     {
283         const char *const name = i->c_str();
284         impl_->file_->writeLine(formatString("%s) %s ;;", name,
285                                              impl_->completionFunctionName(name).c_str()));
286     }
287     impl_->file_->writeLine("esac }");
288 }
289
290 void ShellCompletionWriter::finishCompletions()
291 {
292     impl_->file_->close();
293     impl_->file_.reset();
294 }
295
296 } // namespace gmx