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