This file is indexed.

/usr/lib/python2.7/dist-packages/gnatpython/fileutils.py is in python-gnatpython 54-3+b1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 ############################################################################
 #                                                                          #
 #                            FILEUTILS.PY                                  #
 #                                                                          #
 #           Copyright (C) 2008 - 2011 Ada Core Technologies, Inc.          #
 #                                                                          #
 # This program is free software: you can redistribute it and/or modify     #
 # it under the terms of the GNU General Public License as published by     #
 # the Free Software Foundation, either version 3 of the License, or        #
 # (at your option) any later version.                                      #
 #                                                                          #
 # This program is distributed in the hope that it will be useful,          #
 # but WITHOUT ANY WARRANTY; without even the implied warranty of           #
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
 # GNU General Public License for more details.                             #
 #                                                                          #
 # You should have received a copy of the GNU General Public License        #
 # along with this program.  If not, see <http://www.gnu.org/licenses/>     #
 #                                                                          #
 ############################################################################

"""This module provides various functions to handle files and directories

All this functionalities are already present in python but they are available
in different modules with different interfaces. Here the interface of each
function tries to be as close as possible to the Unix shell commands.
"""

from gnatpython.ex import Run
from gnatpython.env import Env
from gnatpython.logging_util import highlight
from gnatpython.logging_util import COLOR_GREEN, COLOR_RED, COLOR_CYAN

from difflib import SequenceMatcher, unified_diff

import logging
import os
import shutil
import glob
import re
import socket
import sys
import fnmatch

logger = logging.getLogger('gnatpython.fileutils')

# Check whether ln is supported on this platform
# If ln is not supported, use shutil.copy2 instead
HAS_LN = hasattr(os, "link")

# When diff find a difference between two lines, we'll try to highlight
# the differences if diff_within_line is True. This is currently disabled
# because the output is not always more readable (the diff is too fine
# grained, we should probably do it at the word level)
diff_within_line = False


class FileUtilsError (Exception):
    """Exception raised by functions defined in this module
    """

    def __init__(self, cmd, msg):
        Exception.__init__(self, cmd, msg)
        self.cmd = cmd
        self.msg = msg

    def __str__(self):
        return "%s: %s\n" % (self.cmd, self.msg)


def cd(path):
    """Change current directory

    PARAMETERS
      path: directory name

    RETURN VALUE
      None

    REMARKS
      In case of error then FileUtilsError is raised
    """

    try:
        os.chdir(path)
    except Exception, E:
        logger.error(E)
        raise FileUtilsError('cd', "can't chdir to %s\n" % path)


def cp(source, target, copy_attrs=True, recursive=False):
    """Copy files

    PARAMETERS
      source: a glob pattern
      target: target file or directory. If the source resolves as several
         files then target should be a directory
      copy_attrs: If True, also copy all the file attributes such as
         mode, timestamps, ownership, etc.
      recursive: If True, recursive copy. This also preserves attributes;
         if copy_attrs is False, a warning is emitted.

    RETURN VALUE
      None

    REMARKS
      If an error occurs then FileUtilsError is raised
    """
    switches = ''
    if copy_attrs:
        switches += ' -p'
    if recursive:
        switches += ' -r'
    logger.debug('cp %s %s->%s' % (switches, source, target))

    if recursive and not copy_attrs:
        logger.warning('recursive copy always preserves file attributes')

    # Compute file list and number of file to copy
    file_list = ls(source)
    file_number = len(file_list)

    if file_number == 0:
        # If there is no source files raise an error
        raise FileUtilsError('cp', "can't find files matching '%s'" % source)
    elif file_number > 1:
        # If we have more than one file to copy then check that target is a
        # directory
        if not os.path.isdir(target):
            raise FileUtilsError('cp', 'target should be a directory')

    for f in file_list:
        try:
            if recursive:
                shutil.copytree(f, target)
            elif copy_attrs:
                shutil.copy2(f, target)
            else:
                shutil.copy(f, target)
        except Exception, E:
            logger.error(E)
            raise FileUtilsError('cp', 'error occurred while copying %s' % f)


