aboutsummaryrefslogtreecommitdiff
path: root/zen/cmds/copy.cpp
blob: c9b40408e57a3cb96566331034f2b0140d8e7e12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright Epic Games, Inc. All Rights Reserved.

#include "copy.h"

#include <zencore/filesystem.h>
#include <zencore/logging.h>
#include <zencore/string.h>
#include <zencore/timer.h>

namespace zen {

CopyCommand::CopyCommand()
{
	m_Options.add_options()("h,help", "Print help");
	m_Options.add_options()("no-clone", "Do not perform block clone", cxxopts::value(m_NoClone)->default_value("false"));
	m_Options.add_option("", "s", "source", "Copy source", cxxopts::value(m_CopySource), "<file/directory>");
	m_Options.add_option("", "t", "target", "Copy target", cxxopts::value(m_CopyTarget), "<file/directory>");
	m_Options.add_option("", "", "positional", "Positional arguments", cxxopts::value(m_Positional), "");
}

CopyCommand::~CopyCommand() = default;

int
CopyCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions);

	m_Options.parse_positional({"source", "target", "positional"});

	auto result = m_Options.parse(argc, argv);

	if (result.count("help"))
	{
		std::cout << m_Options.help({"", "Group"}) << std::endl;

		return 0;
	}

	// Validate arguments

	if (m_CopySource.empty())
		throw std::runtime_error("No source specified");

	if (m_CopyTarget.empty())
		throw std::runtime_error("No target specified");

	std::filesystem::path FromPath;
	std::filesystem::path ToPath;

	FromPath = m_CopySource;
	ToPath	 = m_CopyTarget;

	const bool IsFileCopy = std::filesystem::is_regular_file(m_CopySource);
	const bool IsDirCopy  = std::filesystem::is_directory(m_CopySource);

	if (!IsFileCopy && !IsDirCopy)
	{
		throw std::runtime_error("Invalid source specification (neither directory nor file)");
	}

	if (IsFileCopy && IsDirCopy)
	{
		throw std::runtime_error("Invalid source specification (both directory AND file!?)");
	}

	if (IsDirCopy)
	{
		if (std::filesystem::exists(ToPath))
		{
			const bool IsTargetDir = std::filesystem::is_directory(ToPath);
			if (!IsTargetDir)
			{
				if (std::filesystem::is_regular_file(ToPath))
				{
					throw std::runtime_error("Attempted copy of directory into file");
				}
			}
		}
		else
		{
			std::filesystem::create_directories(ToPath);
		}
	}
	else
	{
		// Single file copy

		zen::Stopwatch Timer;

		zen::CopyFileOptions CopyOptions;
		CopyOptions.EnableClone = !m_NoClone;
		zen::CopyFile(FromPath, ToPath, CopyOptions);

		ZEN_INFO("Copy completed in {}", zen::NiceTimeSpanMs(Timer.GetElapsedTimeMs()));
	}

	return 0;
}

}  // namespace zen