File: CopyMove.py

package info (click to toggle)
aap 1.072-1.1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny
  • size: 4,976 kB
  • ctags: 2,160
  • sloc: python: 15,113; makefile: 62; sh: 13
file content (683 lines) | stat: -rw-r--r-- 26,566 bytes parent folder | download | duplicates (2)
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
# Part of the A-A-P recipe executive: copy and move files (remotely)

# Copyright (C) 2002-2003 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

#
# These are functions to copy and move files.  Not only on the local system,
# also to remote systems, using http://, ftp://, etc.
#

import os
import os.path
import string
import re

from Dictlist import str2dictlist
from Error import *
from Process import recipe_error, option_error
from Util import *
from Work import getrpstack
from Message import *


def copy_move(line_nr, recdict, arg, copy):
    """Implementation of ":copy -x from to" and ":move -x from to".
       When "copy" is non-zero copying is done, otherwise moving.
       "arg" is the whole argument.
       "line_nr" is used for error messages."""

    # Skip when not actually building.
    cmdname = (copy and ':copy') or ':move'
    if skip_commands():
        msg_skip(line_nr, recdict, cmdname + ' ' + arg)
        return
    rpstack = getrpstack(recdict, line_nr)

    # Get the arguments and check the options.
    # TODO: check if all options are handled properly
    from Commands import get_args
    opt = {"f": "force", "force": "force",
           "i": "interactive", "interactive": "interactive",
           "e": "exist", "exist": "exist", "exists": "exist",
           "m": "mkdir", "mkdir": "mkdir",
           "c": "continue", "continue": "continue",
           "q": "quiet", "quiet": "quiet"}
    if copy:
        opt.update({
                "u": "unlink", "unlink": "unlink",
                "p": "preserve", "preserve": "preserve",
                "r": "recursive", "recursive": "recursive",
                "k": "keepdir", "keepdir": "keepdir"})

    optiondict, attrdict, argdictlist = get_args(line_nr, recdict, arg, opt)
    if attrdict:
        option_error(rpstack, attrdict, cmdname)
    if len(argdictlist) < 2:
        recipe_error(rpstack, _("%s command requires at least two arguments")
                                                                     % cmdname)

    remote_copy_move(rpstack, recdict, copy, argdictlist[:-1],
                                    argdictlist[-1], optiondict, 1, errmsg = 1)

# Schemes handled by scheme_copy().  When changing this also need to change
# code and comments below!
scheme_copy_names = ["rcp", "scp", "rsync"]

def scheme_copy(rpstack, recdict, scheme, fromfile, tmach, destpath, fcount):
    """
    Use rcp, scp or rsync, specified with "scheme" to copy "fromfile" (with
    "fcount" file names in quotes) to tmach:destpath.
    Return non-zero for success.
    """
    # Install rcp/scp/rsync when needed.
    from DoInstall import assert_pkg
    assert_pkg(rpstack, recdict, scheme)

    from Remote import get_progname_rsync, get_progname_rcp, get_progname_scp
    if scheme == "rcp":
        cmd = "%s %s '%s:%s'" % (get_progname_rcp(recdict),
                                                     fromfile, tmach, destpath)
    elif scheme == "scp":
        cmd = "%s %s '%s:%s'" % (get_progname_scp(recdict),
                                                     fromfile, tmach, destpath)
    else:
        # A bug in rsync: it can't handle "file(with)parenthesis" in the
        # destination, but escaping them in the source is not allowed!
        d = re.sub("([()])", r"\\\1", destpath)
        cmd = "%s %s '%s:%s'" % (get_progname_rsync(recdict),
                                                            fromfile, tmach, d)

    if os.name == "posix":
        # On Unix we can use "tee".
        ok, text = redir_system_int(recdict, cmd)
    else:
        # Scp may ask for a password.  When we can't use "tee" we need to
        # see the message.  Can't catch the text output then...
        ok = logged_system(recdict, "{interactive} " + cmd) == 0
        text = ''

    if text:
        msg_log(recdict, text)
        # Check for an error connecting, scp doesn't exit with an error value
        # then.  Usual messages are:
        #    "Secure connection to vim.sf.net refused."
        #    "lost connection"
        #    "Read-only file system"
        i = string.find(text, "connection to")
        if i > 0:
            e = string.find(text, "\n", i)
            if e > 0:
                i = string.find(text, "refused", i, e)
            else:
                i = -1
        if i > 0 or string.find(text, "lost connection") >= 0:
            ok = 0
        elif string.find(text, "Permission denied") >= 0:
            # Happens when a file exists and permissions don't allow
            # overwriting: scp: vim/new/con_cvs.php: Permission denied
            # TODO: check the file name and only mark this one as failed.
            ok = 0
        elif string.find(text, "Read-only file system") >= 0:
            # Happens when the file system was mounted read-only.
            # TODO: check the file name and only mark this one as failed.
            ok = 0
        elif string.find(text, "Not a directory") >= 0:
            # Happens when copying multiple files into a file.
            ok = 0
        elif string.find(text, "No such file or directory") >= 0:
            ok = 0
            msg_info(recdict,
                     _('looks like the directory does not exist, creating it'))
            # TODO: This is just guessing; how do we know if the destination
            # is a directory or a file?
            if fcount > 1:
                dirname = destpath
            else:
                dirname = os.path.dirname(destpath)
            mkdircmd = ('ssh %s mkdir -p %s' % (tmach, dirname))
            if logged_system(recdict, mkdircmd) == 0:
                # Try copying again.
                ok = (logged_system(recdict, cmd) == 0)

    return ok