def unixpath(path):
    """Convert path to Unix/Cygwin format

    PARAMETERS
      path: path string to convert

    RETURN VALUE
      None

    REMARKS
      On Unix systems this function is identity. On Win32 systems it needs
      cygpath to do the conversion.
    """
    if sys.platform == 'win32':
        p = Run(['cygpath', '-u', path])
        if p.status != 0:
            raise FileUtilsError('unixpath',
                                 'cannot transform path %s' % path)
        return p.out.strip()
    else:
        return path


def ln(source, target):
    """Create a symbolic link

    PARAMETERS
      source: a filename
      target: the target filename

    RETURN VALUE
      None
    """
    try:
        if HAS_LN:
            os.link(source, target)
        else:
            shutil.copy2(source, target)
    except Exception, E:
        logger.error(E)
        raise FileUtilsError('ln', 'can not link %s to %s' % (source, target))


def df(path):
    """Disk space available on the filesystem containing the given path

    PARAMETERS
      path: a path string

    RETURN VALUE
      An integer representing the space left in Mo
    """
    if Env().host.os.name.lower() == 'windows':
        import ctypes
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes))
        value = free_bytes.value
    else:
        stats = os.statvfs(path)
        value = stats.f_bsize * stats.f_bavail
    # The final value is in Mo so it can safely be converted to an integer
    return int(value / (1024 * 1024))


def colored_unified_diff(a, b, fromfile='', tofile='',
                          fromfiledate='', tofiledate='', n=3, lineterm='\n',
                          onequal=None, onreplaceA=None, onreplaceB=None):
    """Same parameters as difflib.unified_diff

    ONEQUAL is a callback: it is passed a substring matching parts of the
    input that are the same in A and B. It returns the version to be
    displayed (by default, no change). It can be used if you want to limit
    the output.
    Likewise, ONREPLACEA and ONREPLACEB are called when a substring of A is
    replaced by a substring of B. They should return the actual strings that
    will be compared to find the diffs within a line.
    """
    if not Env().main_options or not Env().main_options.enable_color:
        for line in unified_diff(
            a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm):
            yield line
    else:
        # Code inspired from difflib.py
        minus = highlight('-', fg=COLOR_CYAN)
        plus = highlight('+', fg=COLOR_CYAN)

        if not onequal:
            onequal = lambda x: x
        if not onreplaceA:
            onreplaceA = lambda x: x
        if not onreplaceB:
            onreplaceB = lambda x: x

        started = False
        for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n):
            if not started:
                yield highlight('--- %s %s%s', fg=COLOR_CYAN) \
                        % (fromfile, fromfiledate, lineterm)
                yield highlight('+++ %s %s%s', fg=COLOR_CYAN) \
                        % (tofile, tofiledate, lineterm)
                started = True

            i1, i2, j1, j2 = (group[0][1], group[-1][2],
                              group[0][3], group[-1][4])
            yield highlight(
                "@@ -%d,%d +%d,%d @@%s" % (i1 + 1, i2 - i1,
                                           j1 + 1, j2 - j1, lineterm),
                fg=COLOR_CYAN)

            for tag, i1, i2, j1, j2 in group:
                if tag == 'equal':
                    for line in a[i1:i2]:
                        yield ' ' + onequal(line)
                    continue

                elif tag == 'replace':
                    line1 = onreplaceA(("\n" + minus).join(a[i1:i2]))
                    line2 = onreplaceB(("\n" + plus).join(b[j1:j2]))

                    if diff_within_line:
                        # Do a diff within the lines to highlight the difs

                        d = list(SequenceMatcher(
                            None, line1, line2).get_grouped_opcodes(
                                len(line1) + len(line2)))
                        result1 = ""
                        result2 = ""
                        for c in d:
                            for t, e1, e2, f1, f2 in c:
                                if t == 'equal':
                                    result1 += "".join(onequal(line1[e1:e2]))
                                    result2 += "".join(onequal(line2[f1:f2]))
                                elif t == 'replace':
                                    result1 += highlight(
                                       "".join(line1[e1:e2]), COLOR_RED)
                                    result2 += highlight(
                                       "".join(line2[f1:f2]), COLOR_GREEN)
                                elif t == 'delete':
                                    result1 += highlight(
                                       "".join(line1[e1:e2]), COLOR_RED)
                                elif t == 'insert':
                                    result2 += highlight(
                                       "".join(line2[f1:f2]), COLOR_GREEN)
                        yield minus + result1
                        yield plus + result2
                    else:
                        yield minus + highlight(line1, COLOR_RED)
                        yield plus + highlight(line2, COLOR_GREEN)

                elif tag == 'delete':
                    for line in a[i1:i2]:
                        if diff_within_line:
                            yield minus + line
                        else:
                            yield minus + highlight(line, COLOR_RED)
                elif tag == 'insert':
                    for line in b[j1:j2]:
                        if diff_within_line:
                            yield plus + line
                        else:
                            yield plus + highlight(line, COLOR_GREEN)


