restructure cp-version
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
import os, argparse
|
||||
from shutil import copyfile
|
||||
from datetime import datetime
|
||||
|
||||
def get_options():
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -10,16 +11,21 @@ def get_options():
|
||||
help = "Move file instead of copying",
|
||||
default = False
|
||||
)
|
||||
parser.add_argument('-d', action = "store_true", dest = "date",
|
||||
help = "Use file date+time as version number",
|
||||
default = False
|
||||
)
|
||||
parser.add_argument(action = "store", dest = "file")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def file_versionize(full_path, move = False):
|
||||
def get_version_name(full_path):
|
||||
""" Move file to versioned with integer """
|
||||
file_dir = os.path.dirname(full_path)
|
||||
file_name = os.path.basename(full_path)
|
||||
basename, extension = os.path.splitext(file_name)
|
||||
version = 1
|
||||
|
||||
while True:
|
||||
new_name = os.path.join(
|
||||
file_dir,
|
||||
@@ -33,16 +39,43 @@ def file_versionize(full_path, move = False):
|
||||
version += 1
|
||||
else:
|
||||
break
|
||||
print("%s -> %s"%(
|
||||
full_path,
|
||||
new_name
|
||||
))
|
||||
if move:
|
||||
os.rename(full_path, new_name)
|
||||
else:
|
||||
copyfile(full_path, new_name)
|
||||
return new_name
|
||||
|
||||
|
||||
def get_date_name(full_path):
|
||||
""" Move file to versioned with integer """
|
||||
file_dir = os.path.dirname(full_path)
|
||||
file_name = os.path.basename(full_path)
|
||||
basename, extension = os.path.splitext(file_name)
|
||||
file_time = os.stat(full_path).st_mtime
|
||||
time_formatted = datetime.fromtimestamp(
|
||||
file_time
|
||||
).strftime("%Y%m%d_%H%M%S")
|
||||
|
||||
new_name = os.path.join(
|
||||
file_dir,
|
||||
"%s.%s%s"%(
|
||||
basename,
|
||||
time_formatted,
|
||||
extension
|
||||
)
|
||||
)
|
||||
return new_name
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opts = get_options()
|
||||
file_versionize(opts.file, opts.move)
|
||||
if os.path.isdir(opts.file):
|
||||
raise ValueError("Can not handle directories")
|
||||
if opts.date:
|
||||
new_name = get_date_name(opts.file)
|
||||
else:
|
||||
new_name = get_version_name(opts.file)
|
||||
print("%s -> %s"%(
|
||||
opts.file,
|
||||
new_name
|
||||
))
|
||||
if opts.move:
|
||||
os.rename(opts.file, new_name)
|
||||
else:
|
||||
copyfile(opts.file, new_name)
|
||||
|
||||
Reference in New Issue
Block a user