Debian Codegraph @

case_studies/micromanage/cmds.py

raw
1 # Copyright 2015 Google Inc. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import glob
16 import os
17
18 # E.g. replace Simon's cat with 'Simon'\''s cat'.
19 def escape(s):
20 return "'%s'" % s.replace("'", "'\"'\"'")
21
22 def file_glob(given_glob, to, prefix):
23 dirs = []
24 files = []
25 lp = len(prefix)
26 for f in glob.glob(given_glob):
27 if os.path.isdir(f):
28 more_files = file_glob('%s/*' % f, to, prefix)
29 files += more_files
30 else:
31 files.append((f, to + f[lp:]))
32 return files
33
34
35 def compile_command_to_bash(cmd):
36 if isinstance(cmd, basestring):
37 if len(cmd) > 1 and cmd[0] == '#':
38 comment = cmd[1:].strip()
39 return ['echo %s' % escape(comment)]
40 return [cmd]
41 elif cmd['kind'] == 'LiteralFile':
42 return [
43 'echo -n %s > %s' % (escape(cmd['content']), escape(cmd['to'])),
44 'chmod -v %s %s' % (cmd['filePermissions'], escape(cmd['to'])),
45 'chown -v %s.%s %s' % (cmd['owner'], cmd['group'], escape(cmd['to'])),
46 ]
47 elif cmd['kind'] == 'CopyFile':
48 files = file_glob(cmd['from'], cmd['to'], os.path.dirname(cmd['from']))
49 dirs = set([os.path.dirname(f[1]) for f in files]) - {cmd['to']}
50 lines = []
51 for d in sorted(dirs):
52 lines += [
53 'mkdir -v -p %s' % escape(d),
54 'chmod -v %s %s' % (cmd['dirPermissions'], escape(d)),
55 'chown -v %s.%s %s' % (cmd['owner'], cmd['group'], escape(d)),
56 ]
57 for f in sorted(files):
58 with open (f[0], "r") as stream:
59 content = stream.read()
60 lines += [
61 'echo -n %s > %s' % (escape(content), escape(f[1])),
62 'chmod -v %s %s' % (cmd['filePermissions'], escape(f[1])),
63 'chown -v %s.%s %s' % (cmd['owner'], cmd['group'], escape(f[1])),
64 ]
65 return lines
66 elif cmd['kind'] == 'EnsureDir':
67 return [
68 'mkdir -v -p %s' % escape(cmd['dir']),
69 'chmod -v %s %s' % (cmd['dirPermissions'], escape(cmd['dir'])),
70 'chown -v %s.%s %s' % (cmd['owner'], cmd['group'], escape(cmd['dir'])),
71 ]
72 else:
73 raise RuntimeError('Did not recognize image command kind: ' + cmd['kind'])
74