def diff(item1, item2, ignore=None, item1name="expected", item2name="output"):
    """Compute diff between two files or list of strings

    PARAMETERS
      item1    :  a filename or a list of strings
      item2    :  a filename or a list of strings
      ignore   :  all lines matching this pattern in both files are
                  ignored during comparison. If set to None, all lines are
                  considered.
      item1name:  name to display for item1 in the diff
      item2name:  name to display for item2 in the diff
      color    :  whether colored diff should be displayed (even if True, this
                  will be disabled unless the user specified the --enable-color
                  switch).

    RETURN VALUE
      A diff string. If the string is equal to '' it means that there is no
      difference

    REMARKS
      White character at beginning and end of lines are ignored. On error,
      FileUtilsError is raised
    """

    tmp = [[], []]

    # Read first item
    if isinstance(item1, list):
        tmp[0] = item1
    else:
        try:
            file1_fd = open(item1, 'r')
            tmp[0] = file1_fd.readlines()
            file1_fd.close()
        except IOError:
            tmp[0] = []

    # Do same thing for the second one
    if isinstance(item2, list):
        tmp[1] = item2
    else:
        try:
            file2_fd = open(item2, 'r')
            tmp[1] = file2_fd.readlines()
            file2_fd.close()
        except IOError:
            tmp[1] = []

    def is_line_junk(line):
        """Skip non useful lines"""
        return len(line.strip()) == 0 or \
                 (ignore is not None and re.search(ignore, line) is not None)

    # Filter empty lines in both items and lines that match ignore pattern
    for k in [0, 1]:
        tmp[k] = ["%s\n" % line.strip() \
                  for line in tmp[k] if not is_line_junk(line)]

    diff_content = colored_unified_diff(
       tmp[0], tmp[1], n=1, fromfile=item1name, tofile=item2name)

    return ''.join(diff_content)


def ls(path):
    """List files

    PARAMETERS
      path: glob pattern or glob pattern list

    RETURN VALUE
      a list of filenames

    REMARKS
      This function do not raise an error if no file matching the glob pattern
      is encountered. The only consequence is that an empty list is returned.
    """

    if not isinstance(path, list):
        path = [path]

    result = []

    logger.debug('ls %s' % path)

    for p in path:
        result += glob.glob(p)

    result.sort()
    return result


def mkdir(path, mode=0755):
    """Create a directory

    PARAMETERS
      path: path to create. If intermediate directories do not exist the
            procedure create them
      mode: default is 0755

    RETURN VALUE
      None

    REMARKS
      This function behaves quite like mkdir -p command shell. So if the
      directory already exist no error is raised. If the directory cannot
      be created then FileUtilsError is raised.
    """

    if os.path.isdir(path):
        return
    else:
        logger.debug('mkdir %s %s' % (path, mode))
        try:
            os.makedirs(path, mode)
        except Exception, E:
            logger.error(E)
            raise FileUtilsError('mkdir', "can't create %s" % path)


