[ci] Enable IRC notifications from travis
[xapian.git] / xapian-core / common / append_filename_arg.h
blobf09640a8e58213c84e5880673bad4976697560bb
1 /** @file append_filename_arg.h
2 * @brief Append filename argument to a command string with suitable escaping
3 */
4 /* Copyright (C) 2003,2004,2007,2012 Olly Betts
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 #ifndef XAPIAN_INCLUDED_APPEND_FILENAME_ARG_H
22 #define XAPIAN_INCLUDED_APPEND_FILENAME_ARG_H
24 #include <cstring>
25 #include <string>
27 /// Append filename argument arg to command cmd with suitable escaping.
28 static bool
29 append_filename_argument(std::string & cmd, const std::string & arg) {
30 #ifdef __WIN32__
31 cmd.reserve(cmd.size() + arg.size() + 5);
32 // Prevent a leading "-" on the filename being interpreted as a command
33 // line option.
34 if (arg[0] == '-')
35 cmd += " \".\\";
36 else
37 cmd += " \"";
39 for (std::string::const_iterator i = arg.begin(); i != arg.end(); ++i) {
40 if (*i == '/') {
41 // Convert Unix path separators to backslashes. C library
42 // functions understand "/" in paths, but we are going to
43 // call commands like "xcopy" or "rd" which don't.
44 cmd += '\\';
45 } else if (*i < 32 || std::strchr("<>\"|*?", *i)) {
46 // Check for illegal characters in filename.
47 return false;
48 } else {
49 cmd += *i;
52 cmd += '"';
53 #else
54 // Allow for the typical case of a filename without single quote characters
55 // in - this reserving is just an optimisation, and the string will grow
56 // larger if necessary.
57 cmd.reserve(cmd.size() + arg.size() + 5);
59 // Prevent a leading "-" on the filename being interpreted as a command
60 // line option.
61 if (arg[0] == '-')
62 cmd += " './";
63 else
64 cmd += " '";
66 for (std::string::const_iterator i = arg.begin(); i != arg.end(); ++i) {
67 if (*i == '\'') {
68 // Wrapping the whole argument in single quotes works for
69 // everything except a single quote - for that we drop out of
70 // single quotes, then use a backslash-escaped single quote, then
71 // re-enter single quotes.
72 cmd += "'\\''";
73 continue;
75 cmd += *i;
77 cmd += '\'';
78 #endif
79 return true;
82 #endif // XAPIAN_INCLUDED_APPEND_FILENAME_ARG_H