forked from dgrijalva/gitx
-
Notifications
You must be signed in to change notification settings - Fork 76
/
BMScript.m
1371 lines (1136 loc) · 52.6 KB
/
BMScript.m
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// BMScript.m
// BMScriptTest
//
// Created by Andre Berg on 11.09.09.
// Copyright 2009 Berg Media. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// @cond HIDDEN
#import "BMScript.h"
#if BMSCRIPT_ENABLE_DTRACE
#import "BMScriptProbes.h" /* dtrace probes auto-generated from .d file(s) */
#endif
#include <unistd.h> /* for usleep */
#include <pthread.h> /* for pthread_* */
#define BMSCRIPT_INSERTION_TOKEN @"%@" /* used by templates to mark locations where a replacement insertions should occur */
#define BM_NSSTRING_TRUNCATE_LENGTH 20 /* used by -truncate, defined in NSString (BMScriptUtilities) */
#ifndef BMSCRIPT_DEBUG_HISTORY
#define BMSCRIPT_DEBUG_HISTORY 0
#endif
#if (BMSCRIPT_THREAD_SAFE && BMSCRIPT_ENABLE_DTRACE)
#if BMSCRIPT_FAST_LOCK
#define BM_LOCK(name) \
BM_PROBE(ACQUIRE_LOCK_START, (char *) [BMStringFromBOOL(BMSCRIPT_FAST_LOCK) UTF8String]); \
static pthread_mutex_t mtx_##name = PTHREAD_MUTEX_INITIALIZER; \
if (pthread_mutex_lock(&mtx_##name)) {\
printf("*** Warning: Lock failed! Application behaviour may be undefined. Exiting...");\
exit(EXIT_FAILURE);\
}
#define BM_UNLOCK(name) \
if ((pthread_mutex_unlock(&mtx_##name) != 0)) {\
printf("*** Warning: Unlock failed! Application behaviour may be undefined. Exiting...");\
exit(EXIT_FAILURE);\
}\
BM_PROBE(ACQUIRE_LOCK_END, (char *) [BMStringFromBOOL(BMSCRIPT_FAST_LOCK) UTF8String]);
#else
#define BM_LOCK(name) \
BM_PROBE(ACQUIRE_LOCK_START, (char *) [BMStringFromBOOL(BMSCRIPT_FAST_LOCK) UTF8String]);\
static id const sync_##name##_ref = @""#name;\
@synchronized(sync_##name##_ref) {
#define BM_UNLOCK(name) }\
BM_PROBE(ACQUIRE_LOCK_END, (char *) [BMStringFromBOOL(BMSCRIPT_FAST_LOCK) UTF8String]);
#endif
#elif (BMSCRIPT_THREAD_SAFE && !BMSCRIPT_ENABLE_DTRACE)
#if BMSCRIPT_FAST_LOCK
#define BM_LOCK(name) \
static pthread_mutex_t mtx_##name = PTHREAD_MUTEX_INITIALIZER; \
if (pthread_mutex_lock(&mtx_##name)) {\
printf("*** Warning: Lock failed! Application behaviour may be undefined. Exiting...");\
exit(EXIT_FAILURE);\
}
#define BM_UNLOCK(name) \
if ((pthread_mutex_unlock(&mtx_##name) != 0)) {\
printf("*** Warning: Unlock failed! Application behaviour may be undefined. Exiting...");\
exit(EXIT_FAILURE);\
};
#else
#define BM_LOCK(name) \
static id const sync_##name##_ref = @""#name;\
@synchronized(sync_##name##_ref) {
#define BM_UNLOCK(name) };
#endif
#else
#define BM_LOCK(name)
#define BM_UNLOCK(name)
#endif
NSString * const BMScriptOptionsTaskLaunchPathKey = @"BMScriptOptionsTaskLaunchPathKey";
NSString * const BMScriptOptionsTaskArgumentsKey = @"BMScriptOptionsTaskArgumentsKey";
NSString * const BMScriptOptionsVersionKey = @"BMScriptOptionsVersionKey";
NSString * const BMScriptTaskDidEndNotification = @"BMScriptTaskDidEndNotification";
NSString * const BMScriptNotificationTaskResults = @"BMScriptNotificationTaskResults";
NSString * const BMScriptNotificationTaskTerminationStatus = @"BMScriptNotificationTaskTerminationStatus";
NSString * const BMScriptTemplateArgumentMissingException = @"BMScriptTemplateArgumentMissingException";
NSString * const BMScriptTemplateArgumentsMissingException = @"BMScriptTemplateArgumentsMissingException";
NSString * const BMScriptLanguageProtocolDoesNotConformException = @"BMScriptLanguageProtocolDoesNotConformException";
NSString * const BMScriptLanguageProtocolMethodMissingException = @"BMScriptLanguageProtocolMethodMissingException";
NSString * const BMScriptLanguageProtocolIllegalAccessException = @"BMScriptLanguageProtocolIllegalAccessException";
/* Empty braces means this is an "Extension" as opposed to a Category */
@interface BMScript ()
@property (BM_ATOMIC copy, readwrite) NSString * result;
@property (BM_ATOMIC assign) NSInteger returnValue;
@property (BM_ATOMIC assign) NSInteger bgTaskReturnValue;
@property (BM_ATOMIC copy) NSString * partialResult;
@property (BM_ATOMIC assign) BOOL isTemplate;
@property (BM_ATOMIC retain) NSTask * task;
@property (BM_ATOMIC retain) NSPipe * pipe;
@property (BM_ATOMIC retain) NSTask * bgTask;
@property (BM_ATOMIC retain) NSPipe * bgPipe;
- (void) stopTask;
- (BOOL) setupTask;
- (void) cleanupTask:(NSTask *)whichTask;
- (TerminationStatus) launchTaskAndStoreResult;
- (void) setupAndLaunchBackgroundTask;
- (void) taskTerminated:(NSNotification *)aNotification;
- (void) appendData:(NSData *)d;
- (void) dataReceived:(NSNotification *)aNotification;
- (const char *) gdbDataFormatter;
@end
@implementation BMScript
@dynamic delegate;
@synthesize script;
@synthesize options;
@synthesize partialResult;
@synthesize result;
@synthesize isTemplate;
@synthesize history;
@synthesize task;
@synthesize pipe;
@synthesize bgTask;
@synthesize bgPipe;
@synthesize returnValue;
@synthesize bgTaskReturnValue;
//===========================================================
// delegate
//===========================================================
- (id<BMScriptDelegateProtocol>)delegate {
return delegate;
}
- (void)setDelegate:(id<BMScriptDelegateProtocol>)newDelegate {
BM_LOCK(delegate)
if (delegate != newDelegate) {
delegate = newDelegate;
}
BM_UNLOCK(delegate)
}
// MARK: Description
- (NSString *) description {
return [NSString stringWithFormat:@"%@\n"
@" script: '%@'\n"
@" result: '%@'\n"
@"delegate: '%@'\n"
@" options: '%@'",
[super description],
[script quote],
[result quote],
(delegate == self? (id)@"self" : delegate),
[options descriptionInStringsFileFormat]];
}
- (NSString *) debugDescription {
return [NSString stringWithFormat:@"%@\n"
@" history (%d item%@): '%@'\n"
@" task: '%@'\n"
@" pipe: '%@'\n"
@" bgTask: '%@'\n"
@" bgPipe: '%@'\n",
[self description], [history count], ([history count] == 1 ? @"" : @"s"), history, task, pipe, bgTask, bgPipe ];
}
- (const char *) gdbDataFormatter {
NSString * launchPath = [options objectForKey:BMScriptOptionsTaskLaunchPathKey];
NSArray * args = [options objectForKey:BMScriptOptionsTaskArgumentsKey];
NSMutableString * accString = [NSMutableString string];
if (args) {
for (NSString * arg in args) {
[accString appendFormat:@" %@%@", arg, ([arg isEqualToString:@""] ? @"" : @", ")];
}
}
NSString * desc = [NSString stringWithFormat:@"options = %@%@script = %@, result = %@, isTemplate = %@",
(launchPath ? launchPath : @"nil, "),
(accString ? accString : @"nil, "),
(script ? [[script quote] truncate] : @"nil"),
(result ? [[result quote] truncate] : @"nil"),
BMStringFromBOOL(isTemplate)];
return [desc UTF8String];
}
// MARK: Deallocation
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (BM_EXPECTED([task isRunning], 0)) [task terminate];
if (BM_EXPECTED([bgTask isRunning], 0)) [bgTask terminate];
[script release], script = nil;
[history release], history = nil;
[options release], options = nil;
[result release], result = nil;
[partialResult release], partialResult = nil;
[task release], task = nil;
[pipe release], pipe = nil;
[bgTask release], bgTask = nil;
[bgPipe release], bgPipe = nil;
[super dealloc];
}
- (void) finalize {
if (BM_EXPECTED([task isRunning], 0)) [task terminate];
if (BM_EXPECTED([bgTask isRunning], 0)) [bgTask terminate];
[super finalize];
}
// MARK: Initializer Methods
- (id)init {
NSLog(@"BMScript Warning: Initializing instance %@ with default values! "
@"(options = \"/bin/echo\", \"\", script source = '<script source placeholder>')", [super description]);
return [self initWithScriptSource:nil options:nil];
}
/* designated initializer */
- (id) initWithScriptSource:(NSString *)scriptSource options:(NSDictionary *)scriptOptions {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(INIT_BEGIN,
(char *) (scriptSource ? [[scriptSource quote] UTF8String] : "(null)"),
(char *) (scriptOptions ? [[[scriptOptions descriptionInStringsFileFormat] quote] UTF8String] : "(null)"));
#endif
if ([self isDescendantOfClass:[BMScript class]] && ![self conformsToProtocol:@protocol(BMScriptLanguageProtocol)]) {
@throw [NSException exceptionWithName:BMScriptLanguageProtocolDoesNotConformException
reason:@"BMScript Error: "
@"Descendants of BMScript must conform to the BMScriptLanguageProtocol!"
userInfo:nil];
}
self = [super init];
if (BM_EXPECTED(self != nil, 1)) {
if (scriptOptions) {
options = [scriptOptions retain];
} else {
if ([self isDescendantOfClass:[BMScript class]] && ![self respondsToSelector:@selector(defaultOptionsForLanguage)]) {
@throw [NSException exceptionWithName:BMScriptLanguageProtocolMethodMissingException
reason:@"BMScript Error: Descendants of BMScript must implement "
@"-[<BMScriptLanguageProtocol> defaultOptionsForLanguage]."
userInfo:nil];
} else if ([self respondsToSelector:@selector(defaultOptionsForLanguage)]) {
options = [[self performSelector:@selector(defaultOptionsForLanguage)] retain];
} else {
NSLog(@"BMScript Warning: Initializing instance %@ with default options: BMSynthesizeOptions(@\"/bin/echo\", @\"\")", [super description]);
options = [BMSynthesizeOptions(@"/bin/echo", @"") retain];
}
}
if (scriptSource) {
if (scriptOptions || options) {
script = [scriptSource retain];
} else {
// if scriptOptions == nil, we run with default options, namely /bin/echo so it might be better
// to put quotes around the scriptSource
NSLog(@"BMScript Info: Wrapping script source with single quotes. This is a precautionary measure "
@"because we are using default script options (instance initialized with options:nil).");
script = [[scriptSource wrapSingleQuotes] retain];
}
} else {
if ([self respondsToSelector:@selector(defaultScriptSourceForLanguage)]) {
script = [[self performSelector:@selector(defaultScriptSourceForLanguage)] retain];
} else {
NSLog(@"BMScript Warning: Initializing instance %@ with default script: '<script source placeholder>'", [super description]);
script = @"'<script source placeholder>'";
}
}
history = [[NSMutableArray alloc] init];
partialResult = [[NSString alloc] init];
// tasks/pipes will be allocated, initialized (and destroyed) lazily
// on an as-needed basis because NSTasks are one-shot (not for re-use)
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(INIT_END, (char *) [[[self debugDescription] quote] UTF8String]);
#endif
return self;
}
- (id) initWithTemplateSource:(NSString *)templateSource options:(NSDictionary *)scriptOptions {
if (templateSource) {
BM_LOCK(isTemplate)
self.isTemplate = YES;
BM_UNLOCK(isTemplate)
templateSource = [templateSource stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
templateSource = [templateSource stringByReplacingOccurrencesOfString:@"%%{}" withString:@"%%{"BMSCRIPT_INSERTION_TOKEN"}"];
return [self initWithScriptSource:templateSource options:scriptOptions];
}
return nil;
}
- (id) initWithContentsOfFile:(NSString *)path options:(NSDictionary *)scriptOptions {
NSError * err = nil;
NSString * scriptSource = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
if (BM_EXPECTED(scriptSource && !err, 1)) {
BM_LOCK(isTemplate)
self.isTemplate = NO;
BM_UNLOCK(isTemplate)
return [self initWithScriptSource:scriptSource options:scriptOptions];
} else {
NSLog(@"BMScript Error: Reading script source from file at '%@' failed: %@", path, [err localizedFailureReason]);
}
return nil;
}
- (id) initWithContentsOfTemplateFile:(NSString *)path options:(NSDictionary *)scriptOptions {
NSError * err;
NSString * scriptSource = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
if (BM_EXPECTED(scriptSource != nil, 1)) {
return [self initWithTemplateSource:scriptSource options:scriptOptions];
} else {
NSLog(@"BMScript Error: Reading script source from file at '%@' failed: %@", path, [err localizedFailureReason]);
}
return nil;
}
// MARK: Factory Methods
+ (id) scriptWithSource:(NSString *)scriptSource options:(NSDictionary *)scriptOptions {
return [[[self alloc] initWithScriptSource:scriptSource options:scriptOptions] autorelease];
}
+ (id) scriptWithContentsOfFile:(NSString *)path options:(NSDictionary *)scriptOptions {
return [[[self alloc] initWithContentsOfFile:path options:scriptOptions] autorelease];
}
+ (id) scriptWithContentsOfTemplateFile:(NSString *)path options:(NSDictionary *)scriptOptions {
return [[[self alloc] initWithContentsOfTemplateFile:path options:scriptOptions] autorelease];
}
// MARK: Private Methods
- (BOOL) setupTask {
BOOL success = NO;
if (BM_EXPECTED([task isRunning], 0)) {
[task terminate];
} else {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SETUP_TASK_BEGIN);
#endif
task = [[NSTask alloc] init];
pipe = [[NSPipe alloc] init];
if (task && pipe) {
NSString * path = [options objectForKey:BMScriptOptionsTaskLaunchPathKey];
NSArray * args = [options objectForKey:BMScriptOptionsTaskArgumentsKey];
// If BMSynthesizeOptions is called with "nil" as second argument
// that effectively sets up BMScriptOptionsTaskArgumentsKey as
// [NSArray arrayWithObjects:nil] which in turn becomes a "__NSArray0"
if (!args || [args isEmptyStringArray] || [args isZeroArray]) {
//NSLog(@"BMScript Warning: Zero array set as task arguments.\n args = %@, args class = %@", args, NSStringFromClass([args class]));
args = [NSArray arrayWithObject:script];
} else {
args = [args arrayByAddingObject:script];
}
[task setLaunchPath:path];
[task setArguments:args];
[task setStandardOutput:pipe];
// Unfortunately we need the following define if we want to use SenTestingKit for unit testing. Since we are telling
// BMScript here to write to stdout and stderr SenTestingKit will actually output certain messages to stderr, messages
// which can include the PID of the current task used for the testing. This invalidates testing task ouput from
// two tasks even if their output is identical because their PID is not. To work around this, we can use a define which
// will be set to 1 in the build settings for our unit tests via OTHER_CFLAGS and -DBMSCRIPT_UNIT_TESTS=1.
if (!BMSCRIPT_UNIT_TEST) {
//NSLog(@"BMScript: Info: setting [task standardError:pipe]");
[task setStandardError:pipe];
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SETUP_TASK_END);
#endif
success = YES;
}
}
return success;
}
/* fires a one-off (blocking or synchroneous) task and stores the result */
- (TerminationStatus) launchTaskAndStoreResult {
TerminationStatus status = BMScriptNotExecuted;
NSData * data = nil;
BM_LOCK(task)
@try {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(NET_EXECUTION_BEGIN, (char *) [[BMStringFromTerminationStatus(status) wrapSingleQuotes] UTF8String]);
#endif
[task launch];
}
@catch (NSException * e) {
self.returnValue = status = BMScriptFailedWithException;
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(NET_EXECUTION_END, (char *) [[BMStringFromTerminationStatus(status) wrapSingleQuotes] UTF8String]);
#endif
goto endnow;
}
[task waitUntilExit];
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(NET_EXECUTION_END, (char *) [[BMStringFromTerminationStatus(status) wrapSingleQuotes] UTF8String]);
#endif
data = [[pipe fileHandleForReading] readDataToEndOfFile];
if (BM_EXPECTED([task isRunning], 0)) [task terminate];
BM_UNLOCK(task)
self.returnValue = status = [task terminationStatus];
NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString * aResult = string;
BM_LOCK(result)
BOOL shouldSetResult = YES;
if ([delegate respondsToSelector:@selector(shouldSetResult:)]) {
shouldSetResult = [delegate shouldSetResult:string];
}
if (shouldSetResult) {
if ([delegate respondsToSelector:@selector(willSetResult:)]) {
aResult = [delegate willSetResult:string];
}
self.result = aResult;
}
BM_UNLOCK(result)
[string release], string = nil;
goto endnow;
endnow:
[self cleanupTask:task];
return status;
}
/* fires a one-off (non-blocking or asynchroneous) task and reels in the results
one after another thru notifications */
- (void) setupAndLaunchBackgroundTask {
if (BM_EXPECTED([bgTask isRunning], 0)) {
[bgTask terminate];
} else {
if (!bgTask) {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SETUP_BG_TASK_BEGIN);
#endif
// Create a task and pipe
bgTask = [[NSTask alloc] init];
bgPipe = [[NSPipe alloc] init];
NSString * path = [options objectForKey:BMScriptOptionsTaskLaunchPathKey];
NSArray * args = [options objectForKey:BMScriptOptionsTaskArgumentsKey];
// If BMSynthesizeOptions is called with "nil" as second argument
// that effectively sets up BMScriptOptionsTaskArgumentsKey as
// [NSArray arrayWithObjects:nil] which in turn becomes an opaque
// object named "__NSArray0"
if (!args || [args isEmptyStringArray] || [args isZeroArray]) {
//NSLog(@"args = %@, args class = %@", args, NSStringFromClass([args class]));
args = [NSArray arrayWithObject:script];
} else {
args = [args arrayByAddingObject:script];
}
// set options for background task
[bgTask setLaunchPath:path];
[bgTask setArguments:args];
[bgTask setStandardOutput:bgPipe];
[bgTask setStandardError:bgPipe];
// register for notifications
// currently the execution model for background tasks is an incremental one:
// self.partialResult is accumulated over the time the task is running and
// posting NSFileHandleReadCompletionNotification notifications. This happens
// through #dataReceived: which calls #appendData: until the NSTaskDidTerminateNotification
// is posted. Then, the partialResult is simply mirrored over to lastResult.
// This gives the user the advantage for long running scripts to check partialResult
// periodically and see if the task needs to be aborted.
// [[NSNotificationCenter defaultCenter] addObserver:self
// selector:@selector(dataComplete:)
// name:NSFileHandleReadToEndOfFileCompletionNotification
// object:bgTask];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(dataReceived:)
name:NSFileHandleReadCompletionNotification
object:[bgPipe fileHandleForReading]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(taskTerminated:)
name:NSTaskDidTerminateNotification
object:bgTask];
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SETUP_BG_TASK_END);
#endif
@try {
[bgTask launch];
}
@catch (NSException * e) {
self.bgTaskReturnValue = BMScriptFailedWithException;
[self cleanupTask:bgTask];
}
// kick off pipe reading in background
[[bgPipe fileHandleForReading] readInBackgroundAndNotify];
//[[bgPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
}
}
}
- (void) dataReceived:(NSNotification *)aNotification {
NSData * data = [[aNotification userInfo] valueForKey:NSFileHandleNotificationDataItem];
if (BM_EXPECTED([data length] > 0, 1)) {
[self appendData:data];
} else {
[self stopTask];
}
// fire again in background after each notification
[[bgPipe fileHandleForReading] readInBackgroundAndNotify];
}
- (void) appendData:(NSData *)data {
NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(APPEND_DATA_BEGIN, (char *) [string UTF8String]);
#endif
if (BM_EXPECTED(string != nil, 1)) {
NSString * aPartial = string;
BOOL shouldAppendPartial = YES;
if ([delegate respondsToSelector:@selector(shouldAppendPartialResult:)]) {
shouldAppendPartial = [delegate shouldAppendPartialResult:aPartial];
}
if (shouldAppendPartial) {
if ([delegate respondsToSelector:@selector(willAppendPartialResult:)]) {
aPartial = [delegate willAppendPartialResult:string];
}
BM_LOCK(partialResult)
self.partialResult = [partialResult stringByAppendingString:aPartial];
BM_UNLOCK(partialResult)
}
} else {
NSLog(@"BMScript: Warning: Attempted %s but could not append to self.partialResult. Data maybe lost!", __PRETTY_FUNCTION__);
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(APPEND_DATA_END, (char *) [[partialResult quote] UTF8String]);
#endif
[string release], string = nil;
}
- (void) cleanupTask:(NSTask *)whichTask {
if (task && task == whichTask) {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(CLEANUP_TASK_BEGIN);
#endif
BM_LOCK(task)
[task release], task = nil;
BM_UNLOCK(task)
BM_LOCK(pipe)
if (pipe) {
[[pipe fileHandleForReading] closeFile];
[pipe release], pipe = nil;
}
BM_UNLOCK(pipe)
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(CLEANUP_TASK_END);
#endif
} else if (bgTask && bgTask == whichTask) {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(CLEANUP_BG_TASK_BEGIN);
#endif
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSFileHandleReadCompletionNotification
object:[bgPipe fileHandleForReading]];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSTaskDidTerminateNotification
object:bgTask];
BM_LOCK(bgTask)
[bgTask release], bgTask = nil;
BM_UNLOCK(bgTask)
BM_LOCK(bgPipe)
if (bgPipe) {
[[bgPipe fileHandleForReading] closeFile];
[bgPipe release], bgPipe = nil;
}
BM_UNLOCK(bgPipe)
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(CLEANUP_BG_TASK_END);
#endif
}
}
- (void) stopTask {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(STOP_BG_TASK_BEGIN);
#endif
// read out remaining data, as the pipes have a limited buffer size
// and may stall on subsequent calls if full
NSData * dataInPipe = [[bgPipe fileHandleForReading] readDataToEndOfFile];
if (BM_EXPECTED(dataInPipe && [dataInPipe length], 0)) {
[self appendData:dataInPipe];
}
if(BM_EXPECTED([bgTask isRunning], 0)) [bgTask terminate];
self.bgTaskReturnValue = [bgTask terminationStatus];
// task is finished, copy over the accumulated partialResults into lastResult
NSString * string = self.partialResult;
NSString * aResult = string;
BM_LOCK(result)
BOOL shouldSetResult = YES;
if ([delegate respondsToSelector:@selector(shouldSetResult:)]) {
shouldSetResult = [delegate shouldSetResult:aResult];
}
if (shouldSetResult) {
if ([delegate respondsToSelector:@selector(willSetResult:)]) {
aResult = [delegate willSetResult:string];
}
// we need to do the right thing here and not use the accessor methods
// when the thread safety flag is on, since we are already in a locked
// section.
#if (BMSCRIPT_THREAD_SAFE)
result = aResult;
#else
self.result = aResult;
#endif
}
BM_UNLOCK(result)
[self cleanupTask:bgTask];
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(BG_EXECUTE_END, (char *) [[result quote] UTF8String]);
#endif
NSArray * historyItem = [NSArray arrayWithObjects:script, result, nil];
BM_LOCK(history)
if ([delegate respondsToSelector:@selector(shouldAddItemToHistory:)]) {
if ([delegate shouldAddItemToHistory:historyItem]) {
[history addObject:historyItem];
}
} else {
[history addObject:historyItem];
}
BM_UNLOCK(history)
if (BMSCRIPT_DEBUG_HISTORY) {
NSLog(@"BMScript Debug: Script '%@' executed successfully.\n"
@"Added to history = %@", [[script quote] truncate], history);
}
NSDictionary * info = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:self.bgTaskReturnValue], BMScriptNotificationTaskTerminationStatus,
result, BMScriptNotificationTaskResults, nil];
BM_LOCK(self)
[[NSNotificationCenter defaultCenter] postNotificationName:BMScriptTaskDidEndNotification object:self userInfo:info];
BM_UNLOCK(self)
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(STOP_BG_TASK_END);
#endif
}
- (void) taskTerminated:(NSNotification *) aNotification {
#pragma unused(aNotification)
[self stopTask];
}
// MARK: Templates
- (BOOL) saturateTemplateWithArgument:(NSString *)tArg {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_ARGUMENT_BEGIN, (char *) [tArg UTF8String]);
#endif
if (self.isTemplate) {
BM_LOCK(script)
self.script = [NSString stringWithFormat:script, tArg];
self.isTemplate = NO;
BM_UNLOCK(script)
return YES;
}
return NO;
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_ARGUMENT_END, (char *) [[script quote] UTF8String]);
#endif
}
- (BOOL) saturateTemplateWithArguments:(NSString *)firstArg, ... {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_ARGUMENTS_BEGIN);
#endif
BOOL success = NO;
if (self.isTemplate) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// determine how many replacements we need to make
NSInteger numTokens = [script countOccurrencesOfString:BMSCRIPT_INSERTION_TOKEN];
if (numTokens == NSNotFound) {
goto endnow;
}
NSString * accumulator = self.script;
NSString * arg;
va_list arglist;
va_start(arglist, firstArg);
NSRange searchRange = NSMakeRange(0, [accumulator rangeOfString:BMSCRIPT_INSERTION_TOKEN].location + [BMSCRIPT_INSERTION_TOKEN length]);
accumulator = [accumulator stringByReplacingOccurrencesOfString:BMSCRIPT_INSERTION_TOKEN
withString:firstArg
options:NSLiteralSearch
range:searchRange];
while (--numTokens > 0) {
arg = va_arg(arglist, NSString *);
searchRange = NSMakeRange(0, [accumulator rangeOfString:BMSCRIPT_INSERTION_TOKEN].location + [BMSCRIPT_INSERTION_TOKEN length]);
accumulator = [accumulator stringByReplacingOccurrencesOfString:BMSCRIPT_INSERTION_TOKEN
withString:arg
options:NSLiteralSearch
range:searchRange];
if (numTokens <= 1) break;
}
va_end(arglist);
self.script = [accumulator stringByReplacingOccurrencesOfString:@"%%" withString:@"%"];
self.isTemplate = NO;
[pool drain];
success = YES;
goto endnow;
}
endnow:
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_ARGUMENTS_END, (char *) [[script quote] UTF8String]);
#endif
return success;
}
- (BOOL) saturateTemplateWithDictionary:(NSDictionary *)dictionary {
BOOL success = NO;
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_DICTIONARY_BEGIN, (char *) [[[dictionary descriptionInStringsFileFormat] quote] UTF8String]);
#endif
if (self.isTemplate) {
NSString * accumulator = self.script;
NSArray * keys = [dictionary allKeys];
NSArray * values = [dictionary allValues];
// FIXME: Don't replace escaped token sequences
NSInteger i = 0;
for (NSString * key in keys) {
accumulator = [accumulator stringByReplacingOccurrencesOfString:@"\\%" withString:@"%%%%"];
accumulator = [accumulator stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%%{"BMSCRIPT_INSERTION_TOKEN"}", key ]
withString:[values objectAtIndex:i]];
i++;
}
BM_LOCK(script)
self.script = [accumulator stringByReplacingOccurrencesOfString:@"%" withString:@""];
self.isTemplate = NO;
BM_UNLOCK(script)
success = YES;
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SATURATE_WITH_DICTIONARY_END, (char *) [[script quote] UTF8String]);
#endif
return success;
}
// MARK: Execution
- (TerminationStatus) execute {
if (self.isTemplate) {
@throw [NSException exceptionWithName:BMScriptTemplateArgumentMissingException
reason:@"BMScript Error: Please define all replacement values for the current template "
@"by calling one of the -[saturateTemplate...] methods prior to execution"
userInfo:nil];
}
TerminationStatus success = [self executeAndReturnResult:nil];
return success;
}
- (TerminationStatus) executeAndReturnResult:(NSString **)results {
if (self.isTemplate) {
@throw [NSException exceptionWithName:BMScriptTemplateArgumentMissingException
reason:@"BMScript Error: please define all replacement values for the current template "
@"by calling one of the -[saturateTemplate...] methods prior to execution"
userInfo:nil];
}
TerminationStatus success = [self executeAndReturnResult:results error:nil];
return success;
}
- (TerminationStatus) executeAndReturnResult:(NSString **)results error:(NSError **)error {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(EXECUTE_BEGIN,
(char *) [[[task launchPath] wrapSingleQuotes] UTF8String],
(char *) [[script quote] UTF8String],
(char *) [BMStringFromBOOL(isTemplate) UTF8String]);
#endif
BOOL success = NO;
TerminationStatus status = BMScriptNotExecuted;
if (self.isTemplate) {
if (error) {
NSDictionary * errorDict =
[NSDictionary dictionaryWithObject:@"BMScript Error: Please define all replacement values for the current template "
@"by calling one of the -saturateTemplate... methods prior to execution"
forKey:NSLocalizedFailureReasonErrorKey];
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:0 userInfo:errorDict];
} else {
@throw [NSException exceptionWithName:BMScriptTemplateArgumentMissingException
reason:@"BMScript Error: Please define all replacement values for the current template "
@"by calling one of the -saturateTemplate... methods prior to execution"
userInfo:nil];
}
} else {// isTemplate is NO
BM_LOCK(task)
success = [self setupTask];
BM_UNLOCK(task)
if (BM_EXPECTED(success, 1)) {
status = [self launchTaskAndStoreResult];
if (status == BMScriptFailedWithException) {
if (error) {
NSString * reason = [NSString stringWithFormat:@"BMScript Error: Executing the task raised an exception."];
NSString * suggestion = [NSString stringWithFormat:@"Check launch path (path to the executable) and task arguments. "
@"Most of the time an exception is raised by NSTask because either or both are inappropriate."];
NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
reason, NSLocalizedFailureReasonErrorKey,
suggestion, NSLocalizedRecoverySuggestionErrorKey, nil];
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:0 userInfo:errorDict];
}
} else if (status == BMScriptNotExecuted) {
if (error) {
NSString * reason = [NSString stringWithFormat:@"BMScript Error: Unable to execute task."];
NSString * suggestion = [NSString stringWithFormat:@"Check launch path (path to the executable) and task arguments. "
@"Most of the time an exception is raised because either or both are inappropriate."];
NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:
reason, NSLocalizedFailureReasonErrorKey,
suggestion, NSLocalizedRecoverySuggestionErrorKey, nil];
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:0 userInfo:errorDict];
}
} else {
if (results) {
*results = result;
}
BM_LOCK(history)
NSArray * historyItem = [NSArray arrayWithObjects:script, result, nil];
if ([delegate respondsToSelector:@selector(shouldAddItemToHistory:)]) {
if ([delegate shouldAddItemToHistory:historyItem]) {
[history addObject:historyItem];
}
} else {
[history addObject:historyItem];
}
BM_UNLOCK(history)
if (BMSCRIPT_DEBUG_HISTORY) {
NSLog(@"BMScript Debug: Script '%@' executed successfully.\n"
@"Added to history = %@", [[script quote] truncate], history);
}
}
} else {
if (error) {
NSDictionary * errorDict =
[NSDictionary dictionaryWithObject:@"BMScript Error: Task setup failed! (sorry, don't have more info than that...)"
forKey:NSLocalizedFailureReasonErrorKey];
*error = [NSError errorWithDomain:NSOSStatusErrorDomain code:0 userInfo:errorDict];
}
}
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(EXECUTE_END, (char *) [[result quote] UTF8String]);
#endif
return status;
}
- (void) executeInBackgroundAndNotify {
if (self.isTemplate) {
@throw [NSException exceptionWithName:BMScriptTemplateArgumentMissingException
reason:@"please define all replacement values for the current template "
@"by calling one of the -[saturateTemplate...] methods prior to execution"
userInfo:nil];
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(BG_EXECUTE_BEGIN,
(char *) [[[options objectForKey:BMScriptOptionsTaskLaunchPathKey] wrapSingleQuotes] UTF8String],
(char *) [[script quote] UTF8String],
(char *) [BMStringFromBOOL(isTemplate) UTF8String]);
#endif
[self setupAndLaunchBackgroundTask];
}
// MARK: History
- (NSString *) scriptSourceFromHistoryAtIndex:(NSInteger)index {
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SCRIPT_AT_INDEX_BEGIN, index, (int) [history count]);
#endif
NSString * aScript = nil;
NSInteger hc = [history count];
if (hc > 0 && (index >= 0 && index <= hc)) {
NSString * item = [[self.history objectAtIndex:index] objectAtIndex:0];
if ([delegate respondsToSelector:@selector(shouldReturnItemFromHistory:)]) {
if ([delegate shouldReturnItemFromHistory:item]) {
aScript = item;
}
} else {
aScript = item;
}
} else {
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:[NSString stringWithFormat:@"Index (%d) out of bounds (%d)", index, hc]
userInfo:nil];
}
#if (BMSCRIPT_ENABLE_DTRACE)
BM_PROBE(SCRIPT_AT_INDEX_END, (char *) [[aScript quote] UTF8String], (int) [history count]);
#endif
return aScript;
}