def mv(source, target):
    """Move files

    PARAMETERS
      source: a glob pattern
      target: target file or directory. If the source resolves as several
              files then target should be a directory

    RETURN VALUE
      None

    REMARKS
      If an error occurs then FileUtilsError is raised
    """
    logger.debug('mv %s->%s' % (source, target))

    try:
        # Compute file list and number of file to copy
        file_list = ls(source)
        file_number = len(file_list)
        assert file_number != 0, "can't find files matching '%s'" % source

        if len(file_list) == 1:
            f = file_list[0]
            if os.path.isdir(f) and os.path.isdir(target):
                shutil.move(f, os.path.join(target, os.path.basename(f)))
            else:
                shutil.move(f, target)
        else:
            # If we have more than one file to move then check that target is a
            # directory
            assert os.path.isdir(target), 'target should be a directory'

            for f in file_list:
                shutil.move(f, os.path.join(target, os.path.basename(f)))
    except Exception, E:
        logger.error(E)
        raise FileUtilsError('mv', E)


def rm(path, recursive=False):
    """Remove files

    PARAMETERS
      path:      a glob pattern
      recursive: if True do a recursive deletion. Default is False

    RETURN VALUE
      None

    REMARKS
      If an error occurs then FileUtilsError is raised. The function will not
      raise an Error is there are no file to delete.
    """
    logger.debug('rm %s' % (path))

    file_list = ls(path)

    def onerror(func, path, exc_info):
        """When shutil.rmtree fail, try again to delete the file"""
        if func == os.remove or func == os.rmdir:
            # Cannot remove path, call chmod and redo an attempt
            os.chmod(path, 0777)
            func(path)

    for f in file_list:
        try:
            # When calling rmtree or remove, ensure that the string that is
            # passed to this function is unicode on Windows. Otherwise,
            # the non-Unicode API will be used and so we won't be
            # able to remove these files. On Unix don't do that as
            # we got some strange unicode "ascii codec" errors
            # (need some further investigation at some point)
            if Env().host.os.name == 'windows':
                f = unicode(f)

            if recursive:
                shutil.rmtree(f, onerror=onerror)
            else:
                os.remove(f)
        except Exception, E:
            logger.error(E)
            raise FileUtilsError('rm', 'error occured while removing %s' % f)


def rsync(source, target, files=None,
          protected_files=None, delete=False, options=None):
    """Wrapper around rsync utility

    PARAMETERS
      source: source directory to sync. Note that it will be always considered
        as the 'content' of source (i.e source is passed with a trailing '/')
      target: target destination directory
      files:  if None all files from source are synchronized. Otherwise it
        should be a list of string that are patterns (rsync format) to select
        which files should be transfered.
      protected_files: type is the same as files parameters. Files that are
        matching these pattern will be protected in the destination directory
      delete: If true, files that don't exist in source will deleted in target.

    RETURN VALUE
      None

    REMARKS
      None
    """

    rsync_args = ['rsync', '-a']
    rsync_filename = ''

    if delete:
        rsync_args.append('--delete-excluded')

    if files is not None or protected_files is not None:
        rsync_filename = os.path.join(Env().tmp_dir,
                'rsync.list.%d' % os.getpid())

        f = open(rsync_filename, 'w')

        if files is not None:
            for filename in files:
                # add filename to the list
                f.write('+ /' + filename + '\n')

                # add also all its parent directories
                while filename != '':
                    (filename, _) = os.path.split(filename)
                    if filename != '':
                        f.write('+ /' + filename + '/\n')

        if protected_files is not None:
            for filename in protected_files:
                f.write('P /' + filename + '\n')

        # exclude files that did not match the patterns
        f.write('- *\n')
        f.close()

        # Update rsync arguments
        rsync_args.append('--filter=. ' + rsync_filename)

    if options is not None:
        for opt in options:
            rsync_args.append(opt)

    # Note: source and target must be in Unix format. Windows style for path
    # will not work.
    rsync_args.append(unixpath(source) + '/')
    rsync_args.append(unixpath(target))
    p = Run(rsync_args)

    # Clean temp file if necessary
    if files is not None or protected_files is not None:
        rm(rsync_filename)

    if p.status != 0:
        raise FileUtilsError('rsync',
                             'rsync failed with status %d\n%s\n%s' %
                             (p.status, " ".join(rsync_args), p.out))

    return


