-
Notifications
You must be signed in to change notification settings - Fork 0
/
winshebang.cpp
621 lines (482 loc) · 13.5 KB
/
winshebang.cpp
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
/* -*- mode:cc; tab-width:4; coding:Windows-31J; -*- */
/* vi:set ft=cpp ts=4 fenc=Windows-31J : */
/*
winshebang
2011/08/05 opa
*/
#include <string>
#include <algorithm>
#include <dir>
#include <windows.h>
#define PGM "winshebang"
#define PGM_DEBUG PGM ": "
#define PGM_INFO PGM ": "
#define PGM_WARN PGM " warning: "
#define PGM_ERR PGM " error: "
#define VERSTR "1.03"
#define CREDIT2011 "Copyright (c) 2011-2013 by opa"
typedef signed char schar;
typedef unsigned char uchar;
typedef signed int sint;
typedef unsigned int uint;
typedef signed long slong;
typedef unsigned long ulong;
using namespace std;
char
credit[] = PGM " version " VERSTR " " CREDIT2011;
bool
error = false;
sint
rcode = 0;
////////////////////////////////////////////////////////////////////////
template <class BidirectionalIterator, class T>
BidirectionalIterator rfind(BidirectionalIterator first, BidirectionalIterator last, const T &value)
{
while(first != last){
--last;
if(*last == value)
break;
}
return last;
}
template <class BidirectionalIterator, class Predicate>
BidirectionalIterator rfind_if(BidirectionalIterator first, BidirectionalIterator last, Predicate pred)
{
while(first != last){
--last;
if(pred(*last))
break;
}
return last;
}
inline bool isnotwspace(wchar_t c)
{
return !iswspace(c);
}
inline bool filename_separator(wchar_t c)
{
return c == L'\\' || c == L'/';
}
bool file_is_exist(const wchar_t *filename)
{
_wffblk ff;
sint r = _wfindfirst(filename, &ff, FA_NORMAL + FA_HIDDEN + FA_SYSTEM);
_wfindclose(&ff);
return r == 0;
}
bool file_is_exist(const wstring &filename)
{
return file_is_exist(filename.c_str());
}
////////////////////////////////////////////////////////////////////////
class String : public wstring {
typedef String Self;
typedef wstring Super;
public:
String();
String(const Super &s);
String(const wchar_t *s);
String(const_iterator b, const_iterator e);
String(const char *s);
~String();
string to_ansi() const;
Self to_upper() const;
Self trim() const;
bool isdoublequote() const;
Self doublequote() const;
Self doublequote_del() const;
Self &operator=(const Self &s);
Self &operator=(const wchar_t *s);
Self &operator=(const char *s);
Self &operator+=(const Self &s) { append(s); return *this; }
Self &operator+=(const wchar_t *s) { append(s); return *this; }
Self &operator+=(const char *s);
Self &assign_from_ansi(const char *s);
Self &assign_from_ansi(const uchar *s) { return assign_from_ansi((const char*)s); }
Self &assign_from_ansi(const string &s) { return assign_from_ansi(s.c_str()); }
Self &assign_from_utf8(const char *s);
Self &assign_from_utf8(const string &s) { return assign_from_utf8(s.c_str()); }
Self &assign_from_env(const Self &name);
Self &printf(Self format, ...);
// filename operator
bool have_path() const;
bool have_ext() const;
bool isbackslash() const;
Self backslash() const;
Self subext(const Self &ext) const;
Self drivename() const;
Self dirname() const;
Self basename() const;
};
String::String() {}
String::String(const String::Super &s) : Super(s) {}
String::String(const wchar_t *s) : Super(s) {}
String::String(const_iterator b, const_iterator e) : Super(b, e) {}
String::String(const char *s) { assign_from_ansi(s); }
String::~String() {}
String &String::operator=(const String &s) { assign(s); return *this; }
String &String::operator=(const wchar_t *s) { assign(s); return *this; }
String &String::operator=(const char *s) { assign_from_ansi(s); return *this; }
String &String::operator+=(const char *s) { append(String(s)); return *this; }
String operator+(const String &s1, const char *s2) { return s1 + String(s2); }
String operator+(const char *s1, const String &s2) { return String(s1) + s2; }
bool operator==(const String &s1, const char *s2) { return s1 == String(s2); }
bool operator==(const char *s1, const String &s2) { return String(s1) == s2; }
string String::to_ansi() const
{
sint
siz = WideCharToMultiByte(CP_ACP, 0, c_str(), size(), NULL, 0, NULL, NULL);
char
*buf = new char[siz+1];
fill(buf, buf + siz+1, 0);
WideCharToMultiByte(CP_ACP, 0, c_str(), size(), buf, siz, NULL, NULL);
string
r(buf);
delete [] buf;
return r;
}
String String::trim() const
{
const_iterator
b = begin(),
e = end();
b = ::find_if(b, e, isnotwspace);
e = ::rfind_if(b, e, isnotwspace);
if(e != end() && isnotwspace(*e))
++e;
return Self(b, e);
}
String &String::assign_from_ansi(const char *s)
{
sint
size = MultiByteToWideChar(CP_ACP, 0, s, -1, NULL, 0);
wchar_t
*buf = new wchar_t[size+1];
fill(buf, buf + size+1, 0);
MultiByteToWideChar(CP_ACP, 0, s, -1, buf, size);
assign(buf);
delete [] buf;
return *this;
}
String String::subext(const String &ext) const
{
const_iterator
e = ::rfind(begin(), end(), L'.');
if(e != end() && *e != L'.')
e = end();
return Self(begin(), e).append(ext);
}
String String::basename() const
{
const_iterator
b = begin(),
e = end();
b = ::rfind_if(b, e, ::filename_separator);
if(b != end() && ::filename_separator(*b))
++b;
e = ::rfind(b, e, L'.');
if(e != end() && *e != L'.')
e = end();
return Self(b, e);
}
String::const_iterator skipspace(String::const_iterator b, String::const_iterator e)
{
for( ; b != e ; ++b)
if(!iswspace(*b))
break;
return b;
}
////////////////////////////////////////////////////////////////////////
#if defined(__CONSOLE__)
void _putcxxx(const char *s, FILE *fp)
{
fputs(s, fp);
fputc('\n', fp);
}
#else // __CONSOLE__
String
consolebuf;
void _putcxxx(const char *s, FILE *)
{
if(consolebuf.size() > 0)
consolebuf += "\r\n";
consolebuf += s;
}
#endif // __CONSOLE__
inline void putcout(const char *s)
{
_putcxxx(s, stdout);
}
inline void putcerr(const char *s)
{
_putcxxx(s, stderr);
}
void _putcxxx(const String &s, FILE *fp)
{
_putcxxx(s.to_ansi().c_str(), fp);
}
inline void putcout(const String &s)
{
_putcxxx(s, stdout);
}
inline void putcerr(const String &s)
{
_putcxxx(s, stderr);
}
void _putcxxx(const char *s1, const String &s2, FILE *fp)
{
_putcxxx(String().assign_from_ansi(s1) + s2, fp);
}
inline void putcout(const char *s1, const String &s2)
{
_putcxxx(s1, s2, stdout);
}
inline void putcerr(const char *s1, const String &s2)
{
_putcxxx(s1, s2, stderr);
}
////////////////////////////////////////////////////////////////////////
class WindowsAPI {
public:
static bool CreateProcess(const String &cmd, DWORD CreationFlags, const String &wd, LPSTARTUPINFO si, LPPROCESS_INFORMATION pi);
static String GetClipboardText();
static String GetCommandLine() { return ::GetCommandLine(); }
static String GetComputerName();
static String GetModuleFileName(HMODULE Module = 0);
static String GetTempPath();
static String GetUserName();
static String SHGetSpecialFolder(sint nFolder);
};
bool WindowsAPI::CreateProcess(const String &cmd, DWORD CreationFlags, const String &wd, LPSTARTUPINFO si, LPPROCESS_INFORMATION pi)
{
bool
r;
wchar_t
*cmd_c_str;
cmd_c_str = new wchar_t[cmd.size()+1];
copy(cmd.begin(), cmd.end(), cmd_c_str);
cmd_c_str[cmd.size()] = 0;
r = ::CreateProcess(NULL, cmd_c_str, NULL, NULL, TRUE, CreationFlags, NULL, (wd.size()>0 ? wd.c_str() : NULL), si, pi);
delete [] cmd_c_str;
return r;
}
String WindowsAPI::GetModuleFileName(HMODULE Module)
{
wchar_t
buf[MAX_PATH+1];
DWORD
size = sizeof buf / sizeof(wchar_t);
size = ::GetModuleFileName(Module, buf, size);
if(size == 0)
return String();
return String(buf, buf + size);
}
////////////////////////////////////////////////////////////////////////
String
shebangline;
// コマンドライン文字列から、コマンド名を除いた残りの部分(コマンドに与えるパラメータの部分)を返す
String get_given_option(const String &cmdline)
{
bool
in_quote = false;
for(String::const_iterator s = cmdline.begin() ; s != cmdline.end() ; ++s){
wchar_t
c = *s;
if(!in_quote)
if(iswspace(c))
return String(s, cmdline.end());
if(c == L'"')
in_quote = in_quote ? false : true;
}
return String();
}
sint system(const String &cmdline, bool hide=false)
{
STARTUPINFO
si;
PROCESS_INFORMATION
pi;
DWORD
CreationFlags = 0,
ExitCode = 0;
memset(&si, 0, sizeof si);
memset(&pi, 0, sizeof pi);
si.cb = sizeof si;
GetStartupInfo(&si);
si.dwFlags |= STARTF_FORCEOFFFEEDBACK;
if(hide){
si.wShowWindow = SW_HIDE;
si.dwFlags |= STARTF_USESHOWWINDOW;
}
fflush(stdout);
fflush(stderr);
if(WindowsAPI::CreateProcess(cmdline, CreationFlags, "", &si, &pi) == 0){
error = true;
return -2;
}
CloseHandle(pi.hThread);
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, &ExitCode);
CloseHandle(pi.hProcess);
return ExitCode;
}
void execute_batchfile(const String &scriptname, const String &arg)
{
#if defined(__CONSOLE__)
rcode = system("\"" + scriptname + "\"" + arg);
#else
rcode = system("\"" + scriptname + "\"" + arg, true);
#endif
}
void execute_wscript(const String &scriptname, const String &arg)
{
#if defined(__CONSOLE__)
rcode = system("cscript //Nologo \"" + scriptname + "\"" + arg);
#else
rcode = system("wscript //Nologo \"" + scriptname + "\"" + arg);
#endif
}
void execute_java_jar(const String &jarname, const String &arg)
{
#if defined(__CONSOLE__)
rcode = system("java -jar \"" + jarname + "\"" + arg);
#else
rcode = system("javaw -jar \"" + jarname + "\"" + arg);
#endif
}
void execute_java_class(const String &classname, const String &arg)
{
#if defined(__CONSOLE__)
rcode = system("java \"" + classname + "\"" + arg);
#else
rcode = system("javaw \"" + classname + "\"" + arg);
#endif
}
bool file_is_shebang(const String &scriptname)
{
FILE
*fp;
uchar
buf[1000];
shebangline.clear();
if((fp = _wfopen(scriptname.c_str(), L"rb")) == NULL)
return false;
fill(buf, buf + sizeof buf, 0);
fread(buf, 1, sizeof buf-1, fp); // 最後の1バイトには決して読み込まない
fclose(fp);
// #!で始まっているか判定
if(!(buf[0] == '#' && buf[1] == '!'))
return false;
// 先頭行のみ見る
for(uchar *s = buf ; *s ; ++s){
if(*s == '\n' || *s == '\r'){
*s = 0;
break;
}
}
shebangline.assign_from_ansi(buf);
return true;
}
void execute_shebang(const String &scriptname, const String &arg)
{
String::const_iterator
b = shebangline.begin() + 2, // #! をスキップ
e = shebangline.end(),
shebang_cmd_b;
String
shebang_cmd,
shebang_arg;
b = skipspace(b, e); // #! のあとの空白をスキップ
// コマンド名の切り出し
for(shebang_cmd_b = b ; !(b == e || iswspace(*b)) ; ++b){
if(filename_separator(*b))
shebang_cmd_b = b + 1;
}
shebang_cmd = String(shebang_cmd_b, b);
// envだった場合は次のトークンが事実上のコマンド名
if(shebang_cmd == "env"){
shebang_cmd.clear();
b = skipspace(b, e); // 空白をスキップ
// 再度コマンド名の切り出し
for(shebang_cmd_b = b ; !(b == e || iswspace(*b)) ; ++b){
if(filename_separator(*b))
shebang_cmd_b = b + 1;
}
shebang_cmd = String(shebang_cmd_b, b);
}
b = skipspace(b, e); // 空白をスキップ
#if !defined(__CONSOLE__)
if(shebang_cmd == "perl")
shebang_cmd = "wperl";
if(shebang_cmd == "ruby")
shebang_cmd = "rubyw";
if(shebang_cmd == "python")
shebang_cmd = "pythonw";
if(shebang_cmd == "php")
shebang_cmd = "php-win";
#endif
// 残りは引数
shebang_arg = String(b, e).trim();
if(shebang_arg.size() > 0)
shebang_cmd += " " + shebang_arg;
rcode = system(shebang_cmd + " \"" + scriptname + "\"" + arg);
}
void winshebang_main()
{
String
exename = WindowsAPI::GetModuleFileName(),
arg = get_given_option(WindowsAPI::GetCommandLine()),
s;
if(s = exename.subext(""), file_is_shebang(s)){
execute_shebang(s, arg);
}else if(s = exename.subext(".bat"), file_is_exist(s)){
execute_batchfile(s, arg);
}else if(s = exename.subext(".cmd"), file_is_exist(s)){
execute_batchfile(s, arg);
}else if(s = exename.subext(".js"), file_is_exist(s)){
execute_wscript(s, arg);
}else if(s = exename.subext(".jse"), file_is_exist(s)){
execute_wscript(s, arg);
}else if(s = exename.subext(".vbs"), file_is_exist(s)){
execute_wscript(s, arg);
}else if(s = exename.subext(".vbe"), file_is_exist(s)){
execute_wscript(s, arg);
}else if(s = exename.subext(".jar"), file_is_exist(s)){
execute_java_jar(s, arg);
}else if(s = exename.subext(".class"), file_is_exist(s)){
execute_java_class(s, arg);
}else{
putcout(credit);
putcout("");
putcout("Error: shebang target file not found.");
error = true;
rcode = 1;
}
}
#if defined(__CONSOLE__)
extern "C"
sint wmain(sint, wchar_t *[])
{
winshebang_main();
return rcode;
}
#else // __CONSOLE__
// ダミーのメッセージを送受信することで、プログラムが動き出したことをOSに伝える
void dummy_message()
{
MSG msg;
PostMessage(NULL, WM_APP, 0, 0);
GetMessage(&msg, NULL, WM_APP, WM_APP);
}
extern "C"
sint WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR, int)
{
dummy_message();
consolebuf.clear();
winshebang_main();
if(consolebuf.size() > 0)
MessageBox(0, consolebuf.c_str(), WindowsAPI::GetModuleFileName().basename().c_str(),
MB_ICONINFORMATION + MB_OK);
return rcode;
}
#endif // __CONSOLE__