From 1b54483f21b359721a276b0a74c92deb4829c533 Mon Sep 17 00:00:00 2001 From: Maarten ter Huurne Date: Sun, 26 Apr 2015 21:13:03 +0200 Subject: [PATCH] Put code to construct unique path into new utlity function uniquePath() Two almost identical versions existed of this code. I generalized the code by taking out the knowledge of sections. No other uses of this code are planned, but it is easier to review in isolation now. --- src/menu.cpp | 19 ++----------------- src/utilities.cpp | 14 ++++++++++++++ src/utilities.h | 5 +++++ 3 files changed, 21 insertions(+), 17 deletions(-) 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);