def touch(filename):
    """Update file access and modification times

    PARAMETERS
      filename: file to update

    RETURN VALUE
      None

    REMARKS
      If the file does not exist it is created.
    """
    if os.path.exists(filename):
        os.utime(filename, None)
    else:
        new_file = open(filename, 'w+')
        new_file.close()


def which(prog):
    """Locate executable

    Returns the full path of prog executable that would have been executed
    by gnatpython.ex.Run. It does this by searching for an executable in
    the directories listed in the environment variable PATH

    PARAMETERS
      prog: program to find

    RETURN VALUE
      absolute path to the program on success, '' otherwise.
    """
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(prog)
    if fpath:
        # Full path given, check if executable
        for progname in set((prog, prog + Env().host.os.exeext)):
            if is_exe(progname):
                return progname
    else:
        # Check for all directories listed in $PATH
        for pathdir in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(pathdir, prog)
            for progname in set((exe_file, exe_file + Env().host.os.exeext)):
                if is_exe(progname):
                    return progname
    return ""


def split_file(filename, split_line=None, keys=None, ignore_errors=False,
               host=None):
    """Split a file into a list or a dictionary

    PARAMETERS
      filename: file to read
      split_line: if None then the file is split by line. Otherwise lines are
        also subdivided using split_line as separator
      keys: this is a list of string. If split_line is None then this parameter
        is ignored. Otherwise, each line is subdivided using split_line
        parameter and each field associated with a key to compose a
        dictionary. If the number of keys is not sufficient additional fields
        are ignored. If the number of keys is superior to the number of fields
        then last keys will have '' as value.
      host: if not None, this is a remote file

    RETURN VALUE
      A list. If split_line if None then each element is a string (i.e a line
      of the file), otherwise each element is list of string (i.e a list split
      using split_line separator) or a dictionary (if keys are passed). If
      an I/O error occurs and ignore_errors is set to True then an empty list
      is returned.
    """
    result = []
    try:
        if host is None:
            fd = open(filename, 'r')
        else:
            fd = Run(['ssh', host, 'cat', filename]).out.splitlines()

        for line in fd:
            line = line.rstrip()
            if split_line is not None and line != '':
                tmp = line.split(split_line)
                if keys is None:
                    line = tmp
                else:
                    line = {}
                    tmp_last = len(tmp) - 1
                    for index, k in enumerate(keys):
                        if tmp_last < index:
                            line[k] = ''
                        else:
                            line[k] = tmp[index]
                result.append(line)
            elif split_line is None:
                result.append(line)
        if host is None:
            fd.close()
    except IOError, E:
        if not ignore_errors:
            logger.error(E)
            raise FileUtilsError('split_file',
                                 'cannot open file %s' % filename)
        else:
            result = []

    return result


def echo_to_file(filename, content, append=False):
    """Output content into a file

    PARAMETERS
      filename: file to write into
      content:  string to be written
      append:   if True append to the file. Otherwise overwrite (Default)

    RETURN VALUE
      None

    REMARKS
      This function is useful when writing few content to a file for which we
      don't want to keep a file descriptor opened . In other cases, it's more
      efficient to open a file and use the regular python I/O functions.
    """

    if append:
        fd = open(filename, 'a+')
        fd.seek(0, 2)
    else:
        fd = open(filename, 'w+')

    if isinstance(content, list):
        for l in content:
            fd.write(l + '\n')
    else:
        fd.write(content)

    fd.close()


