Module: Planter::Tag

Defined in:
lib/planter/tag.rb

Overview

File tagging module

Author:

Class Method Summary collapse

Class Method Details

.add(target, tags) ⇒ Boolean

Add tags to a directory.

Parameters:

  • target (String)

    The directory to tag.

  • tags (Array<String>)

    The tags to add.

Returns:

  • (Boolean)

    Success.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/planter/tag.rb', line 36

def add(target, tags)
  return false unless TTY::Which.exist?('xattr')

  tags = [tags] unless tags.is_a?(Array)
  existing_tags = get(target)
  tags.concat(existing_tags).uniq!

  set_tags(target, tags)

  res = $? == 0

  if res
    Planter.notify("[Added tags] to #{target}", :debug, above_spinner: true)
  else
    Planter.notify("Failed to add tags to #{target}", :error)
  end

  res
end

.copy(source, target) ⇒ Boolean

Copy tags from one file to another.

Parameters:

  • source (String)

    path to source file

  • target (String)

    path to target file

Returns:

  • (Boolean)

    success



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/planter/tag.rb', line 84

def copy(source, target)
  return false unless TTY::Which.exist?('xattr')

  tags = `xattr -px com.apple.metadata:_kMDItemUserTags "#{source}" 2>/dev/null`
  `xattr -wx com.apple.metadata:_kMDItemUserTags "#{tags}" "#{target}"`
  res = $? == 0

  if res
    Planter.notify("[Copied tags] from #{source} to #{target}", :debug, above_spinner: true)
  else
    Planter.notify("Failed to copy tags from #{source} to #{target}", :error)
  end

  res
end

.get(target) ⇒ Array

Get tags on target file.

Parameters:

  • target (String)

    target file path

Returns:

  • (Array)

    Array of tags



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/planter/tag.rb', line 63

def get(target)
  return false unless TTY::Which.exist?('xattr')

  res = `xattr -p com.apple.metadata:_kMDItemUserTags "#{target}" 2>/dev/null`.clean_encode
  return [] if res =~ /no such xattr/ || res.empty?

  tags = Plist.parse_xml(res)

  return false if tags.nil?

  tags
end

.set(target, tags) ⇒ Boolean

Set tags on target file.

Parameters:

  • target (String)

    path to target file

  • tags (Array)

    Array of tags to set

Returns:

  • (Boolean)

    success



20
21
22
23
24
25
26
27
# File 'lib/planter/tag.rb', line 20

def set(target, tags)
  return false unless TTY::Which.exist?('xattr')

  tags = [tags] unless tags.is_a?(Array)

  set_tags(target, tags)
  $? == 0
end