From 5303ec39f6f08ccf06f56ff6d5166fc572b2c735 Mon Sep 17 00:00:00 2001 From: Christian Poessinger Date: Sat, 26 Jun 2021 09:17:52 +0200 Subject: vyos.util: add new helper copy_file() Copy a file from A -> B but also support adjusting Bs file permissions and creation of Bs base directory if required. --- python/vyos/util.py | 13 +++++++++++++ src/tests/test_util.py | 10 ++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/python/vyos/util.py b/python/vyos/util.py index 7fea6cdc6..c318d58de 100644 --- a/python/vyos/util.py +++ b/python/vyos/util.py @@ -221,6 +221,19 @@ def write_file(fname, data, defaultonfailure=None, user=None, group=None): return defaultonfailure raise e +def copy_file(source, destination, mkdstdir=False, user=None, group=None): + """ + Copy file from source to destination. Can optionally create the destination + dir if it does not exist. Can optionally change the dir and file ownership. + """ + import shutil + if mkdstdir: + dirname = os.path.dirname(destination) + if not os.path.isdir(dirname): + makedir(dirname, user, group) + + shutil.copyfile(source, destination) + chown(destination, user, group) def read_json(fname, defaultonfailure=None): """ diff --git a/src/tests/test_util.py b/src/tests/test_util.py index 22bc085c5..1efd4868f 100644 --- a/src/tests/test_util.py +++ b/src/tests/test_util.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # -# Copyright (C) 2020 VyOS maintainers and contributors +# Copyright (C) 2020-2021 VyOS maintainers and contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 or later as @@ -15,7 +15,7 @@ # along with this program. If not, see . from unittest import TestCase -from vyos.util import mangle_dict_keys +from vyos.util import * class TestVyOSUtil(TestCase): def test_key_mangline(self): @@ -24,3 +24,9 @@ class TestVyOSUtil(TestCase): new_data = mangle_dict_keys(data, '-', '_') self.assertEqual(new_data, expected_data) + def test_copy_file(self): + source = '/proc/cmdline' + destination = '/tmp/foo/cmdline' + copy_file(source, destination, True) + self.assertEqual(read_file(source), read_file(destination)) + -- cgit v1.2.3