def unpack_archive(filename,
                   dest,
                   selected_files=None,
                   remove_root_dir=False,
                   tar='tar',
                   unpack_cmd=None,
                   force_extension=None):
    """Unpack an archive file (.tgz, .tar.gz, .tar or .zip)

    PARAMETERS
      filename:        archive to unpack
      dest:            destination directory (should exist)
      selected_files:  list of files to unpack (partial extraction). If None
        all files are unpacked
      remove_root_dir: if True then the root dir of the archive is suppressed.
      tar:             path/to/tar binary (else use 'tar')
      unpack_cmd:      command to run to unpack the archive, if None use
                       default methods or raise FileUtilsError if archive
                       format is not supported.
                       The unpack_cmd must raise FileUtilsError in case of
                       failure.
      force_extension: specify the archive extension if not in the filename.
                       If filename has no extension and force_extension is None
                       unpack_archive will fail.
    RETURN VALUE
      None

    REMARKS
      rsync and cygpath (win32) utilities might be needed when using
      remove_root_dir option
      In case of error then FileUtilsError is raised
    """
    # First do some checks such as archive existence or destination directory
    # existence.
    if not os.path.isfile(filename):
        raise FileUtilsError('unpack_archive', 'cannot find %s' % filename)

    if not os.path.isdir(dest):
        raise FileUtilsError('unpack_archive',
                              'dest dir %s does not exist' % dest)

    if selected_files is None:
        selected_files = []

    logger.debug('unpack %s in %s' % (filename, dest))

    # We need to resolve to an absolute path as the extraction related
    # processes will be run in the destination directory
    filename = os.path.abspath(filename)

    # If remove_root_dir is set then extract to a temp directory first.
    # Otherwise extract directly to the final destination
    try:
        if remove_root_dir:
            tmp_dest = '%s.%d' % (os.path.abspath(dest), os.getpid())
            mkdir(tmp_dest)
        else:
            tmp_dest = dest

        if unpack_cmd is not None:
            # Use user defined unpack command
            unpack_cmd(filename, tmp_dest, selected_files=selected_files)
        elif Env().host.os.name == 'windows':
            import tarfile
            import zipfile

            if filename.endswith('.tar.gz') or filename.endswith('.tgz') or \
                    filename.endswith('.tar.bz2') or filename.endswith('.tar')\
                    or (force_extension is not None and force_extension in \
                            ['.tar.gz', '.tgz', '.tar.bz2', '.tar']):
                try:
                    fd = tarfile.open(filename, mode='r')
                    # selected_files must be converted to tarfile members
                    selected_files = [fd.getmember(f) for f in selected_files]

                    # detect directories. This is not done by default
                    # For each directory, select all the tree
                    selected_dirnames = [
                        d.name for d in selected_files if d.isdir()]
                    for dname in selected_dirnames:
                        selected_files += [
                            fd.getmember(n) for n in fd.getnames()
                            if n.startswith(dname + '/')]

                except tarfile.TarError, e:
                    raise FileUtilsError(
                        'unpack_archive',
                        'Cannot untar %s (%s) % (filename, e)')

            elif filename.endswith('.zip') or \
                    (force_extension is not None and force_extension == \
                         '.zip'):
                try:
                    fd = zipfile.ZipFile(filename, mode='r')
                except zipfile.BadZipfile, e:
                    raise FileUtilsError(
                            'unpack_archive',
                            'Cannot unzip %s (%s)' % (filename, e))
            else:
                raise FileUtilsError(
                        'unpack_archive',
                        'unknown format %s' % filename)

            if len(selected_files) == 0:
                selected_files = None
            fd.extractall(tmp_dest, selected_files)
            fd.close()
        else:
            # Handle .zip, .tar.gz and .tar archives
            if filename.endswith('.tar.gz') or filename.endswith('.tgz') or\
                    (force_extension is not None and force_extension in \
                         ['.tar.gz', '.tgz']):
                p = Run([['gzip', '-dc', filename],
                         [tar, '-xf', '-'] + selected_files], cwd=tmp_dest)
            elif filename.endswith('.tar.bz2') or\
                    (force_extension is not None and force_extension == \
                         '.tar.bz2'):
                p = Run([['bunzip2', '-dc', filename],
                         [tar, '-xf', '-'] + selected_files], cwd=tmp_dest)
            elif filename.endswith('.tar') or\
                    (force_extension is not None and force_extension == \
                         '.tar'):
                p = Run([tar, '-xf', filename] + selected_files, cwd=tmp_dest)
            elif filename.endswith('.zip') or\
                    (force_extension is not None and force_extension == \
                         '.zip'):
                p = Run(['unzip', '-o', filename] + selected_files,
                        cwd=tmp_dest)
            else:
                raise FileUtilsError('unpack_archive',
                                     'unknown format "%s"' % filename)
            if p.status != 0:
                # The extract command failed
                raise FileUtilsError('unpack_archive',
                                     'extraction of %s failed' % filename)

        if remove_root_dir:
            # First check that we have only one dir in our temp destination. If
            # not raise an error.
            file_list = ls(tmp_dest + '/*')
            if len(file_list) == 0:
                # Nothing to do...
                return
            if len(file_list) != 1:
                raise FileUtilsError('unpack_archive',
                                     'archive does not have a unique root dir')
            root_dir = file_list[0]

            # Now check if the destination directory is empty. If this is the
            # case a simple move will work, otherwise we need to do a rsync
            # (which cost more)

            if not os.listdir(dest):
                mv([os.path.join(root_dir, f)
                    for f in os.listdir(root_dir)], dest)
            else:
                rsync(root_dir, dest, delete=False)

    finally:
        # Always remove the temp directory before exiting
        if remove_root_dir:
            rm(tmp_dest, True)


