Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""hods - home directory synchronization. 

2 

3Copyright (C) 2016-2020 Mathias Stelzer <knoppo@rolln.de> 

4 

5hods is free software: you can redistribute it and/or modify 

6it under the terms of the GNU General Public License as published by 

7the Free Software Foundation, either version 3 of the License, or 

8(at your option) any later version. 

9 

10hods is distributed in the hope that it will be useful, 

11but WITHOUT ANY WARRANTY; without even the implied warranty of 

12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

13GNU General Public License for more details. 

14 

15You should have received a copy of the GNU General Public License 

16along with this program. If not, see <http://www.gnu.org/licenses/>. 

17""" 

18from hods.utils import run 

19 

20 

21class Script: 

22 """A runnable string descriptor.""" 

23 

24 def __init__(self, hook, name, content=''): 

25 """Initialize script.""" 

26 self.hook = hook 

27 self.name = name 

28 self.content = content 

29 

30 def __str__(self): 

31 """Return the content as string representation.""" 

32 return self.content 

33 

34 def run(self): 

35 """Run this script in a shell. 

36 

37 Returns: The completed process information 

38 

39 Raises: 

40 subprocess.CalledProcessError: If the script returns a non-zero exitcode. 

41 """ 

42 script = self.content.strip() 

43 if not script: 

44 return 

45 return run(script, shell=True) 

46 

47 

48class Hook: 

49 """A container to access and store pre- and post- hook sequences.""" 

50 

51 def __init__(self, hooks, name): 

52 """Initialize hook.""" 

53 self.hooks = hooks 

54 self.name = name 

55 

56 self.pre = Script(self, 'pre') 

57 self.post = Script(self, 'post') 

58 

59 def load(self, data): 

60 """Load given data for this instance.""" 

61 self.pre.content = data.get('pre', '') 

62 self.post.content = data.get('post', '') 

63 

64 def as_dict(self): 

65 """Return `dict` to store this instance.""" 

66 return { 

67 'pre': self.pre.content, 

68 'post': self.post.content, 

69 } 

70 

71 

72class Hooks: 

73 """A container to access and store hooks for a feature.""" 

74 

75 def __init__(self, feature, *hooks): 

76 """Initialize feature hooks.""" 

77 self.feature = feature 

78 

79 self.names = list(hooks) 

80 

81 for name in hooks: 

82 hook = Hook(self, name) 

83 setattr(self, name, hook) 

84 

85 def __iter__(self): 

86 """Generate `Hook` instances in this container.""" 

87 for name in self.names: 

88 yield getattr(self, name) 

89 

90 def load(self, data): 

91 """Load given data for this instance.""" 

92 for hook in self: 

93 hook.load(data.get(hook.name, {})) 

94 

95 def as_dict(self): 

96 """Return `dict` to store this instance.""" 

97 return {h.name: h.as_dict() for h in self}