diff --git a/src/menu.cpp b/src/menu.cpp index 467d5b8..8fa2c76 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -18,7 +18,6 @@ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ -#include #include #include #include @@ -391,14 +390,7 @@ bool Menu::addLink(string const& path, string const& file) title = title.substr(0, pos); } - string linkpath = sectionDir + "/" + title; - int x = 2; - while (fileExists(linkpath)) { - stringstream ss; - ss << sectionDir << '/' << title << x; - ss >> linkpath; - x++; - } + string linkpath = uniquePath(sectionDir, title); INFO("Adding link: '%s'\n", linkpath.c_str()); string dirPath = path; @@ -541,14 +533,7 @@ bool Menu::moveSelectedLink(string const& newSection) return false; } - string newFileName = sectionDir + "/" + linkTitle; - unsigned int x = 2; - while (fileExists(newFileName)) { - string id = ""; - stringstream ss; ss << x; ss >> id; - newFileName = sectionDir + "/" + linkTitle + id; - x++; - } + string newFileName = uniquePath(sectionDir, linkTitle); if (rename(file.c_str(), newFileName.c_str())) { WARNING("Link file move from '%s' to '%s' failed: %s\n", diff --git a/src/utilities.cpp b/src/utilities.cpp index a30820a..65bc434 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include @@ -160,6 +161,19 @@ bool fileExists(const string &file) { return access(file.c_str(), F_OK) == 0; } +string uniquePath(string const& dir, string const& name) +{ + string path = dir + "/" + name; + unsigned int x = 2; + while (fileExists(path)) { + stringstream ss; + ss << dir << '/' << name << x; + ss >> path; + x++; + } + return path; +} + int constrain(int x, int imin, int imax) { return min(imax, max(imin, x)); } diff --git a/src/utilities.h b/src/utilities.h index e90a031..43a874a 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -80,6 +80,11 @@ inline std::string trimExtension(std::string const& filename) { bool fileExists(const std::string &file); +/** + * Constructs a non-existing path in a given directory based on the given name. + */ +std::string uniquePath(std::string const& dir, std::string const& name); + int constrain(int x, int imin, int imax); int evalIntConf(ConfIntHash& hash, const std::string &key, int def, int imin, int imax);