def find(root, pattern=None, include_dirs=False,
         include_files=True, follow_symlinks=False):
    """Find files or directory recursively

    PARAMETERS
      root: directory from which the research start
      pattern: glob pattern that files or directories should match in order
        to be included in the final result
      include_dirs: if True include directories
      include_files: if True include regular files
      follow_symlinks: if True include symbolic links

    RETURN VALUE
      a list of files (strings)
    """

    result = []
    for root, dirs, files in os.walk(root, followlinks=follow_symlinks):
        root = root.replace('\\', '/')
        if include_files:
            for f in files:
                if pattern is None or fnmatch.fnmatch(f, pattern):
                    result.append(root + '/' + f)
        if include_dirs:
            for d in dirs:
                if pattern is None or fnmatch.fnmatch(d, pattern):
                    result.append(root + '/' + d)
    return result


def split_mountpoint(path):
    """Split a given path between it's mount point and the remaining part

    PARAMETERS
      A path string

    RETURN VALUE
      A length two tuple. First element is the mount point and second element
      is the remaining part of the path or None
    """

    # If the path is invalid raise an exception
    if not os.path.exists(path):
        raise FileUtilsError('split_mountpoint',
                             "path does not exist: %s" % path)

    # First get the absolute path
    path = os.path.realpath(os.path.abspath(path))
    queue = []

    # Iterate through the path until we found the mount point
    while not os.path.ismount(path):
        queue = [os.path.basename(path)] + queue
        path = os.path.dirname(path)
    if queue:
        return (path, os.path.join(*queue))
    else:
        return (path, None)


