mirror of
https://github.com/GothenburgBitFactory/taskwarrior.git
synced 2025-07-07 20:06:36 +02:00
File::rename
- Added a rename method to permit safe file writes.
This commit is contained in:
parent
d2f267a7da
commit
9fe9f96f8f
3 changed files with 36 additions and 1 deletions
17
src/Path.cpp
17
src/Path.cpp
|
@ -32,6 +32,7 @@
|
|||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <pwd.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <Path.h>
|
||||
#include <cmake.h>
|
||||
|
@ -170,6 +171,22 @@ bool Path::executable () const
|
|||
return access (_data.c_str (), X_OK) ? false : true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
bool Path::rename (const std::string& new_name)
|
||||
{
|
||||
std::string expanded = expand (new_name);
|
||||
if (_data != expanded)
|
||||
{
|
||||
if (::rename (_data.c_str (), expanded.c_str ()) == 0)
|
||||
{
|
||||
_data = expanded;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// ~ --> /home/user
|
||||
// ~foo/x --> /home/foo/s
|
||||
|
|
|
@ -54,6 +54,7 @@ public:
|
|||
bool readable () const;
|
||||
bool writable () const;
|
||||
bool executable () const;
|
||||
bool rename (const std::string&);
|
||||
|
||||
// Statics
|
||||
static std::string expand (const std::string&);
|
||||
|
|
|
@ -34,7 +34,7 @@ Context context;
|
|||
|
||||
int main (int argc, char** argv)
|
||||
{
|
||||
UnitTest t (6);
|
||||
UnitTest t (13);
|
||||
|
||||
File::write ("/tmp/file.t.txt", "This is a test\n");
|
||||
File f6 ("/tmp/file.t.txt");
|
||||
|
@ -48,6 +48,23 @@ int main (int argc, char** argv)
|
|||
t.ok (File::create ("/tmp/file.t.create"), "File::create /tmp/file.t.create good");
|
||||
t.ok (File::remove ("/tmp/file.t.create"), "File::remove /tmp/file.t.create good");
|
||||
|
||||
// basename (std::string) const;
|
||||
t.is (f6.name (), "file.t.txt", "File::basename /tmp/file.t.txt --> file.t.txt");
|
||||
|
||||
// dirname (std::string) const;
|
||||
t.is (f6.parent (), "/tmp", "File::dirname /tmp/file.t.txt --> /tmp");
|
||||
|
||||
// bool rename (const std::string&);
|
||||
File f7 ("/tmp/file.t.2.txt");
|
||||
f7.append ("something\n");
|
||||
f7.close ();
|
||||
|
||||
t.ok (f7.rename ("/tmp/file.t.3.txt"), "File::rename did not fail");
|
||||
t.is (f7._data, "/tmp/file.t.3.txt", "File::rename stored new name");
|
||||
t.ok (f7.exists (), "File::rename new file exists");
|
||||
t.ok (f7.remove (), "File::remove /tmp/file.t.3.txt good");
|
||||
t.notok (f7.exists (), "File::remove new file no longer exists");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue