2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements gmx::CommandLineProgramContext.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_commandline
42 #include "cmdlineprogramcontext.h"
54 #include <boost/scoped_ptr.hpp>
56 #include "gromacs/legacyheaders/thread_mpi/mutex.h"
58 #include "gromacs/utility/exceptions.h"
59 #include "gromacs/utility/file.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/path.h"
62 #include "gromacs/utility/stringutil.h"
70 //! \addtogroup module_commandline
74 * Quotes a string if it contains spaces.
76 std::string quoteIfNecessary(const char *str)
78 const bool bSpaces = (std::strchr(str, ' ') != NULL);
81 return formatString("'%s'", str);
87 * Default implementation for ExecutableEnvironmentInterface.
89 * Used if ExecutableEnvironmentInterface is not explicitly provided when
90 * constructing CommandLineProgramContext.
92 class DefaultExecutableEnvironment : public ExecutableEnvironmentInterface
95 //! Allocates a default environment.
96 static ExecutableEnvironmentPointer create()
98 return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
101 DefaultExecutableEnvironment()
102 : initialWorkingDirectory_(Path::getWorkingDirectory())
106 virtual std::string getWorkingDirectory() const
108 return initialWorkingDirectory_;
110 virtual std::vector<std::string> getExecutablePaths() const
112 return Path::getExecutablePaths();
116 std::string initialWorkingDirectory_;
120 * Finds the absolute path of the binary from \c argv[0].
122 * \param[in] invokedName \c argv[0] the binary was invoked with.
123 * \param[in] env Executable environment.
124 * \returns The full path of the binary.
126 * If a binary with the given name cannot be located, \p invokedName is
129 std::string findFullBinaryPath(const std::string &invokedName,
130 const ExecutableEnvironmentInterface &env)
132 std::string searchName = invokedName;
133 // On Windows & Cygwin we need to add the .exe extension,
134 // or we wont be able to detect that the file exists.
135 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
136 if (!endsWith(searchName, ".exe"))
138 searchName.append(".exe");
141 if (!Path::containsDirectory(searchName))
143 // No directory in name means it must be in the path - search it!
144 std::vector<std::string> pathEntries = env.getExecutablePaths();
145 std::vector<std::string>::const_iterator i;
146 for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
148 const std::string &dir = i->empty() ? env.getWorkingDirectory() : *i;
149 std::string testPath = Path::join(dir, searchName);
150 if (File::exists(testPath))
156 else if (!Path::isAbsolute(searchName))
158 // Name contains directories, but is not absolute, i.e.,
159 // it is relative to the current directory.
160 std::string cwd = env.getWorkingDirectory();
161 std::string testPath = Path::join(cwd, searchName);
171 /********************************************************************
172 * CommandLineProgramContext::Impl
175 class CommandLineProgramContext::Impl
179 Impl(int argc, const char *const argv[],
180 ExecutableEnvironmentPointer env);
182 ExecutableEnvironmentPointer executableEnv_;
183 std::string invokedName_;
184 std::string programName_;
185 std::string displayName_;
186 std::string commandLine_;
187 mutable std::string fullBinaryPath_;
188 mutable tMPI::mutex binaryPathMutex_;
191 CommandLineProgramContext::Impl::Impl()
192 : programName_("GROMACS")
196 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
197 ExecutableEnvironmentPointer env)
198 : executableEnv_(move(env))
200 invokedName_ = (argc != 0 ? argv[0] : "");
201 programName_ = Path::splitToPathAndFilename(invokedName_).second;
202 programName_ = stripSuffixIfPresent(programName_, ".exe");
204 commandLine_ = quoteIfNecessary(programName_.c_str());
205 for (int i = 1; i < argc; ++i)
207 commandLine_.append(" ");
208 commandLine_.append(quoteIfNecessary(argv[i]));
212 /********************************************************************
213 * CommandLineProgramContext
216 CommandLineProgramContext::CommandLineProgramContext()
221 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
222 : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
226 CommandLineProgramContext::CommandLineProgramContext(
227 int argc, const char *const argv[])
228 : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
232 CommandLineProgramContext::CommandLineProgramContext(
233 int argc, const char *const argv[], ExecutableEnvironmentPointer env)
234 : impl_(new Impl(argc, argv, move(env)))
238 CommandLineProgramContext::~CommandLineProgramContext()
242 void CommandLineProgramContext::setDisplayName(const std::string &name)
244 GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
245 "Can only set display name once");
246 impl_->displayName_ = name;
249 const char *CommandLineProgramContext::programName() const
251 return impl_->programName_.c_str();
254 const char *CommandLineProgramContext::displayName() const
256 return impl_->displayName_.empty()
257 ? impl_->programName_.c_str()
258 : impl_->displayName_.c_str();
261 const char *CommandLineProgramContext::commandLine() const
263 return impl_->commandLine_.c_str();
266 const char *CommandLineProgramContext::fullBinaryPath() const
268 tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
269 if (impl_->fullBinaryPath_.empty())
271 impl_->fullBinaryPath_ =
273 Path::resolveSymlinks(
274 findFullBinaryPath(impl_->invokedName_,
275 *impl_->executableEnv_)));
276 // TODO: Investigate/Consider using a dladdr()-based solution.
277 // Potentially less portable, but significantly simpler, and also works
278 // with user binaries even if they are located in some arbitrary location,
279 // as long as shared libraries are used.
281 return impl_->fullBinaryPath_.c_str();