def get_path_nfs_export(path):
    """Guess NFS related information for a given path

    PARAMETERS
      path: a string containing a valid path

    RETURN VALUE
      a length four tuple containing: (machine IP, machine name, export, path
      relative to the export). Note that the function is just making a guess.
      We cannot really ensure that the return export really exist). If the
      function canot guess the NFS export then None is returned.
    """
    def add_ip_info(machine, export, path):
        """Add ip information"""
        domain = '.' + e.host.domain if e.host.domain else ''
        return (socket.gethostbyname(machine),
                machine + domain,
                export,
                path)

    # First find the mount point
    e = Env()
    mountfiles = []
    if e.host.os.name.lower() != 'windows':
        # Don't try to look into unix specific files or to use 'mount' command
        # on Windows platform (if the later exists it will be a cygwin tool
        # that is not useful in our case).
        mountfiles = ['/etc/mtab', '/etc/mnttab', '/proc/mounts', 'mount']

    mount_point, path = split_mountpoint(path)

    # Then read system imports
    for fname in mountfiles:

        # Extract necessary fields
        if fname == 'mount':
            # Either by parsing the output of the mount command
            mount_bin = which('mount')
            if not mount_bin:
                # /sbin is not always in the PATH
                if os.path.exists('/sbin/mount'):
                    mount_bin = '/sbin/mount'
                else:
                    # No mount program found !
                    raise FileUtilsError(
                            'get_path_nfs_export', 'Cannot find mount')
            p = Run([mount_bin])
            if p.status != 0:
                raise FileUtilsError(
                        'get_path_nfs_export', 'Error when calling mount')
            lines = p.out.splitlines()
            mount_index = 2

        elif os.path.exists(fname):
            # Or by reading a system file
            with open(fname, 'r') as f:
                lines = f.readlines()
            mount_index = 1
        else:
            continue

        for line in lines:
            fields = line.rstrip().split()
            if fields[mount_index] == mount_point:
                # We found a file system. It can either be a local
                # filesystem or on a remote machine.
                tmp = fields[0].split(':')
                if len(tmp) == 1:
                    # This is a local fs. Here the heuristic is to
                    # consider the export
                    return add_ip_info(e.host.machine, mount_point, path)
                elif len(tmp) == 2:
                    # Looks like 'nfs' import
                    return add_ip_info(tmp[0], tmp[1], path)
                else:
                    # What's that ?
                    return add_ip_info(e.host.machine, mount_point, path)

    if e.host.os.name.lower() == 'windows':
        tmp = path.split('\\')
        if len(tmp) > 1:
            return add_ip_info(e.host.machine, '/' + tmp[0], '/'.join(tmp[1:]))


def substitute_template(template, target, variables):
    """Create a file using a template and and a dictionnary.

    PARAMETERS
      template: path to the template
      target: path in which to dump the result
      variables: dictionary that will be applied to the template content
                 using the '%' Python operator

    RETURN VALUE
      None
    """
    if not os.path.isfile(template):
        raise FileUtilsError('process_template',
                             'cannot find template %s' % template)
    with open(template) as f_template:
        with open(target, 'wb') as fd:
            fd.write(f_template.read() % variables)


def get_rlimit():
    """Return rlimit path"""

    def get_path(relative_path):
        """Search for binary in directory parent

        PARAMETERS
          binary: the file or directory to search for
          parent: the directory where binary should be located

        RETURN VALUE
          Return the path or empty string
        """
        start_dir = os.path.join(os.path.dirname(__file__))

        # if current file equals to the already tested one, we stop
        previous_dir = ''
        while os.path.realpath(start_dir) != os.path.realpath(previous_dir):
            previous_dir = start_dir
            start_dir = os.path.join(start_dir, os.pardir)
            if not os.path.exists(start_dir):
                return ""
            if os.path.exists(os.path.join(start_dir, relative_path)):
                return os.path.join(start_dir, relative_path)

        return ""

    if Env().host.os.name.lower() == 'windows':
        path = get_path(os.path.join('Scripts', 'rlimit'))
    else:
        path = get_path(os.path.join('bin', 'gnatpython-rlimit'))

    return path or which("rlimit" + Env().host.os.exeext)