libbtrfsutil: add btrfs_util_is_subvolume() and btrfs_util_subvolume_id()
[platform/upstream/btrfs-progs.git] / libbtrfsutil / python / subvolume.c
1 /*
2  * Copyright (C) 2018 Facebook
3  *
4  * This file is part of libbtrfsutil.
5  *
6  * libbtrfsutil is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * libbtrfsutil is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with libbtrfsutil.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "btrfsutilpy.h"
21
22 PyObject *is_subvolume(PyObject *self, PyObject *args, PyObject *kwds)
23 {
24         static char *keywords[] = {"path", NULL};
25         struct path_arg path = {.allow_fd = true};
26         enum btrfs_util_error err;
27
28         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&:is_subvolume",
29                                          keywords, &path_converter, &path))
30                 return NULL;
31
32         if (path.path)
33                 err = btrfs_util_is_subvolume(path.path);
34         else
35                 err = btrfs_util_is_subvolume_fd(path.fd);
36         if (err == BTRFS_UTIL_OK) {
37                 path_cleanup(&path);
38                 Py_RETURN_TRUE;
39         } else if (err == BTRFS_UTIL_ERROR_NOT_BTRFS ||
40                    err == BTRFS_UTIL_ERROR_NOT_SUBVOLUME) {
41                 path_cleanup(&path);
42                 Py_RETURN_FALSE;
43         } else {
44                 SetFromBtrfsUtilErrorWithPath(err, &path);
45                 path_cleanup(&path);
46                 return NULL;
47         }
48 }
49
50 PyObject *subvolume_id(PyObject *self, PyObject *args, PyObject *kwds)
51 {
52         static char *keywords[] = {"path", NULL};
53         struct path_arg path = {.allow_fd = true};
54         enum btrfs_util_error err;
55         uint64_t id;
56
57         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&:subvolume_id",
58                                          keywords, &path_converter, &path))
59                 return NULL;
60
61         if (path.path)
62                 err = btrfs_util_subvolume_id(path.path, &id);
63         else
64                 err = btrfs_util_subvolume_id_fd(path.fd, &id);
65         if (err) {
66                 SetFromBtrfsUtilErrorWithPath(err, &path);
67                 path_cleanup(&path);
68                 return NULL;
69         }
70
71         path_cleanup(&path);
72         return PyLong_FromUnsignedLongLong(id);
73 }