1#!/usr/bin/env python3
2# Copyright 2021 The Pigweed Authors
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may not
5# use this file except in compliance with the License. You may obtain a copy of
6# the License at
7#
8#     https://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations under
14# the License.
15"""Emulation of `cp -af src dest`."""
16
17import logging
18import os
19import shutil
20import sys
21
22_LOG = logging.getLogger(__name__)
23
24
25def copy_with_metadata(src, dest):
26    """Emulation of `cp -af in out` command."""
27    if not os.path.exists(src):
28        _LOG.error('No such file or directory.')
29        return -1
30
31    try:
32        if os.path.isdir(src):
33            shutil.copytree(src, dest, symlinks=True)
34        else:
35            shutil.copy2(src, dest, follow_symlinks=False)
36    except:  # pylint: disable=bare-except
37        _LOG.exception('Error during copying procedure.')
38        return -1
39
40    return 0
41
42
43def main():
44    # Require exactly two arguments, source and destination.
45    if (len(sys.argv) - 1) != 2:
46        _LOG.error('Incorrect parameters provided.')
47        return -1
48
49    return copy_with_metadata(sys.argv[1], sys.argv[2])
50
51
52if __name__ == '__main__':
53    sys.exit(main())
54