-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpk
649 lines (566 loc) · 18.2 KB
/
dpk
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#! /usr/bin/ruby -E:UTF-8
# -*- mode:Ruby; tab-width:4; coding:UTF-8; -*-
# vi:set ft=ruby ts=4 fenc=UTF-8 :
#----------------------------------------------------------------
# 断片くんドライバ
#
# 2011/04/18 opa
#----------------------------------------------------------------
require 'tempfile'
require 'open3'
ProgName = 'dpk'
Version = '0.03'
DANPENLIBPATHNAME = "DANPENLIB"
#=====dpk===== os_is_windows?
# Windows環境下かどうか判定する
module Kernel
if RUBY_PLATFORM =~ /mswin(?!ce)|mingw|cygwin|bccwin|emx/i
def os_is_windows?; true; end
else
def os_is_windows?; false; end
end
end
#=====dpk=====
#=====dpk===== nz
# nilなら別の値を返す
module Kernel
def nz(a, b=0)
a.nil? ? b : a
end
end
#=====dpk=====
#=====dpk===== determine_mimetype
# MIME Type 管理用クラス
class Mimetype
TABLE = [
{ mimetype:"application/pdf", mode:["pdf"], bin:[], ext:["pdf"] },
{ mimetype:"application/x-applescript", mode:["applescript"], bin:[], ext:["scpt"] },
{ mimetype:"application/x-javascript", mode:["javascript", "js"], bin:["cscript", "wscript"], ext:["js", "jse", "javascript", "jsee"] },
{ mimetype:"application/x-sh", mode:["sh", "bash"], bin:["sh", "bash"], ext:["sh"] },
{ mimetype:"application/xml-dtd", mode:["dtd"], bin:[], ext:["dtd"] },
{ mimetype:"text/css", mode:["css"], bin:[], ext:["css"] },
{ mimetype:"text/html", mode:["html"], bin:[], ext:["html", "htm", "shtml", "stm"] },
{ mimetype:"text/inf", mode:["inform"], bin:[], ext:["inf"] },
{ mimetype:"text/jsp", mode:["jsp"], bin:[], ext:["jsp"] },
{ mimetype:"text/plain", mode:["text", "default"], bin:[], ext:["text", "txt", "log"] },
{ mimetype:"text/plain/tab4", mode:["tab4"], bin:[], ext:[] },
{ mimetype:"text/plain/tab8", mode:["tab8"], bin:[], ext:[] },
{ mimetype:"text/sgml", mode:["sgml"], bin:[], ext:["sgml", "sgm"] },
{ mimetype:"text/x-asm", mode:["asm"], bin:[], ext:["asm", "s"] },
{ mimetype:"text/x-autohotkey", mode:["autohotkey"], bin:["autohotkey"], ext:["ahk"] },
{ mimetype:"text/x-automake", mode:["automake"], bin:["automake"], ext:["am"] },
{ mimetype:"text/x-awk", mode:["awk"], bin:["awk", "gawk"], ext:["awk"] },
{ mimetype:"text/x-c++src", mode:["cpp", "cc"], bin:[], ext:["cpp", "c++", "cc", "cxx", "hpp", "h++"] },
{ mimetype:"text/x-cobol", mode:["cobol"], bin:[], ext:["cbl", "cob"] },
{ mimetype:"text/x-csharp", mode:["cs"], bin:[], ext:["cs"] },
{ mimetype:"text/x-csrc", mode:["c"], bin:[], ext:["c", "h"] },
{ mimetype:"text/x-dosini", mode:["dosini"], bin:[], ext:["ini"] },
{ mimetype:"text/x-java", mode:["java"], bin:[], ext:["java", "jav"] },
{ mimetype:"text/x-lex", mode:["lex"], bin:["lex", "flex"], ext:["lex"] },
{ mimetype:"text/x-lisp", mode:["lisp"], bin:[], ext:["lisp", "lsp", "el"] },
{ mimetype:"text/x-makefile", mode:["make", "cmake"], bin:["make"], ext:["mak", "mk"] },
{ mimetype:"text/x-msdos-batch", mode:["dosbatch", "dosbat", "bat", "cmd"], bin:["cmd"], ext:["bat", "cmd"] },
{ mimetype:"text/x-nsis", mode:["nsis"], bin:[], ext:["nsi"] },
{ mimetype:"text/x-objcsrc", mode:["objc", "objcpp"], bin:[], ext:["m", "mm"] },
{ mimetype:"text/x-pascal", mode:["pascal"], bin:[], ext:["pas"] },
{ mimetype:"text/x-perl", mode:["perl", "cperl"], bin:["perl"], ext:["pl", "plw"] },
{ mimetype:"text/x-php", mode:["php"], bin:["php"], ext:["php"] },
{ mimetype:"text/x-python", mode:["python"], bin:["python"], ext:["py", "pyw"] },
{ mimetype:"text/x-rc", mode:["rc"], bin:["rc"], ext:["rc"] },
{ mimetype:"text/x-registory", mode:["registry"], bin:["regedit"], ext:["reg"] },
{ mimetype:"text/x-ruby", mode:["ruby"], bin:["ruby"], ext:["rb", "rbw"] },
{ mimetype:"text/x-sql", mode:["sql"], bin:[], ext:["sql"] },
{ mimetype:"text/x-tex", mode:["tex"], bin:[], ext:["tex"] },
{ mimetype:"text/x-vba", mode:["vb"], bin:["vb"], ext:["bas", "vb", "frm", "cls"] },
{ mimetype:"text/x-vbscript", mode:["vbs"], bin:["cscript", "wscript"], ext:["vbs", "vbe"] },
{ mimetype:"text/x-yacc", mode:["yacc"], bin:["yacc", "bison"], ext:["y"] },
{ mimetype:"text/x-yaml", mode:["yaml"], bin:[], ext:["yaml", "yml"] },
{ mimetype:"text/xml", mode:["xml", "nxml"], bin:[], ext:["xml"] },
]
# モード名からファイルタイプを返す
def self.mode2mimetype(mode)
return nil if mode.empty?
TABLE.each do |item|
item[:mode].each do |a_mode|
if mode.casecmp(a_mode) == 0
return item[:mimetype]
end
end
end
return nil
end
# ファイルの冒頭20行をバイト列で得る
def self.get_head(filename)
r = []
File.open(filename, "rt:ASCII-8BIT") do |file|
file.each_line do |aline|
r.push(aline.chomp.slice(0, 1000))
break if r.size >= 20
end
end
return r
end
# ファイル名が特定の拡張子(+追加部分)を持つかどうかを返す
def self.filename_ends(filename, ext)
["", ".bak", ".org", ".orig", ".svn-base", ",v", "~"].each do |adds|
if File.fnmatch("*.#{ext}#{adds}", filename, File::FNM_SYSCASE)
return true
end
end
return false
end
# Emacs風 -*- -*- 行
def self.guess_modeline_e(head)
mode = ""
head.each do |aline|
if aline =~ /-\*-(.*)-\*-/
opt = $1.strip
if opt.size > 0
if opt =~ /^[^\s;:]+$/
mode = opt
end
if opt =~ /mode:\s*([^\s;]+)/
mode = $1
end
#if opt =~ /tab-width:\s*([^\s;]+)/
# # 非実装
#end
break if !mode.empty?
end
end
end
return mode2mimetype(mode)
end
# vi風 vi: 行
def self.guess_modeline_v(head)
head.each do |aline|
if aline =~ /\s(?:ex|vim?):\s*(?:set\s+)?([^:]*)/
opt = $1.strip
if opt.size > 0
if opt =~ /(?:ft|filetype)=(\S+)/
return mode2mimetype($1)
end
end
end
end
return nil
end
# sh #!行
def self.guess_shebang(head)
head.each do |aline|
if aline =~ /^#!\s*(?:[\/\\](?:\w+[\/\\])*)?(\w+)(?:\s+(\w+))?/
command = $1
command = $2 if command == "env" # "env"だったら次の引数が事実上のコマンド名
TABLE.each do |item|
item[:bin].each do |a_bin|
if command == a_bin
return item[:mimetype]
end
end
end
end
end
return nil
end
# EmEditor #language行
def self.guess_shelang(head)
head.each do |aline|
break if aline !~ /^#/ #で始まらない行があったらそこで中断
if aline =~ /^#language\s*(?:=\s*)?"([^"]*)"/
return mode2mimetype($1.strip)
end
end
return nil
end
# ファイル名(拡張子等)からファイルタイプを判定する
def self.guess_extname(filename)
filename = File.basename(filename)
TABLE.each do |item|
item[:ext].each do |ext|
if filename_ends(filename, ext)
return item[:mimetype]
end
end
end
return nil
end
# テキストファイルの種類を推測する
# BUG:判定できるファイルの分野に偏りがある
def self.guess(filename)
head = get_head(filename)
r = guess_modeline_e(head) # Emacs風 -*- -*- 行
return r if !r.nil?
r = guess_modeline_v(head) # vi風 vi: 行
return r if !r.nil?
r = guess_shebang(head) # sh #!行
return r if !r.nil?
r = guess_shelang(head) # EmEditor #language行
return r if !r.nil?
r = guess_extname(filename) # ファイル名(拡張子等)
return r if !r.nil?
if File.size(filename) == 0 # 空ファイル
return "application/x-empty"
end
return "text/plain"
# return "application/octet-stream"
end
end
def determine_mimetype(filename)
return Mimetype.guess(filename)
end
#=====dpk=====
#=====dpk===== Win32::API.MessageBox
# Win32との橋渡し用
module Win32
if not defined?(WIDE)
WIDE = Encoding::UTF_16LE
WNUL = "\u0000".encode(WIDE)
def self.wstr(size); WNUL * size; end
def self.to_wstr!(s); s.encode!(WIDE).concat(WNUL); end
def self.to_wstr(s); s.encode(WIDE).concat(WNUL); end
def self.from_wstr(s); ((i = s.index(WNUL)).nil? ? s : s[0, i]).encode; end
end
end
# Ruby 2.0以降はFiddleを使う、Win32APIのようなもの
if RUBY_VERSION >= "2"
require 'fiddle'
module Win32
class API
DLL = {}
POINTER_TYPE = (Fiddle::SIZEOF_VOIDP == Fiddle::SIZEOF_LONG_LONG) ? 'q*' : 'l!*'
CALLTYPEMAP = {cdecl: Fiddle::Function::DEFAULT, stdcall: Fiddle::Function::STDCALL}
def typemap(t)
case t
when /[V0]/i, "", nil; Fiddle::TYPE_VOID
when /[PS]/i; Fiddle::TYPE_VOIDP
when /[NLI]/i; Fiddle::TYPE_LONG
end
end
private :typemap
def initialize(dllname, func, import, export = nil, calltype = :stdcall)
@proto = [import].join.each_char.map { |v| typemap(v) }
handle = DLL[dllname] ||= Fiddle.dlopen(dllname)
@func = Fiddle::Function.new(handle[func], @proto, typemap(export),
CALLTYPEMAP[calltype], name:func)
rescue Fiddle::DLError => e
raise LoadError, e.message, e.backtrace
end
def call(*args)
args.each_with_index do |x, i|
case @proto[i]
when Fiddle::TYPE_VOIDP
args[i], = [x == 0 ? nil : x].pack("p").unpack(POINTER_TYPE)
when Fiddle::TYPE_LONG
args[i], = [x].pack("I").unpack("i")
end
end
ret = @func.call(*args)
return ret || 0
end
end
end
else
require 'win32api'
module Win32
class API < Win32API
end
end
end
module Win32
class API
MB_ABORTRETRYIGNORE = 0x00000002
MB_CANCELTRYCONTINUE = 0x00000006
MB_HELP = 0x00004000
MB_OK = 0x00000000
MB_OKCANCEL = 0x00000001
MB_RETRYCANCEL = 0x00000005
MB_YESNO = 0x00000004
MB_YESNOCANCEL = 0x00000003
MB_ICONEXCLAMATION = 0x00000030
MB_ICONWARNING = 0x00000030
MB_ICONINFORMATION = 0x00000040
MB_ICONASTERISK = 0x00000040
MB_ICONQUESTION = 0x00000020
MB_ICONSTOP = 0x00000010
MB_ICONERROR = 0x00000010
MB_ICONHAND = 0x00000010
MB_DEFBUTTON1 = 0x00000000
MB_DEFBUTTON2 = 0x00000100
MB_DEFBUTTON3 = 0x00000200
MB_DEFBUTTON4 = 0x00000300
MB_APPLMODAL = 0x00000000
MB_SYSTEMMODAL = 0x00001000
MB_TASKMODAL = 0x00002000
MB_DEFAULT_DESKTOP_ONLY = 0x00020000
MB_RIGHT = 0x00080000
MB_RTLREADING = 0x00100000
MB_SETFOREGROUND = 0x00010000
MB_TOPMOST = 0x00040000
MB_SERVICE_NOTIFICATION = 0x00200000
IDABORT = 3
IDCANCEL = 2
IDCONTINUE = 11
IDIGNORE = 5
IDNO = 7
IDOK = 1
IDRETRY = 4
IDTRYAGAIN = 10
IDYES = 6
def self.MessageBox(hwnd, text, caption, type)
api = new("user32", "MessageBoxW", "pppi", "i")
text = Win32::to_wstr(text)
caption = Win32::to_wstr(caption) if not caption.nil?
return api.call(hwnd, text, caption, type)
end
end
end
#=====dpk=====
#=====dpk===== File.unify_separator
# ALT_SEPARATORがある環境では、ALT_SEPARATOR を SEPARATOR に統一する
if !File::ALT_SEPARATOR.nil?
def File.unify_separator(pathname)
return pathname.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
end
else
def File.unify_separator(pathname)
return pathname.dup
end
end
#=====dpk=====
#=====dpk===== LocaleVersion:system
# Encoding用便利メソッド等
class Encoding
ZWNBSP = "\ufeff" # ZERO WIDTH NO-BREAK SPACE (or BOM)
REPLACE = "\ufffd" # REPLACEMENT_CHARACTER
# あるオブジェクトのエンコードを変更する(Array,Hashの中も変更する)
def self.change(obj, encoding=default_internal)
case
when obj.respond_to?(:encode)
if obj.method(:encode).arity < 2
return obj.encode(encoding)
else
return obj.encode(encoding, invalid: :replace, undef: :replace)
end
when obj.is_a?(Array)
return obj.clone.map! do |v|
change(v, encoding)
end
when obj.is_a?(Hash)
tmp = obj.clone.clear
obj.each do |k, v|
tmp[change(k, encoding)] = change(v, encoding)
end
return tmp
end
return obj # case else
end
end
# ロケール対応変換用メソッド
class Encoding
# 内部エンコーディングに変換する
# UTF-8等
def self.to_in(obj)
return change(obj, default_internal)
end
# 外部エンコーディングに変換する
# 日本のWindowsでは、Windows-31J
def self.to_ex(obj)
return change(obj, default_external)
end
# ファイルシステムエンコーディングに変換する
# Windowsでは、UTF-16LEだがASCII comaptibleでないといけないためUTF-8
if os_is_windows?
def self.to_fs(obj)
return change(obj, Encoding::UTF_8)
end
else
def self.to_fs(obj)
return change(obj, 'filesystem')
end
end
# ロケールエンコーディングに変換する
# 日本のWindowsでは、Windows-31J
def self.to_lo(obj)
return change(obj, 'locale')
end
end
# ロケールエンコーディング版 system
# (org: IN:NG[U,W])
module Kernel
if !respond_to?(:system_verbatim)
alias :system_verbatim :system
module_function :system_verbatim
end
def system(*arg)
ival = Encoding.to_ex(arg)
return system_verbatim(*ival)
end
module_function :system
end
#=====dpk=====
#=====dpk===== LocaleVersion:File.exist?
# エンコーディングを考慮した File.exist?
class << File
if os_is_windows?
alias :exist_verbatim? :exist? if !respond_to?(:exist_verbatim?)
def exist?(file)
ival = Encoding.to_fs(file)
return exist_verbatim?(ival)
end
alias :exists? :exist?
end
end
#=====dpk=====
#=====dpk===== LocaleVersion:File.join
# エンコーディングを考慮した File.join
class << File
alias :join_verbatim :join if !respond_to?(:join_verbatim)
def join(*item)
ival = Encoding.to_fs(item)
oval = join_verbatim(*ival)
return Encoding.to_in(oval)
end
end
#=====dpk=====
#=====dpk===== LocaleVersion:File.expand_path
# エンコーディングを考慮した File.expand_path
class << File
alias :expand_path_verbatim :expand_path if !respond_to?(:expand_path_verbatim)
def expand_path(path, default_dir='.')
oval = expand_path_verbatim(path, default_dir)
oval = oval.force_encoding(oval.encoding) # for Issue #5533
return Encoding.to_in(oval)
end
end
#=====dpk=====
#=====dpk===== LocaleVersion:Open3.capture2e
# エンコーディングを考慮した Open3.capture2e
class << Open3
alias :capture2e_verbatim :capture2e if !respond_to?(:capture2e_verbatim)
def capture2e(*arg)
ival = Encoding.to_ex(arg)
oval = capture2e_verbatim(*ival)
return Encoding.to_in(oval)
end
end
#=====dpk=====
#=====dpk===== message_box
# メッセージボックス(ダイアログ+応答待ち)を表示する
def message_box(msg)
if os_is_windows?
Win32::API.MessageBox(0, msg, ProgName, Win32::API::MB_ICONINFORMATION)
else
if system("dialog", "--title", ProgName, "--msgbox", msg, "8", "60").nil?
system("echo", ProgName + ": " + msg)
system("read", "-p", "[HIT ENTER]")
end
end
end
#=====dpk=====
# オプションはオプション、ファイル名はファイル名に分けて返す
def sort_opts_files(argv)
opts = []
files = []
next_is_opt = false
no_more_opt = false
argv.each do |av|
if no_more_opt
files.push(av)
elsif next_is_opt
opts.push(av)
next_is_opt = false
elsif av == "--" # これ以降は全てファイル名として扱う
opts.push(av)
no_more_opt = true
elsif av =~ /^-[Lmeo]/ # パラメータが続くオプション
opts.push(av)
next_is_opt = true
elsif av =~ /^-/ # それ以外のオプション
opts.push(av)
else
files.push(av)
end
end
return [opts, files]
end
# ライブラリの位置を決定する
def determine_danpenlib(filename)
uld = ENV["USRLOCAL"]
uld = os_is_windows? ? "D:/usrlocal" : "~/Dropbox/usrlocal" if uld.nil?
uld = File.expand_path(uld)
uld = File.join(uld, "share", "danpenlib")
uld = File.unify_separator(uld)
mimetype = determine_mimetype(filename)
# $stderr.printf("%s: %s\n", filename, mimetype)
case mimetype
when "text/x-msdos-batch"
return File.join(uld, "BAT")
when "text/x-cobol"
return File.join(uld, "COBOL")
when "text/x-c++src", "text/x-csrc"
return File.join(uld, "CPP")
when "application/x-javascript"
return File.join(uld, "javascript")
when "text/x-perl"
return File.join(uld, "perl")
when "text/x-ruby"
return File.join(uld, "ruby")
when "application/x-sh"
return File.join(uld, "sh")
when "application/x-applescript"
return File.join(uld, "applescript")
end
return nil
end
def main(argv)
$PROGRAM_NAME = ProgName
# ENV["PROGRAM_NAME"] = ProgName
abort("This program must be use Ruby 1.9<= (current:#{RUBY_VERSION})") if RUBY_VERSION < "1.9"
# abort("This program must be run under Windows (current:#{RUBY_PLATFORM})") if !os_is_windows?
# オプションとファイル名をそれぞれ得る
opts, files = sort_opts_files(argv)
# ファイル名が与えられていない場合の断片くん本体の起動
return system("danpenkun", *opts) if files.empty?
files.each do |a_file|
# ファイルが存在しなければエラー
if !File.exist?(a_file)
$stderr.printf("#{ProgName}: Not found: #{a_file}\n")
next
end
# ライブラリの位置が環境変数で与えられていない場合、拡張子から推定する
lib = ENV[DANPENLIBPATHNAME]
lib = determine_danpenlib(a_file) if lib.nil?
# 推定できなかった場合はエラー
if lib.nil?
$stderr.printf("#{ProgName}: Cannot detarmine library path: #{a_file}\n")
next
end
# ライブラリが存在しなければエラー
if !File.exist?(lib)
$stderr.printf("#{ProgName}: Library not found: #{lib}\n")
next
end
tmp = Tempfile.new(ProgName)
tmp.close(false)
args = opts + ["--library-path=#{lib}", "--no-backup", "--output=#{tmp.path}", a_file]
output = Open3.capture2e("danpenkun", *args)[0]
if File.size(tmp.path) == 0
output = "#{a_file}: No output\n" + output
else
if os_is_windows?
system("WinMerge",
"-x", "--label-right=(Regenerated)", "/ur", "--readonly-right", "--no-backupfile",
File.realpath(a_file), tmp.path)
else
system("diff", "-u", "--label", a_file, "--label", "New", a_file, tmp.path)
end
end
output = output.chomp
if !output.empty?
message_box(output)
end
tmp.close(false)
end
return 0
end
exit main(ARGV)