~tribaal/+junk/landscape-client-14.12-0ubuntu0.10.04

« back to all changes in this revision

Viewing changes to landscape/lib/fs.py

  • Committer: Chris Glass
  • Date: 2014-12-15 06:54:28 UTC
  • Revision ID: chris.glass@canonical.com-20141215065428-e23g6yyvrsvyb656
Imported pristine tarball.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""File-system utils"""
 
2
 
 
3
import os
 
4
import time
 
5
 
 
6
 
 
7
def create_file(path, content):
 
8
    """Create a file with the given content.
 
9
 
 
10
    @param path: The path to the file.
 
11
    @param content: The content to be written in the file.
 
12
    """
 
13
    fd = open(path, "w")
 
14
    fd.write(content)
 
15
    fd.close()
 
16
 
 
17
 
 
18
def append_file(path, content):
 
19
    """Append a file with the given content.
 
20
 
 
21
    The file is created, if it doesn't exist already.
 
22
 
 
23
    @param path: The path to the file.
 
24
    @param content: The content to be written in the file at the end.
 
25
    """
 
26
    fd = open(path, "a")
 
27
    fd.write(content)
 
28
    fd.close()
 
29
 
 
30
 
 
31
def read_file(path, limit=None):
 
32
    """Return the content of the given file.
 
33
 
 
34
    @param path: The path to the file.
 
35
    @param limit: An optional read limit. If positive, read up to that number
 
36
        of bytes from the beginning of the file. If negative, read up to that
 
37
        number of bytes from the end of the file.
 
38
    @return content: The content of the file, possibly trimmed to C{limit}.
 
39
    """
 
40
    fd = open(path, "r")
 
41
    if limit and os.path.getsize(path) > abs(limit):
 
42
        whence = 0
 
43
        if limit < 0:
 
44
            whence = 2
 
45
        fd.seek(limit, whence)
 
46
    content = fd.read()
 
47
    fd.close()
 
48
    return content
 
49
 
 
50
 
 
51
def touch_file(path, offset_seconds=None):
 
52
    """Touch a file, creating it if it doesn't exist.
 
53
 
 
54
    @param path: the path to the file to be touched.
 
55
    @param offset_seconds: a signed integer number of seconds to offset the
 
56
        atime and mtime of the file from the current time.
 
57
 
 
58
    """
 
59
    fd = open(path, "a")
 
60
    fd.close()
 
61
    if offset_seconds is not None:
 
62
        offset_time = long(time.time()) + offset_seconds
 
63
        touch_time = (offset_time, offset_time)
 
64
    else:
 
65
        touch_time = None
 
66
    os.utime(path, touch_time)