# Cached ftp connections.
ftp_conn = {}
did_set_exitfunc = 0
old_exitfunc = None

def ftpCloseAll():
    """
    Close all cached ftp connections.  Invoked on exit.
    """
    import ftplib

    if old_exitfunc:
        old_exitfunc()      # Invoke previous exit function.

    global ftp_conn
    for ftp in ftp_conn.values():
        try:
            ftp.quit()
        except ftplib.all_errors, e:
            msg_log({}, _("could not quit an ftp connection: %s") % e)
    ftp_conn = {}


# Cached passwords for ftp connections.
ftp_pass = {}

def ftpConnect(mach):
    """
    Connect to an ftp server "mach".
    If "mach" is in the form "user:passwd@ftp.com" use that.
    Otherwise consult the netrc file or ask the user.
    Returns a tuple.  The first item is an ftp object.
    If the connection was successful the second item is an empty string.
    If the connection failed the second item is an error message.
    """

    # Use a cached connection if there is one.
    if mach in ftp_conn.keys():
        return ftp_conn[mach], ''

    passwd = ''
    acct = ''
    key = None
    msg = ''

    # For "user:passwd@ftp.com" split at the @
    i = string.find(mach, '@')
    if i > 0:
        user = mach[:i]
        machname = mach[i+1:]
        i = string.find(user, ':')
        if i > 0:
            passwd = user[i+1:]
            user = user[:i]
        else:

            key = user + "@" + machname
            passwd = ftp_pass.get(key)
            if not passwd:
                prompt = (_('Enter password for user %s at %s: ')
                                                        % (user, machname))
                try:
                    import getpass
                    passwd = getpass.getpass(prompt)
                except:
                    # TODO: should display stars for typed chars
                    passwd = raw_input(prompt)
    else:
        user = ''
        machname = mach

        import aapnetrc
        # obtain the login name and password from the netrc file
        try:
            n = aapnetrc.netrc()
            res = n.authenticators(machname)
            if res is None:
                user = ''
            else:
                user, acct, passwd = res
        except (IOError, aapnetrc.NetrcParseError), e:
            pass

    # Try to open the connection to the ftp server.
    import ftplib
    try:
        ftp = ftplib.FTP()

        i = string.find(machname, ':')
        if i > 0:
            # Port number specified.
            ftp.connect(machname[0:i], machname[i+1:])
        else:
            # Use default port number.
            ftp.connect(machname)

        if user != '':
            if passwd != '':
                if acct != '':
                    ftp.login(user, passwd, acct)
                else:
                    ftp.login(user, passwd)
            else:
                ftp.login(user)
        else:
            ftp.login()
    except ftplib.all_errors, e:
        msg = (_('Cannot open connection to "%s": %s') % (mach, str(e)))
    else:
        if key and passwd:
            # Remember the typed password, so that the user doesn't have to
            # type it again.
            ftp_pass[key] = passwd

        # Cache the connection for another time.
        ftp_conn[mach] = ftp

        # Setup the exit function to close the connection.
        global did_set_exitfunc
        global old_exitfunc
        if not did_set_exitfunc:
            did_set_exitfunc = 1
            old_exitfunc = getattr(sys, 'exitfunc', None)
            sys.exitfunc = ftpCloseAll

    return ftp, msg


