jsi_util_linux 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 22c53472ee3be81594f1e682b72e0e044f04c9827ec6d3a9efeaa84bdcb16fdc
4
+ data.tar.gz: fffa8403367f74471fcda515c8874f1fbe59dd84a47bd84874e3210745e35623
5
+ SHA512:
6
+ metadata.gz: 69f713f3748a16ce4f42174ffa1a02ad9995599ddb803b5a3d117476d3e7af568c8fdc78d752ed7f9c001e49367dc709dab546fa9a77ff47a18fb22400a5e132
7
+ data.tar.gz: 1df26fae74c30d14853b850ed8a072c8a1a1760877d2acf1a01411a6c032835fc7646edbf55c2019e2774a250297d159d9fd77e641bd828af52f28e018e828d4
data/.yardopts ADDED
@@ -0,0 +1,6 @@
1
+ --main README.md
2
+ --markup=markdown
3
+ --markup-provider=commonmarker
4
+ --no-private
5
+ --hide-void-return
6
+ lib/**/*.rb
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Ethan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # JSIUtilLinux
2
+
3
+ This library interacts with certain utilities of `util-linux` (see [Wikipedia](https://en.wikipedia.org/wiki/Util-linux), [kernel.org](https://git.kernel.org/pub/scm/utils/util-linux/util-linux.git), [Github](https://github.com/util-linux/util-linux)) and offers an object-oriented representation for their results. This uses the JSON output of those utilities, JSON Schemas describing that, and the [JSI gem](https://github.com/notEthan/jsi).
4
+
5
+ ## Usage
6
+
7
+ Methods named after supported utilities are defined on {JSIUtilLinux}. Arguments passed to these are transformed from convenient Ruby expressions to CLI arguments - see {JSIUtilLinux.args_to_argv}; note that Symbols become hyphenated dash arguments.
8
+
9
+ What arguments are recognized, and their defaults, vary by system or utility version - see e.g. `lsblk --help` and `man lsblk` for more information.
10
+
11
+ Supported utilities are:
12
+
13
+ - {JSIUtilLinux.lsblk} for [`lsblk`](https://linux.die.net/man/8/lsblk)
14
+ - {JSIUtilLinux.findmnt} for [`findmnt`](https://linux.die.net/man/8/findmnt)
15
+ - {JSIUtilLinux.losetup_ls} for [`losetup --list`](https://linux.die.net/man/8/losetup) (other modes of `losetup` than `--list` are not supported)
16
+
17
+ ### Examples
18
+
19
+ ```ruby
20
+ JSIUtilLinux.lsblk
21
+ ```
22
+
23
+ returns:
24
+
25
+ ```
26
+ #{<JSI (JSIUtilLinux::LsBlk)>
27
+ "blockdevices" => #[<JSI (JSIUtilLinux::LsBlk.properties["blockdevices"])>
28
+ #{<JSI (JSIUtilLinux::BlockDev)>
29
+ "name" => "sda",
30
+ "maj:min" => "8:0",
31
+ "size" => "119.2G",
32
+ "type" => "disk",
33
+ "mountpoint" => nil,
34
+ "children" => #[<JSI (JSIUtilLinux::BlockDev.properties["children"])>
35
+ #{<JSI (JSIUtilLinux::BlockDev)>
36
+ "name" => "sda1",
37
+ "maj:min" => "8:1",
38
+ "size" => "1M",
39
+ "type" => "part",
40
+ "mountpoint" => nil
41
+ },
42
+ #{<JSI (JSIUtilLinux::BlockDev)>
43
+ "name" => "sda2",
44
+ "maj:min" => "8:2",
45
+ "size" => "100G",
46
+ "type" => "part",
47
+ "mountpoint" => "/"
48
+ }
49
+ ]
50
+ }
51
+ ]
52
+ }
53
+ ```
54
+
55
+ More examples, arguments:
56
+
57
+ ```ruby
58
+ JSIUtilLinux.lsblk(output: 'name') # lsblk --output name
59
+ JSIUtilLinux.lsblk(:output_all) # lsblk --output-all
60
+ JSIUtilLinux.findmnt
61
+ JSIUtilLinux.findmnt('/dev')
62
+ JSIUtilLinux.findmnt(target: 'path/file')
63
+ JSIUtilLinux.losetup_ls # losetup --list
64
+ JSIUtilLinux.losetup_ls(associated: 'file.img') # losetup --list --associated file.img
65
+ ```
@@ -0,0 +1,25 @@
1
+ require_relative "lib/jsi_util_linux/version"
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "jsi_util_linux"
5
+ spec.version = JSIUtilLinux::VERSION
6
+ spec.authors = ["Ethan"]
7
+ spec.email = ["ethan@unth.net"]
8
+
9
+ spec.summary = "JSI + util-linux"
10
+ spec.description = "util-linux utilities represented with JSI"
11
+ spec.homepage = "https://github.com/notEthan/jsi_util_linux"
12
+ spec.license = "MIT"
13
+
14
+ spec.files = [
15
+ 'LICENSE.txt',
16
+ 'README.md',
17
+ '.yardopts',
18
+ File.basename(__FILE__),
19
+ *Dir['lib/**/*'],
20
+ ].reject { |f| File.lstat(f).ftype == 'directory' }
21
+
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency("jsi", "~> 0.8")
25
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JSIUtilLinux
4
+ findmnt_schema_content = JSI::Util.deep_stringify_symbol_keys({
5
+ "$schema": "http://json-schema.org/draft-07/schema#",
6
+ "type": "object",
7
+ "properties": {
8
+ "filesystems": {
9
+ "type": "array",
10
+ "items": {"$ref": "#/definitions/filesystem"}
11
+ }
12
+ },
13
+ "definitions": {
14
+ "filesystem": {
15
+ "type": "object",
16
+ "properties": {
17
+ "children": {
18
+ "type": "array",
19
+ "items": {"$ref": "#/definitions/filesystem"}
20
+ },
21
+ "action": {},
22
+ "avail": {},
23
+ "freq": {},
24
+ # fsroot: just "/" for a lot of things (no relation to parent, seems like)
25
+ # btrfs: subvolume name e.g. "/@" (/), "/ethan" (/home/ethan)
26
+ # zfs: "/"
27
+ "fsroot": {},
28
+ "fstype": {},
29
+ "fs-options": {},
30
+ "id": {},
31
+ "label": {},
32
+ "maj:min": {},
33
+ "old-options": {},
34
+ "old-target": {},
35
+ "options": {},
36
+ "opt-fields": {},
37
+ "parent": {},
38
+ "partlabel": {},
39
+ "partuuid": {},
40
+ "passno": {},
41
+ "propagation": {},
42
+ "size": {},
43
+ # source: this contains some information about a source (device or whatever) but I don't know the format
44
+ # e.g. "selinuxfs" for target: "/sys/fs/selinux"
45
+ # btrfs: "/dev/mapper/luks-9583[/ethan]" where "ethan" is btrfs subvolume
46
+ # (or "/ethan" is fsroot, but no others include "[#{fsroot}]")
47
+ # no [] when subvolume is volume root
48
+ # zfs: zfs fs name (doesn't start with /; starts with pool name)
49
+ "source": {},
50
+ # I don't know when this contains anything other than source
51
+ "sources": {
52
+ "items": {},
53
+ },
54
+ # this exists in the root filesystem. is this always within its parent's target?
55
+ "target": {},
56
+ "tid": {},
57
+ "used": {},
58
+ "use%": {},
59
+ # only seen this show up for btrfs. it is the root fs uuid, not subvol
60
+ "uuid": {},
61
+ "vfs-options": {},
62
+ }
63
+ }
64
+ }
65
+ })
66
+ findmnt_help_outputs = {
67
+ "ACTION" => "action detected by --poll",
68
+ "AVAIL" => "filesystem size available",
69
+ "FREQ" => "dump(8) period in days [fstab only]",
70
+ "FSROOT" => "filesystem root",
71
+ "FSTYPE" => "filesystem type",
72
+ "FS-OPTIONS" => "FS specific mount options",
73
+ "ID" => "mount ID",
74
+ "LABEL" => "filesystem label",
75
+ "MAJ:MIN" => "major:minor device number",
76
+ "OLD-OPTIONS" => "old mount options saved by --poll",
77
+ "OLD-TARGET" => "old mountpoint saved by --poll",
78
+ "OPTIONS" => "all mount options",
79
+ "OPT-FIELDS" => "optional mount fields",
80
+ "PARENT" => "mount parent ID",
81
+ "PARTLABEL" => "partition label",
82
+ "PARTUUID" => "partition UUID",
83
+ "PASSNO" => "pass number on parallel fsck(8) [fstab only]",
84
+ "PROPAGATION" => "VFS propagation flags",
85
+ "SIZE" => "filesystem size",
86
+ "SOURCE" => "source device",
87
+ "SOURCES" => "all possible source devices",
88
+ "TARGET" => "mountpoint",
89
+ "TID" => "task ID",
90
+ "USED" => "filesystem size used",
91
+ "USE%" => "filesystem use percentage",
92
+ "UUID" => "filesystem UUID",
93
+ "VFS-OPTIONS" => "VFS specific mount options",
94
+ }
95
+ findmnt_help_outputs.each do |k, v|
96
+ (findmnt_schema_content['definitions']['filesystem']['properties'][k.downcase] || raise(k))['description'] = v
97
+ end
98
+
99
+ FindMnt = JSI.new_schema_module(findmnt_schema_content)
100
+ Filesystem = FindMnt.definitions['filesystem']
101
+
102
+
103
+ # a result of invoking {JSIUtilLinux.findmnt}
104
+ module FindMnt
105
+ EMPTY_CONTENT = {"filesystems" => [].freeze}.freeze
106
+
107
+ # @yield [Filesystem]
108
+ # @return [Enumerator, nil]
109
+ def each_filesystem(&block)
110
+ return to_enum(__method__) unless block_given?
111
+ # jsi_each_descendent_node do |n|
112
+ # yield n if n.is_a?(Filesystem)
113
+ # end
114
+ filesystems.each { |fs| fs.each_filesystem(&block) }
115
+ nil
116
+ end
117
+ end
118
+
119
+ # an item in `filesystems` array of a {FindMnt} result
120
+ module Filesystem
121
+ def maj_min
122
+ self['maj:min']
123
+ end
124
+
125
+ def dev_re_match
126
+ (self['maj:min'] || raise("no maj:min present in #{inspect}")).match(/\A(\d+):(\d+)\z/)
127
+ end
128
+
129
+ # @return [Integer]
130
+ def dev_major
131
+ Integer(dev_re_match[1])
132
+ end
133
+
134
+ # @return [Integer]
135
+ def dev_minor
136
+ Integer(dev_re_match[2])
137
+ end
138
+
139
+ # alias of #target
140
+ def mount_point
141
+ # why do you call this 'target', findmnt?
142
+ # 'f_mntonname' from statfs / getmntinfo
143
+ # 'mnt_dir' from sys/mount.h
144
+ # 'mount_point' in rubygem sys/filesystem
145
+ target
146
+ end
147
+
148
+ # @return [Pathname]
149
+ def mount_pathname
150
+ Pathname.new(target)
151
+ end
152
+
153
+ # @return [File::Stat]
154
+ def mount_stat
155
+ File.lstat(target)
156
+ end
157
+
158
+ # @yield [Filesystem]
159
+ # @return [Enumerator, nil]
160
+ def each_filesystem(&block)
161
+ return to_enum(__method__) unless block_given?
162
+ yield self
163
+ children && children.each { |fs| fs.each_filesystem(&block) }
164
+ nil
165
+ end
166
+
167
+ # @return [Filesystem]
168
+ def parent_filesystem
169
+ #jsi_parent_nodes.detect { |n| n.is_a?(Filesystem) }
170
+ jsi_root_node.each_filesystem.detect { |fs| fs.id == parent }
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,4 @@
1
+ require 'jsi_util_linux'
2
+
3
+ # require 'jsi_util_linux/jul' for this abbreviation
4
+ JUL = JSIUtilLinux
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ module JSIUtilLinux
4
+ losetup_list_schema_content = JSI::Util.deep_stringify_symbol_keys({
5
+ "$schema": "http://json-schema.org/draft-07/schema#",
6
+ "type": "object",
7
+ "properties": {
8
+ "loopdevices": {
9
+ "type": "array",
10
+ "items": {"$ref": "#/definitions/loopdevice"}
11
+ }
12
+ },
13
+ "definitions": {
14
+ "loopdevice": {
15
+ "type": "object",
16
+ "properties": {
17
+ "name": {"type": "string"},
18
+ "autoclear": {"type": "boolean"},
19
+ "back-file": {"type": "string"},
20
+ "back-ino": {},
21
+ "back-maj:min": {},
22
+ "maj:min": {"type": "string"},
23
+ "offset": {"type": "integer"},
24
+ "partscan": {"type": "boolean"},
25
+ "ro": {"type": "boolean"},
26
+ "sizelimit": {"type": "integer"},
27
+ "dio": {"type": "boolean"},
28
+ "log-sec": {"type": "integer"},
29
+ }
30
+ }
31
+ }
32
+ })
33
+
34
+ losetup_help_outputs = {
35
+ "NAME" => "loop device name",
36
+ "AUTOCLEAR" => "autoclear flag set",
37
+ "BACK-FILE" => "device backing file",
38
+ "BACK-INO" => "backing file inode number",
39
+ "BACK-MAJ:MIN" => "backing file major:minor device number",
40
+ "MAJ:MIN" => "loop device major:minor number",
41
+ "OFFSET" => "offset from the beginning",
42
+ "PARTSCAN" => "partscan flag set",
43
+ "RO" => "read-only device",
44
+ "SIZELIMIT" => "size limit of the file in bytes",
45
+ "DIO" => "access backing file with direct-io",
46
+ "LOG-SEC" => "logical sector size in bytes",
47
+ }
48
+
49
+ losetup_help_outputs.each do |k, v|
50
+ lp = losetup_list_schema_content['definitions']['loopdevice']['properties'][k.downcase] || raise(k)
51
+ lp['description'] = v
52
+ end
53
+
54
+
55
+ LoSetupList = JSI.new_schema_module(losetup_list_schema_content)
56
+ LoopDev = LoSetupList.definitions['loopdevice']
57
+
58
+
59
+ # a result of invoking {JSIUtilLinux.losetup_ls}
60
+ module LoSetupList
61
+ EMPTY_CONTENT = {"loopdevices" => [].freeze}.freeze
62
+ end
63
+
64
+ # an item in `loopdevices` array of a {LoSetupList} result
65
+ module LoopDev
66
+ end
67
+ end
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ module JSIUtilLinux
4
+ lsblk_schema_content = JSI::Util.deep_stringify_symbol_keys({
5
+ "$schema": "http://json-schema.org/draft-07/schema#",
6
+ "type": "object",
7
+ "properties": {
8
+ "blockdevices": {
9
+ "type": "array",
10
+ "items": {"$ref": "#/definitions/blockdevice"}
11
+ }
12
+ },
13
+ "definitions": {
14
+ "blockdevice": {
15
+ "type": "object",
16
+ "properties": {
17
+ "children": {
18
+ "type": "array",
19
+ "items": {"$ref": "#/definitions/blockdevice"}
20
+ },
21
+ "hctl": {"type": ["null","string"]},
22
+ "log-sec": {"type": "integer"},
23
+ "disc-max": {"type": "string"},
24
+ "ptuuid": {"type": ["null","string"]},
25
+ "pttype": {"type": ["null","string"]},
26
+ "type": {"type": "string"},
27
+ "disc-gran": {"type": "string"},
28
+ "subsystems": {"type": "string"},
29
+ "uuid": {"type": ["null","string"]},
30
+ "mountpoint": {"type": ["null","string"]},
31
+ "wwn": {"type": ["null","string"]},
32
+ "mode": {"type": "string"},
33
+ "rand": {"type": "boolean"},
34
+ "path": {"type": "string"},
35
+ "fsused": {"type": ["null","string"]},
36
+ "dax": {"type": "boolean"},
37
+ "model": {"type": ["null","string"]},
38
+ "state": {"type": ["null","string"]},
39
+ "tran": {"type": ["null","string"]},
40
+ "fstype": {"type": ["null","string"]},
41
+ "group": {"type": "string"},
42
+ "wsame": {"type": "string"},
43
+ "rev": {"type": ["null","string"]},
44
+ "zone-omax": {"type": "integer"},
45
+ "zone-wgran": {"type": "integer"},
46
+ "ra": {"type": "integer"},
47
+ "pkname": {"type": ["null","string"]},
48
+ "sched": {"type": ["string","null"]},
49
+ "size": {"type": "string"},
50
+ "name": {"type": "string"},
51
+ "partlabel": {"type": ["null","string"]},
52
+ "rm": {"type": "boolean"},
53
+ "alignment": {"type": "integer"},
54
+ "ro": {"type": "boolean"},
55
+ "disc-aln": {"type": "integer"},
56
+ "mountpoints": {"type": "array","items": {"type": ["null","string"]}},
57
+ "fsavail": {"type": ["null","string"]},
58
+ "rq-size": {"type": "integer"},
59
+ "disc-zero": {"type": "boolean"},
60
+ "opt-io": {"type": "integer"},
61
+ "zone-amax": {"type": "integer"},
62
+ "parttype": {"type": ["null","string"]},
63
+ "partuuid": {"type": ["null","string"]},
64
+ "maj:min": {"type": "string"},
65
+ "fsuse%": {"type": ["null","string"]},
66
+ "hotplug": {"type": "boolean"},
67
+ "zoned": {"type": "string"},
68
+ "fssize": {"type": ["null","string"]},
69
+ "vendor": {"type": ["null","string"]},
70
+ "fsroots": {"type": "array","items": {"type": ["null","string"]}},
71
+ "zone-nr": {"type": "integer"},
72
+ "rota": {"type": "boolean"},
73
+ "owner": {"type": "string"},
74
+ "kname": {"type": "string"},
75
+ "fsver": {"type": ["null","string"]},
76
+ "start": {"type": ["null","integer"]},
77
+ "parttypename": {"type": ["null","string"]},
78
+ "label": {"type": ["null","string"]},
79
+ "phy-sec": {"type": "integer"},
80
+ "serial": {"type": ["null","string"]},
81
+ "zone-sz": {"type": "integer"},
82
+ "min-io": {"type": "integer"},
83
+ "zone-app": {"type": "integer"},
84
+ "partflags": {"type": "null"}
85
+ }
86
+ }
87
+ }
88
+ })
89
+ lsblk_help_outputs = {
90
+ "ALIGNMENT" => "alignment offset",
91
+ "DISC-ALN" => "discard alignment offset",
92
+ "DAX" => "dax-capable device",
93
+ "DISC-GRAN" => "discard granularity",
94
+ "DISC-MAX" => "discard max bytes",
95
+ "DISC-ZERO" => "discard zeroes data",
96
+ "FSAVAIL" => "filesystem size available",
97
+ "FSROOTS" => "mounted filesystem roots",
98
+ "FSSIZE" => "filesystem size",
99
+ "FSTYPE" => "filesystem type",
100
+ "FSUSED" => "filesystem size used",
101
+ "FSUSE%" => "filesystem use percentage",
102
+ "FSVER" => "filesystem version",
103
+ "GROUP" => "group name",
104
+ "HCTL" => "Host:Channel:Target:Lun for SCSI",
105
+ "HOTPLUG" => "removable or hotplug device (usb, pcmcia, ...)",
106
+ "KNAME" => "internal kernel device name",
107
+ "LABEL" => "filesystem LABEL",
108
+ "LOG-SEC" => "logical sector size",
109
+ "MAJ:MIN" => "major:minor device number",
110
+ "MIN-IO" => "minimum I/O size",
111
+ "MODE" => "device node permissions",
112
+ "MODEL" => "device identifier",
113
+ "NAME" => "device name",
114
+ "OPT-IO" => "optimal I/O size",
115
+ "OWNER" => "user name",
116
+ "PARTFLAGS" => "partition flags",
117
+ "PARTLABEL" => "partition LABEL",
118
+ "PARTTYPE" => "partition type code or UUID",
119
+ "PARTTYPENAME" => "partition type name",
120
+ "PARTUUID" => "partition UUID",
121
+ "PATH" => "path to the device node",
122
+ "PHY-SEC" => "physical sector size",
123
+ "PKNAME" => "internal parent kernel device name",
124
+ "PTTYPE" => "partition table type",
125
+ "PTUUID" => "partition table identifier (usually UUID)",
126
+ "RA" => "read-ahead of the device",
127
+ "RAND" => "adds randomness",
128
+ "REV" => "device revision",
129
+ "RM" => "removable device",
130
+ "RO" => "read-only device",
131
+ "ROTA" => "rotational device",
132
+ "RQ-SIZE" => "request queue size",
133
+ "SCHED" => "I/O scheduler name",
134
+ "SERIAL" => "disk serial number",
135
+ "SIZE" => "size of the device",
136
+ "START" => "partition start offset",
137
+ "STATE" => "state of the device",
138
+ "SUBSYSTEMS" => "de-duplicated chain of subsystems",
139
+ "MOUNTPOINT" => "where the device is mounted",
140
+ "MOUNTPOINTS" => "all locations where device is mounted",
141
+ "TRAN" => "device transport type",
142
+ "TYPE" => "device type",
143
+ "UUID" => "filesystem UUID",
144
+ "VENDOR" => "device vendor",
145
+ "WSAME" => "write same max bytes",
146
+ "WWN" => "unique storage identifier",
147
+ "ZONED" => "zone model",
148
+ "ZONE-SZ" => "zone size",
149
+ "ZONE-WGRAN" => "zone write granularity",
150
+ "ZONE-APP" => "zone append max bytes",
151
+ "ZONE-NR" => "number of zones",
152
+ "ZONE-OMAX" => "maximum number of open zones",
153
+ "ZONE-AMAX" => "maximum number of active zones",
154
+ }
155
+ lsblk_help_outputs.each do |k, v|
156
+ bp = lsblk_schema_content['definitions']['blockdevice']['properties'][k.downcase] || raise(k)
157
+ bp['description'] = v
158
+ end
159
+
160
+ LsBlk = JSI.new_schema_module(lsblk_schema_content)
161
+ BlockDev = LsBlk.definitions['blockdevice']
162
+
163
+
164
+ # a result of invoking {JSIUtilLinux.lsblk}
165
+ module LsBlk
166
+ EMPTY_CONTENT = {"blockdevices" => [].freeze}.freeze
167
+
168
+ # @yield [BlockDev]
169
+ # @return [Enumerator, nil]
170
+ def each_blockdev(&block)
171
+ jsi_each_descendent_node.lazy.select { |n| n.is_a?(BlockDev) }.eager.each(&block)
172
+ end
173
+
174
+ # @yield [BlockDev]
175
+ # @return [Enumerator, nil]
176
+ def each_disk(&block)
177
+ each_blockdev.lazy.select { |d| d.type == 'disk' }.eager.each(&block)
178
+ end
179
+
180
+ # luks devices are type 'crypt'. veracrypt devices are type 'dm' (dev mapper).
181
+ CRYPT_TYPES = %w(crypt dm).freeze
182
+
183
+ # @yield [BlockDev]
184
+ # @return [Enumerator, nil]
185
+ def each_crypt(&block)
186
+ each_blockdev.lazy.select { |d| CRYPT_TYPES.include?(d.type) }.eager.each(&block)
187
+ end
188
+ end
189
+
190
+ # an item in `blockdevices` array of a {LsBlk} result
191
+ module BlockDev
192
+ # @return [BlockDev, nil]
193
+ def parent_blockdev
194
+ jsi_parent_nodes.detect { |n| n.is_a?(BlockDev) }
195
+ end
196
+
197
+ def maj_min
198
+ self['maj:min']
199
+ end
200
+
201
+ # @return [LoopDev, nil]
202
+ def loopdev
203
+ JSIUtilLinux.losetup_ls(path || raise("missing 'path' in #{inspect}")).loopdevices.first
204
+ end
205
+
206
+ # if this blockdevice is a loopdevice, and the backing file of that loopdevice is a blockdevice, returns that blockdevice
207
+ # @return [BlockDev, nil]
208
+ def loop_backing_blockdev
209
+ loopdev = self.loopdev
210
+ if loopdev
211
+ jsi_root_node.each_blockdev.detect { |bd| bd.path == loopdev["back-file"] }
212
+ end
213
+ end
214
+ end
215
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JSIUtilLinux
4
+ VERSION = "0.0.1"
5
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "jsi_util_linux/version"
4
+ require 'jsi'
5
+ require 'shellwords'
6
+
7
+ module JSIUtilLinux
8
+ autoload(:FindMnt, 'jsi_util_linux/findmnt')
9
+ autoload(:Filesystem, 'jsi_util_linux/findmnt')
10
+ autoload(:LoSetupList, 'jsi_util_linux/losetup')
11
+ autoload(:LoopDev, 'jsi_util_linux/losetup')
12
+ autoload(:LsBlk, 'jsi_util_linux/lsblk')
13
+ autoload(:BlockDev, 'jsi_util_linux/lsblk')
14
+
15
+ # Invokes [`findmnt`](https://linux.die.net/man/8/findmnt). Method arguments become CLI arguments via {args_to_argv}.
16
+ # @return [FindMnt]
17
+ def self.findmnt(*args, **kwargs)
18
+ system_jsi(FindMnt, 'findmnt', args, kwargs, empty: FindMnt::EMPTY_CONTENT)
19
+ end
20
+
21
+ # invokes {findmnt} and returns the resulting filesystems
22
+ # @return [Array<Filesystem>]
23
+ def self.filesystems(*args, **kwargs)
24
+ findmnt(*args, **kwargs).filesystems
25
+ end
26
+
27
+ # Invokes [`losetup --list`](https://linux.die.net/man/8/losetup). Method arguments become CLI arguments via {args_to_argv}.
28
+ #
29
+ # Other modes of `losetup` than `--list` are not supported.
30
+ #
31
+ # @return [LoSetupList]
32
+ def self.losetup_ls(*args, **kwargs)
33
+ system_jsi(LoSetupList, 'losetup', ['--list', *args], kwargs, empty: LoSetupList::EMPTY_CONTENT)
34
+ end
35
+
36
+ # invokes {losetup_ls} and returns the resulting loopdevices
37
+ # @return [Array<LoopDev>]
38
+ def self.loopdevices(*args, **kwargs)
39
+ losetup_ls(*args, **kwargs).loopdevices
40
+ end
41
+
42
+ # Invokes [`lsblk`](https://linux.die.net/man/8/lsblk). Method arguments become CLI arguments via {args_to_argv}.
43
+ # @return [LsBlk]
44
+ def self.lsblk(*args, **kwargs)
45
+ system_jsi(LsBlk, 'lsblk', args, kwargs, empty: LsBlk::EMPTY_CONTENT)
46
+ end
47
+
48
+ # invokes {lsblk} and returns the resulting blockdevices
49
+ # @return [Array<BlockDev>]
50
+ def self.blockdevices(*args, **kwargs)
51
+ lsblk(*args, **kwargs).blockdevices
52
+ end
53
+
54
+ # Transforms arguments, taking what is convenient to write in Ruby and returning what will be passed as `argv` to a CLI utility.
55
+ #
56
+ # String arguments go into argv as-is.
57
+ # Symbols are prefixed with '-' for single-character, '--' otherwise, and underscores become dashes.
58
+ # Arrays are recursed - `%w()` syntax is convenient to express arguments roughly like in a shell.
59
+ # Hashes are recursed - this would usually come from a keyword arguments hash.
60
+ #
61
+ # (o: 'name') => ['-o', 'name']
62
+ # (:a, :b, I: '7') => ['-a', '-b', '-I', '7']
63
+ # (:bytes) => ['--bytes']
64
+ # (include: '7') => ['--include', '7']
65
+ # (%w(--include 7)) => ['--include', '7']
66
+ #
67
+ # @return [Array<String>]
68
+ def self.args_to_argv(*args, **kwargs)
69
+ argv = []
70
+ args << kwargs
71
+ args.each do |a|
72
+ if a.is_a?(Symbol)
73
+ argv << (a.size == 1 ? "-#{a}" : "--#{a.to_s.tr('_', '-')}")
74
+ elsif a.is_a?(Array)
75
+ argv += args_to_argv(*a)
76
+ elsif a.is_a?(Hash)
77
+ a.each do |k, v|
78
+ argv += args_to_argv(k, v)
79
+ end
80
+ else
81
+ argv << a.to_str
82
+ end
83
+ end
84
+ argv
85
+ end
86
+
87
+ # @private
88
+ def self.system_jsi(schema, util, args, kwargs, empty: nil)
89
+ argv = args_to_argv('--json', *args, **kwargs)
90
+ # TODO probably better to use an open3 method
91
+ cmd = "#{util} #{argv.map { |a| Shellwords.escape(a) }.join(' ')}"
92
+ json = Kernel.send(:`, cmd)
93
+ raise("#{util} exited #{$?.exitstatus}\ncmd: #{cmd}\noutput: #{json}") unless $?.exitstatus == 0
94
+ content = json.empty? ? empty.nil? ? raise("empty output from command: #{cmd}") : empty : begin
95
+ JSON.parse(json)
96
+ rescue JSON::ParserError => e
97
+ raise("command did not output JSON.\ncommand: #{cmd}\noutput: #{json}\n#{e.class}: #{e.message}")
98
+ end
99
+ schema.new_jsi(content)
100
+ end
101
+ end
metadata ADDED
@@ -0,0 +1,64 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: jsi_util_linux
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Ethan
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: jsi
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '0.8'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '0.8'
26
+ description: util-linux utilities represented with JSI
27
+ email:
28
+ - ethan@unth.net
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - ".yardopts"
34
+ - LICENSE.txt
35
+ - README.md
36
+ - jsi_util_linux.gemspec
37
+ - lib/jsi_util_linux.rb
38
+ - lib/jsi_util_linux/findmnt.rb
39
+ - lib/jsi_util_linux/jul.rb
40
+ - lib/jsi_util_linux/losetup.rb
41
+ - lib/jsi_util_linux/lsblk.rb
42
+ - lib/jsi_util_linux/version.rb
43
+ homepage: https://github.com/notEthan/jsi_util_linux
44
+ licenses:
45
+ - MIT
46
+ metadata: {}
47
+ rdoc_options: []
48
+ require_paths:
49
+ - lib
50
+ required_ruby_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ required_rubygems_version: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '0'
60
+ requirements: []
61
+ rubygems_version: 3.6.9
62
+ specification_version: 4
63
+ summary: JSI + util-linux
64
+ test_files: []