dtas.git  about / heads / tags
duct tape audio suite for *nix
blob 127b1a034c3fae5696469b1ba3b106e956df9a3e 2190 bytes (raw)
$ git show v0.16.1:bin/dtas-cueedit	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
 
#!/usr/bin/env ruby
# Copyright (C) 2013-2016 all contributors <dtas-all@nongnu.org>
# License: GPL-3.0+ <https://www.gnu.org/licenses/gpl-3.0.txt>
# frozen_string_literal: true
require 'tempfile'
require 'dtas/xs'
usage = "Usage: #$0 FILENAME"
editor = ENV["VISUAL"] || ENV["EDITOR"] || "vi"
ARGV.size > 0 or abort usage
include DTAS::XS

def err_msg(cmd, status)
  "E: #{xs(cmd)} failed: #{status.inspect}"
end

def x!(*cmd)
  system(*cmd) or abort err_msg(cmd, $?)
end

def tmpfile(file, suffix)
  tmp = Tempfile.new([File.basename(file), suffix])
  tmp.sync = true
  tmp.binmode
  tmp
end

ARGV.each do |file|
  file =~ /\.flac\z/i or warn "Unsupported suffix, assuming FLAC"
  tmp = tmpfile(file, '.cue')
  begin
    # export the temporary file for the user to edit
    if system(*%W(metaflac --export-cuesheet-to=#{tmp.path} #{file}))
      remove_existing = true
      backup = tmpfile(file, '.backup.cue')
    else
      remove_existing = false
      backup = nil
      tmp.puts 'FILE "dtas-cueedit.tmp.flac" FLAC'
      tmp.puts '  TRACK 01 AUDIO'
      tmp.puts '    INDEX 01 00:00:00'
    end

    # keep a backup, in case the user screws up the edit
    original = File.binread(tmp.path)
    backup.write(original) if backup

    # user edits the file
    x!("#{editor} #{xs(tmp.path)}")

    # avoid an expensive update if the user didn't change anything
    current = File.binread(tmp.path)
    if current == original
      $stderr.puts "tags for #{xs(file)} unchanged" if $DEBUG
      next
    end

    # we must remove existing tags before importing again
    if remove_existing
      x!(*%W(metaflac --remove --block-type=CUESHEET #{file}))
    end

    # try to import the new file but restore from the original backup if the
    # user wrote an improperly formatted cue sheet
    cmd = %W(metaflac --import-cuesheet-from=#{tmp.path} #{file})
    if ! system(*cmd) && backup
      warn err_msg(cmd, $?)
      warn "E: restoring original from backup"
      x!(*%W(metaflac --import-cuesheet-from=#{backup.path} #{file}))
      warn "E: backup cuesheet restored, #{xs(file)} unchanged"
      exit(false)
    end
  ensure
    tmp.close!
    backup.close! if backup
  end
end

git clone git://80x24.org/dtas.git
git clone https://80x24.org/dtas.git