def remote_copy_move(rpstack, recdict, copy, from_items, to_item,
                                            optiondict, argexpand, errmsg = 0):
    """Copy or move command.  Copy when "copy" is non-zero.
       "from_items" is a dictlist of the files to copy or move from.
       "to_item" is the dictionary of the destination.
       "optiondict" is a dictionary with options:
            recursive: recursive copy.
            exist: skip if destination exists
            interactive: ask about overwriting.
            preserve: keep mode bits and timestamp
            quiet: don't report copied/moved files
            continue: ignore wildcards without matches
            mkdir: create directory when needed
       "argexpand" is non-zero when wildcards are to be expanded (called from
       ":copy" or ":move").
       When "errmsg" is non-zero, call recipe_error() for an error.
       Returns a list of filenames that failed."""
    from Remote import url_split3
    import glob
    failed = []

    # -l: change symlinks to real files
    #if optiondict.get("unlink"):
    #    keepsymlinks = 0
    #else:
    #    keepsymlinks = 1

    # Expand and check the "from" arguments.
    fromlist = []
    for a in from_items:
        fname = a["name"]
        fscheme, fmach, fpath = url_split3(fname)
        if fscheme == '':
            # It's a local file, may expand ~user and wildcards.
            f = os.path.expanduser(fname)
            if argexpand:
                fl = glob.glob(f)
                if len(fl) == 0:
                    if optiondict.get("continue") and has_wildcard(f):
                        continue
                    recipe_error(rpstack, _('No match for "%s"') % fname)
            else:
                fl = [ f ]
            # For copy without {r} sources can't be a directory.
            if copy and not optiondict.get("recursive"):
                for l in fl:
                    if os.path.isdir(l):
                        recipe_error(rpstack,
                             _('Copying a directory requires {r} flag: %s') % l)
            fromlist.extend(fl)

        else:
            # It's a URL, append without expanding.
            if not copy:
                recipe_error(rpstack, _('Cannot move from a URL yet: "%s"')
                                                                       % fname)
            if argexpand:
                # Do change [*] to *, we might support expanding later.
                f = expand_unescape(fname)
            else:
                f = fname
            fromlist.append(f)

    # Expand and check the "to" argument.
    tname = to_item["name"]
    tscheme, tmach, tpath = url_split3(tname)
    if tscheme == '':
        # For a local file expand "~/" and "~user/".  Don't use "tname", it may
        # start with "file:".
        tpath = os.path.expanduser(tpath)
    if argexpand:
        if tscheme == '':
            # For a local destination file expand wildcards.  If expanding
            # results in no matches use the name without expansion.
            l = glob.glob(tpath)
            if len(l) > 1:
                recipe_error(rpstack, _('More than one match for "%s"') % tname)
            if len(l) == 1:
                tpath = l[0]
        else:
            # Can't expand wildcards in a URL yet, at least remove escaped
            # wildcards.
            tpath = expand_unescape(tpath)

    if tscheme == '' and optiondict.get("mkdir"):
        # Create local target directory when it doesn't exist.
        if len(fromlist) > 1:
            dir = tpath;
        else:
            dir = os.path.dirname(tpath)
        may_create_dir(recdict, rpstack, dir, optiondict.get("quiet"))

    # If there is more than one source, target must be a directory.
    if tscheme == '' and len(fromlist) > 1 and not os.path.isdir(tpath):
        recipe_error(rpstack, _('Destination must be a directory: "%s"')
                                                                       % tname)

    msg = ''
    if tscheme == "ftp":
        #
        # Prepare for uploading through ftp.
        #
        ftp, msg = ftpConnect(tmach)

    elif tscheme in scheme_copy_names:
        #
        # TODO: Prepare for uploading through rcp/scp/rsync.
        #
        pass

    elif tscheme != '':
        msg = _('Can only upload to rcp://, scp://, rsync:// and ftp://')

    # If copy/move isn't possible either give an error message or return the
    # whole list of sources.
    if msg:
        if argexpand:
            msg_error(recdict, msg)
            return map(lambda x : x["name"], from_items)
        recipe_error(rpstack, msg)

    # files to be copied with scp or rsync later.
    scheme_files = {}
    scheme_filelist = {}
    for scheme in scheme_copy_names:
        scheme_files[scheme] = ''
        scheme_filelist[scheme] = []

    #
    # Loop over all "from" files.
    #
    for fname in fromlist:
        fscheme, fmach, fpath = url_split3(fname)

        # If the destination is a directory, append the source file name to the
        # destination directory.
        # "dest" includes the scheme (may be "file:" when "tscheme" is empty).
        if ((tscheme != '' and len(fromlist) > 1)
                                  or (tscheme == '' and os.path.isdir(tpath))):
            if optiondict.get("keepdir"):
                dest = os.path.join(tname, fpath)
                destpath = os.path.join(tpath, fpath)
                if tscheme == '' and os.path.dirname(fpath):
                    # Create the directory if it doesn't exist.
                    dir = os.path.dirname(destpath)
                    may_create_dir(recdict, rpstack, dir,
                                                       optiondict.get("quiet"))
            else:
                dest = os.path.join(tname, os.path.basename(fname))
                destpath = os.path.join(tpath, os.path.basename(fname))
        else:
            dest = tname
            destpath = tpath

        # If destination is a local file and exists:
        # - When {exist} option used, silently ignore.
        # - When {interactive} option used, ask for overwriting.  Use a special
        #   string to allow translating the response characters.
        if tscheme == '' and os.path.exists(destpath):
            if optiondict.get("exist"):
                msg = _('file already exists: "%s"') % dest
                msg_note(recdict, msg)
                failed.append(fname)
                continue
            if optiondict.get("interactive"):
                reply = raw_input(_('"%s" exists, overwrite? (y/n) ') % dest)
                if (len(reply) == 0 or not reply[0]
                              in _("yY   up to four chars that mean yes")[:4]):
                    if copy:
                        msg_note(recdict, _("file not copied"))
                    else:
                        msg_note(recdict, _("file not moved"))
                    failed.append(fname)
                    continue

        if fscheme == '' and tscheme == '':
            #
            # local file copy or move
            #

            if not copy:
                try:
                    os.rename(fpath, destpath)
                    done = 1
                except:
                    done = 0        # renaming failed, try copying

            if copy or not done:
                try:
                    import shutil

                    # TODO: handle symlinks and "keepsymlinks".
                    if os.path.isdir(fpath):
                        # Cannot use shutil.copytree here, it fails when the
                        # destination already exists.
                        if not os.path.exists(destpath):
                            os.mkdir(destpath)
                        # Call ourselves recursively
                        from Commands import dir_contents
                        flist = map(lambda x: {"name": x}, dir_contents(fpath))

                        if flist:
                            # Remove the "keepdir" attribute, the directory
                            # name is already in "destpath" now.
                            if optiondict.has_key("keepdir"):
                                opt = optiondict.copy()
                                del opt["keepdir"]
                            else:
                                opt = optiondict

                            f = remote_copy_move(rpstack, recdict, copy, flist,
                                         {"name": destpath}, opt, 0, errmsg)
                            if f:
                                failed.extend(f)
                    elif not copy or optiondict.get("preserve"):
                        shutil.copy2(fpath, destpath)
                    else:
                        shutil.copy(fpath, destpath)
                except (IOError, OSError), e:
                    msg = (_('Cannot copy "%s" to "%s": %s')
                                                       % (fname, dest, str(e)))
                    if not argexpand and not errmsg:
                        msg_note(recdict, msg)
                        failed.append(fname)
                    else:
                        recipe_error(rpstack, msg)
                    continue
                if not copy:
                    if os.path.isdir(fpath):
                        deltree(fpath)
                    else:
                        os.remove(fpath)

            if not optiondict.get("quiet"):
                f = shorten_name(fpath)
                if copy:
                    msg_info(recdict, _('Copied "%s" to "%s"') % (f, dest))
                else:
                    msg_info(recdict, _('Moved "%s" to "%s"') % (f, dest))

        else:
            if fscheme != '':
                # download to local file
                from Remote import url_download

                try:
                    if tscheme != '':
                        tmpfile, rtime = url_download(recdict, fname, '')
                    else:
                        tmpfile, rtime = url_download(recdict, fname, destpath)
                except IOError, e:
                    msg = (_('Cannot download "%s" to "%s": %s')
                                                       % (fname, dest, str(e)))
                    if not argexpand and not errmsg:
                        msg_note(recdict, msg)
                        failed.append(fname)
                    else:
                        recipe_error(rpstack, msg)
                    continue

            if tscheme != '':
                if fscheme != '':
                    # use temporary file
                    fromfile = tmpfile
                else:
                    fromfile = fpath

                postponed = 0
                if tscheme == 'ftp':
                    # No system command, give a message about what we're doing,
                    # it may take a while.
                    if fscheme != '':
                        msg_info(recdict, _('Uploading to "%s"' % dest))
                    else:
                        if not copy:
                            msg_info(recdict, _('Moving "%s" to "%s"'
                                                              % (fname, dest)))
                        else:
                            msg_info(recdict, _('Uploading "%s" to "%s"'
                                                              % (fname, dest)))

                    # FTP must use '/' path separator characters,
                    # os.path.join() may have used something else.
                    if os.sep != '/':
                        destpath = string.replace(destpath, os.sep, '/')

                    def store_file(ftp, fromfile, destpath):
                        import ftplib       # avoid warning message
                        error = None
                        f = open(fromfile, "rb")
                        try:
                            ftp.storbinary("STOR " + destpath, f, 8192)
                        except ftplib.all_errors, e:
                            error = e
                        f.close()
                        return error

                    error = store_file(ftp, fromfile, destpath)

                    # If it looks like the directory doesn't exist, try
                    # creating it.
                    if (error and string.find(str(error),
                                                  "No such file or dir") >= 0):
                        dir = os.path.dirname(destpath)
                        if dir:
                            import ftplib
                            msg_info(recdict, _('Directory does not appear to exist, creating it...'))
                            try:
                                ftp.mkd(dir)
                            except ftplib.all_errors, e:
                                msg_info(recdict, _('Could not create directory'))
                                pass
                            else:
                                msg_info(recdict, _('Directory created, attempt uploading again...'))
                                error = store_file(ftp, fromfile, destpath)

                    if error:
                        msg = (_('Cannot upload "%s" to "%s": %s')
                                                   % (fname, dest, str(error)))
                        if not argexpand and not errmsg:
                            msg_note(recdict, msg)
                            failed.append(fname)
                        else:
                            recipe_error(rpstack, msg)
                        if fscheme != '':
                            os.remove(tmpfile)      # delete temporary file
                        continue

                elif tscheme in scheme_copy_names:
                    if fscheme == '' and len(fromlist) > 1:
                        # do all local files at once below
                        scheme_files[tscheme] = (scheme_files[tscheme]
                                                       + "'" + fromfile + "' ")
                        scheme_filelist[tscheme].append(fromfile)
                        postponed = 1
                    elif not scheme_copy(rpstack, recdict, tscheme,
                                     "'" + fromfile + "'", tmach, destpath, 1):
                        msg = _('Cannot upload "%s" to "%s"') % (fname, dest)
                        if not argexpand and not errmsg:
                            msg_note(recdict, msg)
                            failed.append(fname)
                        else:
                            recipe_error(rpstack, msg)
                        if fscheme != '':
                            os.remove(tmpfile)      # delete temporary file
                        continue

                if fscheme != '':
                    os.remove(tmpfile)      # delete temporary file
                    msg_info(recdict, _('Uploaded to "%s"' % dest))
                else:
                    if not copy:
                        os.remove(fname)
                        msg_info(recdict, _('Moved "%s" to "%s"'
                                                % (shorten_name(fname), dest)))
                    elif not postponed:
                        msg_info(recdict, _('Uploaded "%s" to "%s"'
                                                % (shorten_name(fname), dest)))



    # End of loop over all "from" files.

    if fscheme != '':
        from Remote import url_cleanup
        url_cleanup(fscheme)

    # Copy collected files with rcp, scp and rsync.
    for scheme in scheme_copy_names:
        files = scheme_files[scheme]
        if files:
            filelist = scheme_filelist[scheme]

            # If there is only one file to copy, add its basename to the
            # destination path to avoid creating a file by the name of the
            # directory of that file.
            if len(filelist) == 1:
                tpath = os.path.join(tpath,
                        os.path.basename(filelist[0]))

            if scheme_copy(rpstack, recdict, scheme, files, tmach, tpath,
                                                                len(filelist)):
                dl = shorten_dictlist(str2dictlist(rpstack, files))
                flist = map(lambda x: x["name"], dl)
                msg_info(recdict, _('Uploaded "%s" to "%s"' % (flist, tname)))
            else:
                msg = _('Cannot upload "%s" to "%s"') % (files, tname)
                if not argexpand and not errmsg:
                    msg_note(recdict, msg)
                    failed.extend(filelist)
                else:
                    recipe_error(rpstack, msg)

    return failed


def may_create_dir(recdict, rpstack, dir, quiet):
    """
    Create directory "dir" if it does not exist.
    """
    if not os.path.exists(dir):
        try:
            os.makedirs(dir)
            if not quiet:
                msg_info(recdict, _('Created directory "%s"') % dir)
        except StandardError, e:
            recipe_error(rpstack, _('Destination directory "%s" cannot be created: %s') % (dir, str(e)))


# vim: set sw=4 et sts=4 tw=79 fo+=l: