summaryrefslogtreecommitdiffstats
path: root/iq.drush.inc
blob: 4c7acbd24a3459b3bc0f4f16a0fbbcb149c4e39c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
<?php

/**
 * @file
 *  The drush Issue Queue manager
 */



/**
 * Implementation of hook_drush_command().
 */
function iq_drush_command() {
  $items['iq-info'] = array(
    'description' => 'Show information about an issue from the queue on drupal.org.',
    'examples' => array(
      'drush iq-info 1234' => 'Get info on issue 1234.',
      'drush iq-info http://drupal.org/node/1234' => 'Get info on an issue identified by its URL.',
      'drush iq-info 1234-#3' => 'Get info on the patch on the third comment of issue 1234.',
      'drush iq-info 1234-5678' => 'Get info on the patch on comment id 5678 of issue 1234.',
    ),
    'arguments' => array(
      'number' => 'The issue number.',
    ),
    'required-arguments' => TRUE,
    'options' => array(
      'pipe' => 'Print the full issue info data structure.',
    ),
    'aliases' => array('iqi'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['iq-create-commit-comment'] = array(
    'description' => 'Create a commit comment for the specified issue number.',
    'examples' => array(
      'drush iq-create-commit-comment 1234' => 'Generate a commit comment using the title from issue 1234, and crediting every user who provided attachments.',
    ),
    'arguments' => array(
      'number' => 'The issue number.',
    ),
    'aliases' => array('iqccc', 'ccc'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['iq-apply-patch'] = array(
    'description' => 'Look up the most recent patch attached to the specified issue, and apply it to its project.',
    'examples' => array(
      'drush iq-apply-patch 1234' => 'Apply the newest patch attached to issue 1234.',
      'drush iq-apply-patch 1234-#5' => 'Apply the patch attached to the fifth comment of issue 1234.',
      'drush iq-apply-patch 1234-5678' => 'Apply the patch attached to comment id 5678 of issue 1234.',
      'drush iq-apply-patch 1234 --select' => 'Show all patches attached to issue 1234, and prompt for the one to apply.',
    ),
    'arguments' => array(
      'number' => 'The issue number.',
    ),
    'required-arguments' => TRUE,
    'options' => array(
      'no-prefix' => 'Patch was created with --no-prefix, and therefore should be applied with -Np0 instead of -Np1.  Optional; default is to try both.',
      'no-git' => 'Do not execute any git commands. Default is to create a new branch for the issue and commit the patch.',
      'no-commit' => 'Create a new branch, but do not commit the patch to the issue working branch after applying it. Optional. Patches created by git format-patch are always committed.',
      'keep-patch' => 'Keep the patchfile after applying it.  Default is to delete the patchfile.',
      'select' => 'Prompt for which patch to apply.  Optional; default is newest patch.',
    ),
    'aliases' => array('patch', 'am'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['iq-diff'] = array(
    'description' => 'Create a diff.  Uses `git format-patch`, so author information is included.',
    'examples' => array(
      'drush iq-diff' => 'Create a diff between the current branch and its upstream branch.',
      'drush iq-diff --commit' => 'Commit the changes to the current branch after creating the diff.',
    ),
    'arguments' => array(
      'number' => 'The issue number.',
    ),
    'options' => array(
      'no-prefix' => 'Create patch with no prefix.  Not recommended; patch will have to be applied with -Np0 instead of -Np1.',
      'no-git' => 'Do not execute any git commands; just run diff. Default is to use git format-patch.',
      'commit' => 'Commit change to current patch review branch. Optional; default is to leave changes unstaged.',
      'no-squash' => 'Show all commits in the branch, like a standard format-patch. Default is to squash into a single commit.',
      'rebase' => 'Rebase before creating patch.',
      'message' => 'Commit message.  Optional; default is to use `drush iq-create-commit-comment`.',
    ),
    'aliases' => array('diff', 'iqd'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['iq-reset'] = array(
    'description' => 'Stop working on a patch, and return to the original branch.',
    'examples' => array(
      'drush iq-reset' => 'Safely go back to the original branch. Work on the patch may resume later by returning to the working branch.',
      'drush iq-reset --hard' => 'Permanently delete all changes, and go back to the original branch.',
    ),
    'options' => array(
      'hard' => 'Also delete the working branch.',
    ),
    'aliases' => array('reset', 'iqr'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['iq-merge'] = array(
    'description' => 'Merge patch working branch into the original branch.',
    'examples' => array(
      'drush iq-merge' => 'Go back to the original branch, bringing all commits along.',
      'drush iq-merge --squash' => 'Merge multiple commits into a single commit when merging. May discard some author credit, as only the last commit is recorded.',
    ),
    'options' => array(
      'squash' => 'Merge all commits into one, keeping only the last.',
      'no-commit' => 'Skip committing unstaged changes.  Default is to commit everything.',
    ),
    'aliases' => array('merge', 'iqm'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'topics' => array('docs-iq-commands'),
  );
  $items['docs-iq-commands'] = array(
    'description' => 'Issue queue commands for applying and creating patches from drupal.org.',
    'hidden' => TRUE,
    'topic' => TRUE,
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'callback' => 'drush_print_file',
    'callback arguments' => array(dirname(__FILE__) . '/docs/iq-commands.html'),
  );

  return $items;
}

function drush_iq_diff($number = NULL) {
  $branch_merges_with = FALSE;
  $issue_info = array();
  $remote = FALSE;
  if (isset($number)) {
    $issue_info = drush_iq_get_info($number);
    if (!$issue_info) {
      return FALSE;
    }
    $branch = _drush_iq_get_branch($issue_info);
    $dir = _drush_iq_project_dir($issue_info);
    if (!$dir) {
      return drush_set_error('DRUSH_IQ_DIFF_NO_PROJECT', dt('Could not find the project directory for !n', array('!n' => $number)));
    }
  }
  else {
    $dir = _drush_iq_git_root_dir_from_cwd();
    $branch = _drush_iq_get_branch_at_dir($dir);
    $branch_merges_with = _drush_iq_get_branch_merges_with($dir);
    if ($branch_merges_with === FALSE) {
      return FALSE;
    }
    if (!empty($branch_merges_with)) {
      $remote = _drush_iq_get_best_remote($branch_merges_with);
      $branch_merges_with = _drush_iq_merge_branch_with_remote($remote, $branch_merges_with);
    }
  }
  if (!$branch_merges_with && ($branch != "(no branch)")) {
    $branch_merges_with = 'master';
  }

  // Not under git revision control is an error
  if (empty($branch)) {
    return drush_set_error('DRUSH_NO_VCS', dt("Error: drush can only produce diffs of projects under git version control"));
  }

  // If the user did not provide an issue number, but we can find
  // that a git branch has been made at the current working directory,
  // then we will expect that the branch tag is in the format of
  // "arbitrary-prequel-ISSUENUMBER".  If it is in this form, drush_iq_get_info
  // will be able to find the issue number.
  if (isset($branch) && ($branch != "master") && empty($issue_info)) {
    $issue_info_id = drush_iq_issue_number($branch);
    if (!empty($issue_info_id)) {
      $number = $issue_info_id['id'];
      $issue_info = drush_iq_download_info($issue_info_id);
    }
  }
  // Add on extra flags
  $extra = "";
  if (drush_get_option('no-prefix', FALSE)) {
    $extra .= ' --no-prefix';
  }

  $cwd = getcwd();
  $committed = FALSE;
  $squashed = FALSE;
  drush_op('chdir', $dir);
  $patch_description = "drush-iq";
  if (!empty($issue_info)) {
    $comment_number = array_key_exists('comment-number', $issue_info) ? $issue_info['comment-number'] : 1 + count($issue_info['comments']);
    $patch_description = _drush_iq_make_description($issue_info['title']) . '-' . $issue_info['id'] . '-' . $comment_number . '.patch';
  }
  drush_log(dt("# Create patch: !patch_description (branch: !b merge: !m)", array('!patch_description' => $patch_description, '!b' => $branch, '!m' => $branch_merges_with)), 'notice');

  // If we have modified the master branch (not recommended), just run git diff
  if (($branch == "master") || ($branch == "(no branch)") || ($branch == $branch_merges_with) || drush_get_option('no-git', FALSE)) {
    $result = drush_shell_exec_interactive("git diff $extra %s", $branch_merges_with);
  }
  // Changes are being made under a local branch.  Do the recommended procedure for creating the diff.
  else {
    $commit_comment = _drush_iq_create_commit_comment($issue_info, drush_get_option('committer', TRUE), drush_get_option('message', FALSE));
    $result = drush_shell_exec("git status -s");
    $status_output = drush_shell_exec_output();
    // If there are unstaged changes, commit them
    if (!empty($status_output)) {
      // TODO: can we easily ignore *.patch, etc., or easily add only modified files?
      $result = drush_shell_exec("git add .");
      $result = drush_shell_exec("git commit -m %s", $commit_comment);
      if (!$result) {
        return drush_set_error('DRUSH_IQ_DIFF_CANNOT_COMMIT', dt("Commit failed."));
      }
      $committed = TRUE;
    }
    // If the branch to merge with is remote, then fetch and rebase
    if (drush_get_option('rebase', FALSE)) {
      if ($remote) {
        drush_shell_exec("git fetch %s %s && git rebase %s", $remote, $branch, $branch_merges_with);
      }
      else {
        drush_log(dt('--rebase ignored because !branch has no upstream branch.', array('!branch' => $branch)), 'warning');
      }
    }

    // Check to see if there are multiple commits on this branch. If there
    // are, make a new temporary branch and squash-merge all commits there.
    if (!drush_get_option('no-squash', FALSE)) {
      $result = drush_shell_exec("git log --oneline %s..HEAD", $branch_merges_with);
      $commits_output = drush_shell_exec_output();
      if (count($commits_output) > 1) {
        drush_shell_exec('git branch -D drush-iq-temp 2>/dev/null');
        drush_shell_exec('git checkout %s', $branch_merges_with);
        drush_shell_exec('git checkout -b drush-iq-temp');
        drush_shell_exec('git merge --squash %s', $branch);
        drush_shell_exec("git commit -m %s", $commit_comment);
        $squashed = TRUE;
      }
    }

    $result = drush_shell_exec_interactive("git format-patch %s -k $extra --stdout", $branch_merges_with);
    if ($squashed) {
      drush_shell_exec('git checkout %s', $branch);
      drush_shell_exec('git branch -D drush-iq-temp  2>/dev/null');
    }
    if ($committed && !drush_get_option('commit', FALSE)) {
      // Get rid of our commit
      drush_shell_exec("git reset HEAD~1");
    }
  }
  drush_op('chdir', $cwd);
  return $issue_info;
}

/**
 * iq-info command callback
 */
function drush_iq_info($number = NULL) {
  if (isset($number)) {
    $issue_info = drush_iq_get_info($number);
  }
  else {
    $dir = _drush_iq_git_root_dir_from_cwd();
    $branch = _drush_iq_get_branch_at_dir($dir);
    $issue_info = drush_iq_get_info($branch);
  }
  if ($issue_info === FALSE) {
    return FALSE;
  }
  $issue_info = _drush_iq_select_patch($issue_info);

  if (drush_get_option('pipe')) {
    drush_print_pipe(var_export($issue_info, TRUE));
  }
  else {
    $label_map = _drush_iq_label_map();
    $rows = array();

    foreach($label_map as $label => $key) {
      if (array_key_exists($key, $issue_info)) {
        $rows[] = array($label, ':', $issue_info[$key]);
      }
    }

    drush_print_table($rows);
  }
  return $issue_info;
}

/**
 * iq-create-commit-comment command callback
 */
function drush_iq_create_commit_comment($number = NULL) {
  if (isset($number)) {
    $issue_info = drush_iq_get_info($number);
  }
  else {
    $dir = _drush_iq_git_root_dir_from_cwd();
    $branch = _drush_iq_get_branch_at_dir($dir);
    $issue_info = drush_iq_get_info($branch);
  }
  if ($issue_info === FALSE) {
    return FALSE;
  }

  $result = _drush_iq_create_commit_comment($issue_info, drush_get_option('committer', FALSE));
  drush_print($result);
  return $result;
}

/**
 * Abandon the current branch
 */
function drush_iq_reset($number = NULL) {
  $cwd = getcwd();
  if (isset($number)) {
    $issue_info = drush_iq_get_info($number);
    if (!$issue_info) {
      return FALSE;
    }
    $dir = _drush_iq_project_dir($issue_info);
    if (!$dir) {
      return drush_set_error('DRUSH_IQ_RESET_NO_PROJECT', dt('Could not find the project directory for !n', array('!n' => $number)));
    }
  }
  else {
    $dir = _drush_iq_git_root_dir_from_cwd();
  }
  $result = drush_shell_cd_and_exec($dir, "git status -s");
  $status_output = drush_shell_exec_output();
  $unstaged_changes = (!empty($status_output));
  $branch = _drush_iq_get_branch_at_dir($dir);
  $branch_merges_with = _drush_iq_get_branch_merges_with($dir);
  if ($branch_merges_with === FALSE) {
    return FALSE;
  }
  if (empty($branch_merges_with)) {
    $branch_merges_with = 'master';
  }
  $delete = drush_get_option('hard', FALSE);
  $issue_info['branch'] = $branch;
  $issue_info['mergeBranch'] = $branch_merges_with;

  $reset_message = dt("Would you like to reset to the branch !merges_with? ", array('!merges_with' => $branch_merges_with, '!branch' => $branch));

  if (($branch == '(no branch)') || ($branch_merges_with == $branch)) {
    $reset_message = "";
    if (!$unstaged_changes) {
      return drush_set_error('DRUSH_IQ_NO_UNSTAGED_CHANGES', dt("No unstaged changes, and not on a branch; Drush cannot reset. If you have commits that you would like to get rid of, try:\n  git reset HEAD~1\nReplace '1' with the number of commits you have made. Use 'git log' and 'git status' for information."));
    }
    if (!$delete) {
      return drush_set_error('DRUSH_WILL_NOT_DELETE', dt("Not on a branch; Drush will not delete your unstaged changes unless you use the --hard flag."));
    }
    $action_message = dt("Your unstaged changes will be permanently deleted.");
  }
  elseif ($unstaged_changes) {
    $action_message = $delete ? dt("Your working branch !branch will be deleted, along with all unstaged changes.", array('!merges_with' => $branch_merges_with, '!branch' => $branch)) : dt("Your work will be preserved; you can return to it by typing:\n    git checkout !branch\nYour unstaged changes will be re-applied on top of the branch !merges_with", array('!merges_with' => $branch_merges_with, '!branch' => $branch));
  }
  else {
    $action_message = $delete ? dt("Your working branch !branch will be deleted.", array('!merges_with' => $branch_merges_with, '!branch' => $branch)) : dt("Your work will be preserved; you can return to it by typing:\n    git checkout !branch", array('!merges_with' => $branch_merges_with, '!branch' => $branch));
  }
  drush_print($reset_message . $action_message);
  $confirm = drush_confirm(dt("Is it okay to continue?"));
  if (!$confirm) {
    return drush_user_abort();
  }

  if ($delete) {
    drush_shell_exec_interactive("git reset --hard HEAD");
  }
  if (($branch_merges_with != $branch) && ($branch != "(no branch)")) {
    drush_op('chdir', $dir);
    $result = drush_shell_exec_interactive("git checkout %s", $branch_merges_with);
    if ($delete && ($branch != '(no branch)')) {
      $result = drush_shell_exec_interactive("git branch -D %s", $branch);
    }
  }
  drush_op('chdir', $cwd);
  return $issue_info;
}

/**
 * Merge the current branch in with its upstream branch.
 */
function drush_iq_merge($number = NULL) {
  $issue_info = array();
  $cwd = getcwd();
  if (isset($number)) {
    $issue_info = drush_iq_get_info($number);
    if (!$issue_info) {
      return FALSE;
    }
    $dir = _drush_iq_project_dir($issue_info);
    if (!$dir) {
      return drush_set_error('DRUSH_IQ_MERGE_NO_PROJECT', dt('Could not find the project directory for !n', array('!n' => $number)));
    }
  }
  else {
    $dir = _drush_iq_git_root_dir_from_cwd();
  }
  $result = drush_shell_cd_and_exec($dir, "git status -s");
  $status_output = drush_shell_exec_output();
  $unstaged_changes = (!empty($status_output));
  $branch = _drush_iq_get_branch_at_dir($dir);
  if (empty($issue_info)) {
    $issue_info = drush_iq_get_info($branch);
  }
  $branch_merges_with = _drush_iq_get_branch_merges_with($dir);
  if ($branch_merges_with === FALSE) {
    return FALSE;
  }
  if (empty($branch_merges_with)) {
    $branch_merges_with = 'master';
  }
  $issue_info['branch'] = $branch;
  $issue_info['mergeBranch'] = $branch_merges_with;

  if (($branch == '(no branch)') || ($branch_merges_with == $branch)) {
    return drush_set_error('DRUSH_IQ_CANNOT_MERGE', dt("Not on a branch; cannot merge."));
  }
  elseif ($unstaged_changes) {
    if (!drush_get_option('no-commit', FALSE)) {
      $commit_comment = _drush_iq_create_commit_comment($issue_info, drush_get_option('committer', TRUE), drush_get_option('message', FALSE));
      // TODO: can we easily ignore *.patch, etc., or easily add only modified files?
      $result = drush_shell_exec("git add .");
      $result = drush_shell_exec("git commit -m %s", $commit_comment);
      if (!$result) {
        return drush_set_error('DRUSH_IQ_DIFF_CANNOT_COMMIT', dt("Commit failed."));
      }
    }
    else {
      return drush_set_error('DRUSH_IQ_CANNOT_MERGE', dt("Please commit your unstaged changes before merging, or run command again without the --no-commit option."));
    }
  }
  $confirm = drush_confirm(dt("Would you like to merge the branch !branch with its upstream branch !merges_with? ", array('!merges_with' => $branch_merges_with, '!branch' => $branch)));
  if (!$confirm) {
    return drush_user_abort();
  }
  $squash = drush_get_option('squash', FALSE) ? '--squash' : '';

  drush_op('chdir', $dir);
  $result = drush_shell_exec_interactive("git checkout %s", $branch_merges_with);
  $result = drush_shell_exec_interactive("git merge %s %s", $squash, $branch);
  $result = drush_shell_exec_interactive("git branch -D %s", $branch);
  drush_op('chdir', $cwd);
  return $issue_info;
}

/**
 * iq-apply-patch command callback
 *
 * Given an issue number, find the most recent patch file
 * attached to it
 */
function drush_iq_apply_patch($number) {
  $issue_info = drush_iq_get_info($number);
  $do_git_operations = !drush_get_option('no-git', FALSE);
  $result = FALSE;
  if (!$issue_info) {
    return FALSE;
  }
  $project_dir = _drush_iq_project_dir($issue_info);
  if (!$project_dir) {
    return drush_set_error('DRUSH_IQ_APPLY_PATCH_NO_PROJECT', dt('You are not working in a site, and the current directory is not named after the project.  Please cd to the project !project and try again.', array('!project' => $issue_info['projectName'])));
  }
  $issue_info = _drush_iq_select_patch($issue_info, drush_get_option('select', FALSE));
  if (!$issue_info) {
    return FALSE;
  }
  if (!array_key_exists('patchId', $issue_info)) {
    return drush_set_error('DRUSH_NO_PATCHES', dt("Could not find a suitable patch in !issue", array('!issue' => _drush_iq_create_commit_comment($issue_info))));
  }
  $patch_name = $issue_info['patchName'];
  $patch_id = $issue_info['patchId'];
  $patch = $issue_info['patchUrl'];
  drush_log(dt("Drush iq-apply-patch !id: downloading patchfile !patch for project !project", array('!patch' => $patch_name, '!id' => $patch_id, '!project' => $issue_info['projectName'])), 'ok');
  // n.b. the file returned by drush_download_file is either in the cache,
  // or is registered for deletion
  $filename = drush_download_file($patch);
  if (!file_exists($filename)) {
    return drush_set_error('DRUSH_PATCH_NOT_DOWNLOADED', dt("Patch could not be downloaded."));
  }
  $filename = realpath($filename);
  $handle = @fopen($filename, "r");
  if (!$handle) {
    return drush_set_error('DRUSH_PATCH_NOT_READABLE', dt("Patch could not be read."));
  }
  // Get the first 80 characters or so from the file; we really only
  // care whether it starts 'diff' or 'from'.
  $line = fgets($handle, 80);
  $from_format_patch = (strncasecmp('from ', $line, 5) == 0);
  $from_diff = (strncasecmp('diff ', $line, 5) == 0);
  if (!$from_format_patch && !$from_diff) {
    drush_log("Could not tell if patch was created by diff or git format-patch; will try both.");
    $from_format_patch = $from_diff = TRUE;
  }
  fclose($handle);

  $keep_patch = FALSE;
  if (drush_get_option('keep-patch', FALSE)) {
    $keep_patch = dirname($filename) . '/iq-' . basename($filename);
    copy($filename, $keep_patch);
  }

  $cwd = getcwd();
  drush_op('chdir', $project_dir);

  $try_patch_tool = TRUE;
  if ($do_git_operations) {
    $branch_merges_with = _drush_iq_get_branch_merges_with($project_dir);
    if (!$branch_merges_with) {
      $branch_merges_with = _drush_iq_get_branch_at_dir($project_dir);
      if (empty($branch_merges_with)) {
        $result = drush_shell_cd_and_exec($project_dir, "git init");
        $result = drush_shell_cd_and_exec($project_dir, "git add .");
        if (dirname($filename) == $project_dir) {
          $result = drush_shell_cd_and_exec($project_dir, "git rm --cached -- %s", basename($filename));
        }
        if ($keep_patch) {
          $result = drush_shell_cd_and_exec($project_dir, "git rm --cached -- %s", basename($keep_patch));
        }
        $result = drush_shell_cd_and_exec($project_dir, "git commit -m 'Git repository created by drush apply-patch command.'");
      }
    }
    else {
      $branch_merges_with = 'origin/' . $branch_merges_with;
    }
    if ($branch_merges_with != "(no branch)") {
      $issue_info['mergeBranch'] = $branch_merges_with;
      drush_log(dt("Starting at branch !branchlabel", array('!branchlabel' => $branch_merges_with)), 'notice');

      // Make a branch via 'git checkout -b [description]-[issue]'
      $description = $issue_info['title'];
      $comment_number = array_key_exists('patchIndex', $issue_info) ? $issue_info['patchIndex'] : ('#' . 1 + count($issue_info['comments']));
      $branchlabel = 'drush-iq-' . _drush_iq_make_description($description) . '-' . $issue_info['id'] . '-' . $comment_number;
      $issue_info['branch'] = $branchlabel;
      drush_log(dt("Switching to branch !branchlabel", array('!branchlabel' => $branchlabel)), 'ok');
      $result = drush_shell_exec_interactive("git checkout -b %s %s", $branchlabel, $branch_merges_with);
      if (!$result) {
        return drush_set_error('DRUSH_IQ_BRANCH_CREATE_ERROR', dt("Could not create branch !branch", array('!branch' => $branchlabel)));
      }
    }
  }

  if ($do_git_operations && $from_format_patch) {
    $result = drush_shell_exec_interactive('git apply -v --directory=%s %s', $project_dir, $filename);
    if ($result === FALSE) {
      drush_log(dt("git apply failed; falling back to 'patch' tool"), 'warning');
    }
    else {
      $try_patch_tool = FALSE;
    }
  }

  if ($try_patch_tool) {
    // Try -Np1 first, then -Np0, unless the user selected --no-prefix,
    // in which case we'll try -Np0 followed by -Np1 if that does not work.
    $strip_count = 1;
    if (drush_get_option('no-prefix', FALSE)) {
      $strip_count = 0;
    }

    $result = drush_shell_exec_interactive('patch -Np%d --dry-run --batch -d %s -i %s', $strip_count, $project_dir, $filename);
    if (!$result) {
      $strip_count = !$strip_count;
      $result = drush_shell_exec_interactive('patch -Np%d --dry-run --batch -d %s -i %s', $strip_count, $project_dir, $filename);
      if (!$result) {
        return drush_set_error('DRUSH_IQ_PATCH_DID_NOT_APPLY', dt("Could not apply the patch with either -Np0 or -Np1; perhaps the patch was rolled for a different version of the project."));
      }
    }
    $result = drush_shell_exec_interactive('patch -Np%d --batch -d %s -i %s', $strip_count, $project_dir, $filename);
  }
  if (!drush_get_option('no-commit', FALSE)) {
    $commit_comment = _drush_iq_create_commit_comment($issue_info, drush_get_option('committer', FALSE), drush_get_option('message', FALSE));
    // Add the modified files
    $result = drush_shell_exec("git add -A");
    if (dirname($filename) == $project_dir) {
      $result = drush_shell_exec("git rm --cached -- %s", basename($filename));
      if ($keep_patch) {
        $result = drush_shell_exec("git rm --cached -- %s", basename($keep_patch));
      }
    }
    if (array_key_exists('patchAuthorCredit', $issue_info)) {
      $result = drush_shell_exec("git commit --author=%s -m %s", $issue_info['patchAuthorCredit'], $commit_comment);
    }
    else {
      $result = drush_shell_exec("git commit -m %s", $commit_comment);
    }
  }
  drush_op('chdir', $cwd);
  return $issue_info;
}

function _drush_iq_select_patch($issue_info, $prompt = FALSE) {
  $patch_list = _drush_iq_get_patch_list($issue_info);
  $patches = _drush_iq_collate_patches($issue_info, $patch_list);

  if (!empty($patches)) {
    // If --select, then prompt the user
    if ($prompt) {
      $choices = array();

      foreach ($patch_list as $patch => $info) {
        $index = $info['index'] . $info['suffix'];
        $choices[$patch] = array("$index", ":", $patch);
      }
      $patch = drush_choice($choices, dt("Select a patch to apply:"));
      if ($patch === FALSE) {
        return drush_user_abort();
      }
    }
    // If the issue specification included a comment number, e.g. #1078108-1, then select the patch attached to the specified comment
    elseif (array_key_exists('comment-number', $issue_info)) {
      $index = $issue_info['comment-number'];
      if (!array_key_exists($index, $patches)) {
        return drush_set_error('DRUSH_IQ_NO_PATCH', dt("Error: comment #!index does not exist or does not have a patch.", array('!index' => $index)));
      }
      $patch = $patches[$index];
    }
    else {
      // TODO: See http://drupal.org/node/1078108#comment-5659936 and
      // http://drupal.org/node/1078108#comment-5663932 for additional
      // heuristics we might apply here.
      $patch = array_pop($patches);
    }

    $patch_name = basename($patch);
    $patch_id = $issue_info['id'];
    if (array_key_exists($patch, $patch_list)) {
      $issue_info['patchUrl'] = $patch;
      $issue_info['patchIndex'] = $patch_list[$patch]['index'] . $patch_list[$patch]['suffix'];
      $patch_id .= '-' . $issue_info['patchIndex'];
      $issue_info['patchAuthorId'] = $issue_info['comments'][$patch_list[$patch]['id']]['contributorId'];
      $issue_info['patchAuthorCredit'] = $issue_info['contributors'][$issue_info['patchAuthorId']]['authorCredit'];
    }
    $issue_info['patchName'] = $patch_name;
    $issue_info['patchId'] = $patch_id;
  }
  return $issue_info;
}

/**
 * This lookup table is used to map items from
 * the issue queue json to the human-readable
 * labels used in the output of iq-info.
 */
function _drush_iq_label_map() {
  return  array(
    'Title' => 'title',
    'ID' => 'id',
    'URL' => 'url',
    'Project' => 'projectTitle',
    'Project URL' => 'projectUrl',
    'Version' => 'version',
    'Component' => 'component',
    'Category' => 'category',
    'Priority' => 'priority',
    'Assigned' => 'assignedName',
    'Status' => 'status',
    'Patch URL' => 'patchUrl',
    'Patch Index' => 'patchIndex',
    'Patch ID' => 'patchId',
  );
}

/**
 * Create a commit comment
 *
 * @param $issue_info array describing an issue; @see drush_iq_get_info()
 *
 * @returns string "#id by contributor1, contributor2: issue title"
 */
function _drush_iq_create_commit_comment($issue_info, $committer = FALSE, $message = FALSE) {
  $contributors = array();

  // If this function is being called because a patch is being
  // created right now, then add the committer to the head of the
  // credits list.
  if ($committer !== FALSE) {
    // If 'TRUE' is passed for the committer, then look up
    // the current user name from git config --list
    if ($committer === TRUE) {
      drush_shell_exec("git config --list | grep '^user.name=' | sed -e 's|[^=]*=||'");
      $output = drush_shell_exec_output();
      $committer = array_pop($output);
    }

    if (!empty($committer)) {
      $contributors[$committer] = $committer;
    }
  }
  // Gather up commit credits, listing most recent contributors first.
  // Everyone who added an attachment gets credit.
  if (!empty($issue_info)) {
    foreach (array_reverse($issue_info['attachments']) as $comment_number => $attachment) {
      if (array_key_exists($attachment['contributorId'], $issue_info['contributors'])) {
        $contributor = $issue_info['contributors'][$attachment['contributorId']]['name'];
        if (!in_array($contributor, $contributors)) {
          $contributors[$contributor] = $contributor;
        }
      }
    }
  }
  $credits = "";
  $credits_prequel = "";
  if (!empty($contributors)) {
    $credits_prequel = " by";
    $credits = " " . implode(', ', $contributors);
  }

  $prequel = "";
  if ($issue_info) {
    $issue_number = $issue_info['id'];
    $issue_title = $issue_info['title'];
    if (!$message) {
      $message = $issue_title;
    }
    $prequel = "Issue #$issue_number$credits_prequel";
  }
  if (!$message) {
    $message = dt("Generated with Drush iq");
  }
  return "$prequel$credits: $message";
}

/**
 * Get information about an issue
 *
 * @param $number integer containing the issue number, or string beginning with a "#" and the issue number
 *
 * @returns array
 *  - title             Title of the issue
 *  - id                Issue number
 *  - url               URL to issue page on drupal.org
 *  - projectTitle      Title of the project issue belongs to (e.g. Drush)
 *  - projectName       Name of the project (e.g. drush) - http://drupal.org/project/{projectName}
 *  - projectId
 *  - projectUrl
 *  - version           Project version
 *  - versionId
 *  - authorName       Name of the user who submitted the issue
 *  - authorId
 *  - authorUrl
 *  - assignedName     Name of the user the issue is assigned to
 *  - assignedId
 *  - assignedUrl
 *  - component         Code, documentation, etc.
 *  - category          Bug, feature request, etc.
 *  - priority          minor, normal, major, critical
 *  - priorityId
 *  - status            active, needs work, etc.
 *  - statusId
 *  - created
 *  - changed
 *  - comments          A list (array with numeric keys) of URLs
 *  - attachments       A list (array with numeric keys) of attachments
 *      Array
 *        - contributorId uid of user submitting the patch
 *        - urls        A list of strings pointing to the attachments
 *  - contributors      An associative array keyed by uid of contributors
 *      Array
 *        - name        Name of contributor
 *        - uid         uid of contributor (same as key for this item)
 *        - profile     url to user profile on drupal.org
 */
function drush_iq_get_info($issue_spec) {
  $issue_info_id = drush_iq_issue_number($issue_spec);
  if (empty($issue_info_id)) {
    return drush_set_error('DRUSH_ISSUE_NOT_FOUND', dt("Could not find the issue !issue", array('!issue' => $issue_spec)));
  }
  $issue_info = drush_iq_download_info($issue_info_id);
  return $issue_info;
}

/**
 *  Given an issue specification,
 */
function drush_iq_issue_number($issue_spec) {
  $issue_info_id = array();
  $number = FALSE;
  $issue_site_domain = drush_get_option('issue-site', 'drupal.org');
  $comment_number = FALSE;
  // #1234
  if (substr($issue_spec, 0, 1) == '#') {
    $issue_info_id['id'] = substr($issue_spec, 1);
  }
  // http://drupal.org/node/1234
  elseif (preg_match("#^http://([^/]*)/node/([0-9]*)/*#", $issue_spec, $matches, PREG_OFFSET_CAPTURE)) {
    $issue_site_domain = $matches[1][0];
    $issue_info_id['id'] = $matches[2][0];
  }
  // 1234
  elseif (is_numeric($issue_spec)) {
    $issue_info_id['id'] = $issue_spec;
  }
  // description-of-issue-1234 or description-of-issue-1234-8 (description-issue or description-issue-comment)
  elseif (strpos($issue_spec, ' ') === FALSE) {
    if (preg_match('/-*([0-9]+)(-*(#*[0-9]*[a-z]*))$/', $issue_spec, $matches)) {
      $issue_info_id['id'] = $matches[1];
      if (!empty($matches[3])) {
        $issue_info_id['comment-number'] = $matches[3];
      }
    }
  }
  return $issue_info_id;
}

/**
 *  Given a node id, fetch and decode the issue info json from drupal.org.
 */
function drush_iq_download_info($issue_info_id) {
  $number = $issue_info_id['id'];
  $comment_number = array_key_exists('comment-number', $issue_info_id) ? $issue_info_id['comment-number'] : FALSE;
  $issue_site_domain = drush_get_option('issue-site', 'drupal.org');
  $url = "http://$issue_site_domain/node/$number";
  // Get the json data from d.o.
  $filename = drush_find_tmp() . '/project-issue-' . $number . '.json';
  $filename = _drush_download_file($url . "/project-issue/json", $filename, TRUE);
  if (!empty($filename)) {
    $data = file_get_contents($filename);
  }
  if (!empty($data)) {
    $issue_info = json_decode($data, TRUE);
    // Fixup: if d.o claims that attachment #0 has a contributor, change it to contributor-id
    if (array_key_exists(0, $issue_info['attachments']) && array_key_exists('contributor', $issue_info['attachments'][0]) && !array_key_exists('contributorId', $issue_info['attachments'][0])) {
      $issue_info['attachments'][0]['contributorId'] = $issue_info['attachments'][0]['contributor'];
    }
    // Copy the comment number (in 'subject') from the comment structure
    // to the attachments structure.
    foreach ($issue_info['comments'] as $commentId => $comment) {
      if (array_key_exists($commentId, $issue_info['attachments'])) {
        if (!array_key_exists('commentNumber', $issue_info['attachments'][$commentId])) {
          $issue_info['attachments'][$commentId]['commentNumber'] = $issue_info['comments'][$commentId]['subject'];
        }
      }
    }
    // Add in the author credit info
    foreach ($issue_info['contributors'] as $uid => $info) {
      if ($info['name'] != 'System Message') {
        $issue_info['contributors'][$uid]['authorCredit'] = sprintf("%s <%s@%s.no-reply.drupal.org>", $info['name'], $info['name'], $uid);
      }
    }
    if (!empty($issue_info)) {
      if ($comment_number) {
        $issue_info['comment-number'] = $comment_number;
      }
      return $issue_info;
    }
  }
  return drush_set_error('DRUSH_PM_ISSUE_FAILED', dt('Could not fetch issue data from !url', array('!url' => $url)));
}

function _drush_iq_get_patch_list($issue_info) {
  $patch_list = array();

  foreach ($issue_info['attachments'] as $comment_number => $attachment) {
    $comment_patches = array();
    $index = array_key_exists('commentNumber', $attachment) ? $attachment['commentNumber'] : '0';
    foreach ($attachment['urls'] as $url) {
      if (substr($url, -6) == ".patch" || substr($url, -5) == ".diff") {
        $comment_patches[] = $url;
      }
    }
    if (count($comment_patches) == 1) {
      $patch_list[$comment_patches[0]] = array('index' => $index, 'id' => $comment_number, 'suffix' => '');
    }
    else {
      $label = 'a';
      foreach ($comment_patches as $url) {
        $patch_list[$url] = array('index' => $index, 'id' => $comment_number, 'suffix' => $label);
        $label = chr(ord($label) + 1);
      }
    }
  }
  return $patch_list;
}

function _drush_iq_collate_patches($issue_info, $patch_list) {
  $patches = array();

  foreach ($patch_list as $url => $info) {
    $patches[$info['index'] . $info['suffix']] = $url;
    $patches[$info['id'] . $info['suffix']] = $url;
  }

  return $patches;
}

/**
 * Find the project directory associated with the project
 * the specified issue is associated with.
 */
function _drush_iq_project_dir(&$issue_info) {
  $project_name = $issue_info['projectName'];
  $result = FALSE;

  if (array_key_exists('project-dir', $issue_info)) {
    $result = $issue_info['project-dir'];
  }
  else {
    // If our cwd is at the root of the project, then prefer that project over
    // one in some other location.
    $dir = _drush_iq_git_root_dir_from_cwd();
    if (basename($dir) == $project_name) {
      $result = $dir;
    }
    // TODO: Find drush extensions such as drush_extras, drush_make, drubuntu, etc.
    elseif ($project_name == 'drush') {
      $result = DRUSH_BASE_PATH;
    }
    else {
      $phase = drush_bootstrap_max();
      drush_log("bootstrapped to phase $phase");
      if ($phase >= DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION) {
        $extension_info = drush_get_extensions();
        // TODO: offer to download the project if it is not found?
        if (array_key_exists($project_name, $extension_info)) {
          $result = drush_get_context('DRUSH_DRUPAL_ROOT', '') . '/' . dirname($extension_info[$project_name]->filename);
        }
      }
      if ($phase >= DRUSH_BOOTSTRAP_DRUPAL_ROOT) {
        $root = drush_get_context('DRUSH_DRUPAL_ROOT', FALSE);
        if ($root) {
          if ($project_name == 'drupal') {
            $result = $root;
          }
          else {
            foreach (array('modules', 'sites/all/modules', 'sites/default/modules') as $loc) {
              $path = $root . '/' . $loc . '/' . $project_name;
              if (is_dir($path)) {
                $result = $path;
              }
            }
          }
        }
      }
    }
    if ($result) {
      $issue_info['project-dir'] = $result;
    }
    else {
      drush_log(dt('Could not find the project directory under the bootstrapped site'));
    }
  }

  return $result;
}

function _drush_iq_get_branch(&$issue_info) {
  $branch = FALSE;
  if (array_key_exists('branch', $issue_info)) {
    $branch = $issue_info['branch'];
  }
  else {
    $project_dir = _drush_iq_project_dir($issue_info);
    if ($project_dir) {
      $branch = _drush_iq_get_branch_at_dir($project_dir);
    }
  }
  $issue_info['branch'] = $branch;
  return $branch;
}

function _drush_iq_get_branch_at_dir($dir) {
  $result = drush_shell_cd_and_exec($dir, "git branch");
  $branch_output = drush_shell_exec_output();

  // Return the last non-empty line
  $branch = FALSE;
  while (($branch === FALSE) && !empty($branch_output)) {
    $line = array_shift($branch_output);
    if (!empty($line) && ($line[0] == '*')) {
      $branch_components = explode(' ', $line, 2);
      $branch = $branch_components[1];
    }
  }
  return $branch;
}

function _drush_iq_get_merge_branch_with_remote($merges_with) {
  $remote = _drush_iq_get_best_remote($merges_with);
  return _drush_iq_merge_branch_with_remote($remote, $merges_with);
}

function _drush_iq_merge_branch_with_remote($remote, $merges_with) {
  if (empty($remote)) {
    return $merges_with;
  }
  else {
    return $remote . '/' . $merges_with;
  }
}

function _drush_iq_get_best_remote($merges_with) {
  $remotes = _drush_iq_get_remotes($merges_with);
  if (empty($remotes)) {
    return "";
  }
  elseif (count($remotes) == 1) {
    return $remotes[0];
  }
  elseif (in_array('origin', $remotes)) {
    return 'origin';
  }
  return $remotes[0];
}

function _drush_iq_get_remotes($merges_with) {
  // Check the output of `git branch -r`; we are looking
  // for output "remote/branchname"
  $result = drush_shell_exec("git branch -r");
  $git_branch_output = drush_shell_exec_output();

  $remotes = array();
  foreach($git_branch_output as $line) {
    $line = trim($line);
    if (preg_match("#([^/]+)/(.*)#", $line, $matches)) {
      if ($matches[2] == $merges_with) {
        $remotes[] = $matches[1];
      }
    }
  }
  return $remotes;
}

function _drush_iq_get_branch_merges_with($dir, $branch_label = FALSE) {
  $merges_with = "";
  $default_merges_with = FALSE;
  $alternate_remotes = array();

  if ($branch_label === FALSE) {
    $branch_label = _drush_iq_get_branch_at_dir($dir);
  }
  if ($branch_label == "(no branch)") {
    return $merges_with;
  }
  // We expect that the upstream remote has been configured via
  // `git branch --set-upstream drush-iq-x master`
  $result = drush_shell_cd_and_exec($dir, "git config branch.%s.merge", $branch_label);
  $branch_merge_output = drush_shell_exec_output();
  if (!empty($branch_merge_output)) {
    // Convert the branch name into its abbreviated form.
    $result = drush_shell_exec("git rev-parse --abbrev-ref %s", $branch_merge_output[0]);
    $rev_parse_output = drush_shell_exec_output();
    return $rev_parse_output[0];
  }

  // If the upstream remote has not been configured, then we will look
  // at the output of `git remote show origin` and see if we can find
  // a fallback branch to use.
  $result = drush_shell_cd_and_exec($dir, "git remote show origin -n");
  $show_orgin_output = drush_shell_exec_output();

  foreach ($show_orgin_output as $line) {
    $line = trim($line);
    // Find all of the other branches 'master merges with remote master', etc.
    if (preg_match("/([^ ]+).* with remote (.*)/", $line, $matches)) {
      if ($matches[1] == $matches[2]) {
        $alternate_remotes[] = $matches[2];
      }
    }
  }
  // If there is only one remote, that must be the one we merge with!
  if (count($alternate_remotes) == 1) {
    $merges_with = array_shift($alternate_remotes);
  }
  elseif (!empty($alternate_remotes)) {
    // We could figure out which of these branches was the correct
    // one to use by walking the commit log.  See:
    // http://drupal.org/node/1078108#comment-6335376
    $setupstream = "";
    foreach ($alternate_remotes as $alternate) {
      $setupstream .= "\n  " . dt("git branch --set-upstream !branch !merge", array('!branch' => $branch_label, '!merge' => $alternate));
    }
    return drush_set_error('DRUSH_IQ_CANNOT_FIND_MERGE_BRANCH', dt("Could not determine which branch of !alternatives was the correct merge branch.  Use one of the following commands to select the correct one: !setupstream", array('!alternatives' => implode(',', $alternate_remotes), '!setupstream' => $setupstream)));
  }
  return $merges_with;
}

function _drush_iq_make_description($title) {
  $description = preg_replace('/[^a-z._-]/', '', str_replace(' ', '-', strtolower($title)));

  // Clip the description off at the next dash after the 30th position
  if (strlen($description) > 30) {
    $find_dash = strpos($description, '-', 30);
    if ($find_dash !== FALSE) {
      $description = substr($description, 0, $find_dash);
    }
  }

  return $description;
}

/**
 * Determine the location of the git root directory from the
 * location of the user's current working directory.  If the
 * cwd is somewhere inside the git repo, pop up to the top
 * by using git rev-parse.
 */
function _drush_iq_git_root_dir_from_cwd() {
  $dir = drush_get_context('DRUSH_OLDCWD', drush_cwd());
  exec('git rev-parse --show-toplevel 2> /dev/null', $output);
  if (!empty($output)) {
    $dir = $output[0];
  }
  return $dir;
}