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

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

""" 

:py:mod:`sysdirs.specifications` 

 

Copyright (C) 2018 Mathias Stelzer 

 

sysdirs 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. 

 

sysdirs 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/>. 

""" 

from __future__ import absolute_import, unicode_literals, print_function 

 

import grp 

import os 

import shutil 

import sys 

import tempfile 

 

 

if sys.version_info[0] < 3: 

FileExistsError = OSError 

 

 

class InitializationError(Exception): 

pass 

 

 

def try_makedirs(path, mode=0o700): 

try: 

os.makedirs(path, mode) 

except FileExistsError: 

pass 

else: 

os.chmod(path, mode) 

return path 

 

 

def touch(path, mode=None): 

with open(path, 'w') as f: 

f.write('') 

if mode is not None: 

os.chmod(path, mode) 

return path 

 

 

class DirectorySpecification(object): 

name = NotImplemented 

description = NotImplemented 

 

hidden = False 

force = False 

requires_root = False 

 

def __init__(self, force=None): 

if force is not None: 

self.force = force 

 

self._installer = None 

 

def init(self, installer): 

"""Initialize installer.""" 

self._installer = installer 

 

def init_install(self): 

"""Initialize installation.""" 

pass 

 

@property 

def installer(self): 

if self._installer is None: 

msg = '{} instance {} is not initialized'.format(self.__class__.__name__, self) 

raise InitializationError(msg) 

return self._installer 

 

def is_available_for_installation(self): 

return True 

 

def is_installed(self): 

return self.any_config_dir_exists() or self.any_data_dir_exists() 

 

@property 

def all(self): 

return list(set(list(self.get_config_dirs()) + list(self.get_data_dirs()) + [ 

self.get_cache(), 

self.get_var(), 

self.get_run(), 

self.get_log() 

])) 

 

def uninstall(self): 

for directory in self.all: 

shutil.rmtree(directory, ignore_errors=True) 

 

def _install_type(self, type_dir, type_dir_mode, source=None, relpath=None, mode=None): 

try_makedirs(type_dir, type_dir_mode) 

 

if relpath is None: 

if source is None: 

return 

relpath = os.path.basename(source) 

elif source is not None and relpath.endswith(os.sep): 

relpath = os.path.join(relpath, os.path.basename(source)) 

destination = os.path.normpath(os.path.join(type_dir, relpath)) 

 

dirname = os.path.dirname(destination) 

try_makedirs(dirname, type_dir_mode) 

 

if source is None: 

if relpath.endswith(os.sep): 

try_makedirs(destination, type_dir_mode) 

else: 

touch(destination, mode) 

else: 

shutil.copyfile(source, destination) 

 

if mode is not None: 

os.chmod(destination, mode) 

 

return destination 

 

@property 

def config(self): 

return self.get_config() 

 

def get_config(self): 

"""Return the directory to store configuration files.""" 

raise NotImplementedError 

 

def get_config_dirs(self): 

"""Return all possible configration locations.""" 

return [self.get_config()] 

 

def get_config_files(self, relpath, first=False, create=False): 

default = self.config if create else None 

return find_files(self.get_config_dirs(), relpath, first=first, default=default) 

 

def any_config_dir_exists(self): 

for path in self.get_config_dirs(): 

if os.path.exists(path): 

return path 

 

def install_config(self, source=None, relpath=None, mode=0o740): 

return self._install_type(self.get_config(), self.installer.config_mode, source=source, relpath=relpath, 

mode=mode) 

 

@property 

def data(self): 

return self.get_data() 

 

def get_data(self): 

"""Return the directory to store (shared) data files.""" 

raise NotImplementedError 

 

def get_data_dirs(self): 

return [self.get_data()] 

 

def get_data_files(self, relpath, first=False, create=False): 

default = self.data if create else None 

return find_files(self.get_data_dirs(), relpath, first=first, default=default) 

 

def any_data_dir_exists(self): 

for path in self.get_data_dirs(): 

if os.path.exists(path): 

return path 

 

def install_data(self, source=None, relpath=None, mode=None): 

return self._install_type(self.get_data(), self.installer.data_mode, source=source, relpath=relpath, mode=mode) 

 

@property 

def cache(self): 

return self.get_cache() 

 

def get_cache(self): 

"""Return the directory to store cache files.""" 

raise NotImplementedError 

 

def install_cache(self, source=None, relpath=None, mode=None): 

return self._install_type(self.get_cache(), self.installer.cache_mode, source=source, relpath=relpath, 

mode=mode) 

 

@property 

def var(self): 

return self.get_var() 

 

def get_var(self): 

"""Return the directory to store variable files.""" 

raise NotImplementedError 

 

def install_var(self, source=None, relpath=None, mode=None): 

return self._install_type(self.get_var(), self.installer.var_mode, source=source, relpath=relpath, mode=mode) 

 

@property 

def run(self): 

return self.get_run() 

 

def get_run(self): 

"""Return the directory to store runtime files.""" 

raise NotImplementedError 

 

def install_run(self, source=None, relpath=None, mode=None): 

return self._install_type(self.get_run(), self.installer.run_mode, source=source, relpath=relpath, mode=mode) 

 

@property 

def log(self): 

return self.get_log() 

 

def get_log(self): 

"""Return the directory to store log files.""" 

raise NotImplementedError 

 

def install_log(self, source=None, relpath=None, mode=None): 

return self._install_type(self.get_log(), self.installer.log_mode, source=source, relpath=relpath, mode=mode) 

 

 

def get_gid_by_name(name): 

try: 

gr = grp.getgrnam(name) 

except KeyError: 

return 

return gr.gr_gid 

 

 

def clean_group(answer): 

gid = get_gid_by_name(answer) 

if gid is None: 

sys.stdout.write('No such group: {}, Create it first or choose another.\n'.format(answer)) 

sys.stdout.flush() 

return gid 

 

 

class FHS(DirectorySpecification): 

name = 'FHS' 

description = '/etc, /usr, /var' 

 

requires_root = True 

 

def __init__(self, force=False, chown_group=None, support_hier=True): 

self.chown_group = chown_group 

self.support_hier = support_hier 

super(FHS, self).__init__(force=force) 

 

self.gid = None 

self.is_root = os.geteuid() == 0 

 

def is_available_for_installation(self): 

return self.is_root 

 

def get_gid(self, group): 

gid = get_gid_by_name(group) 

if gid is not None: 

return gid 

 

default = self.installer.project_name.lower() 

interface = self.installer.get_interface() 

return interface.ask_text('The group to own the directories', 

default=default, 

timeout_default=default, 

clean_callback=clean_group) 

 

def init_install(self): 

if self.chown_group: 

if self.chown_group is True: 

group = self.installer.project_name 

else: 

group = self.chown_group 

self.gid = self.get_gid(group) 

 

def _install_type(self, type_dir, type_dir_mode, source=None, relpath=None, mode=None): 

new_type_dir = not os.path.exists(type_dir) 

destination = super(FHS, self)._install_type(type_dir, type_dir_mode, 

source=source, relpath=relpath, mode=mode) 

uid = os.geteuid() 

if self.gid is not None: 

if new_type_dir: 

os.chown(type_dir, uid, self.gid) 

if destination is not None: 

os.chown(destination, uid, self.gid) 

return destination 

 

def get_config(self): 

return os.path.join('/etc', self.installer.project_name) 

 

def get_data(self): 

return os.path.join('/usr', 'local', 'share', self.installer.project_name) 

 

def get_data_dirs(self): 

dirs = super(FHS, self).get_data_dirs() 

dirs.append(os.path.join('/usr', 'share', self.installer.project_name)) 

return dirs 

 

def get_cache(self): 

return os.path.join('/var', 'cache', self.installer.project_name) 

 

def get_var(self): 

return os.path.join('/var', 'lib', self.installer.project_name) 

 

def get_run(self): 

if self.support_hier: 

return os.path.join('/var', 'run', self.installer.project_name) 

return os.path.join('/run', self.installer.project_name) 

 

def get_log(self): 

return os.path.join('/var', 'log', self.installer.project_name) 

 

 

class XDG(DirectorySpecification): 

name = 'XDG' 

description = 'XDG_* environment variables. E.g. ~/.config, ~/.cache, ~/.local/share' 

 

def get_config(self): 

home = os.environ.get('XDG_CONFIG_HOME', os.path.join(os.path.expanduser('~'), '.config')) 

return os.path.join(home, self.installer.project_name) 

 

def get_config_dirs(self): 

dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg').split(':') 

return super(XDG, self).get_config_dirs() + [os.path.join(d, self.installer.project_name) for d in dirs] 

 

def get_data(self): 

home = os.environ.get('XDG_DATA_HOME', os.path.join(os.path.expanduser('~'), '.local', 'share')) 

return os.path.join(home, self.installer.project_name) 

 

def get_data_dirs(self): 

dirs = os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':') 

return super(XDG, self).get_data_dirs() + [os.path.join(d, self.installer.project_name) for d in dirs] 

 

def get_cache(self): 

home = os.environ.get('XDG_CACHE_HOME', os.path.join(os.path.expanduser('~'), '.cache')) 

return os.path.join(home, self.installer.project_name) 

 

def get_var(self): 

return self.get_config() 

 

def install_var(self, *args, **kwargs): 

return self.install_config(*args, **kwargs) 

 

def get_run(self): 

runtime_home = os.environ.get('XDG_RUNTIME_HOME', None) 

if runtime_home is None: 

runtime_home = os.path.join(tempfile.gettempdir(), 'run') 

sys.stderr.write('WARNING: XDG_RUNTIME_HOME is not set! Using "{}" instead.\n'.format(runtime_home)) 

sys.stderr.flush() 

 

return os.path.join(runtime_home, self.installer.project_name) 

 

def get_log(self): 

return self.get_cache() 

 

def install_log(self, *args, **kwargs): 

return self.install_cache(*args, **kwargs) 

 

 

class DevDir(DirectorySpecification): 

name = 'dev' 

description = 'Single directory for development' 

 

def __init__(self, path, hidden=True): 

self.hidden = hidden 

 

if os.path.isfile(path): 

dirname = os.path.dirname(path) 

path = os.path.join(dirname, 'dev') 

self.path = path 

 

def get_config(self): 

return self.path 

 

def install_config(self, *args, **kwargs): 

return self.install_data(*args, **kwargs) 

 

def get_data(self): 

return self.path 

 

def get_cache(self): 

return self.path 

 

def install_cache(self, *args, **kwargs): 

return self.install_data(*args, **kwargs) 

 

def get_var(self): 

return self.path 

 

def install_var(self, *args, **kwargs): 

return self.install_data(*args, **kwargs) 

 

def get_run(self): 

return self.path 

 

def install_run(self, *args, **kwargs): 

return self.install_data(*args, **kwargs) 

 

def get_log(self): 

return self.path 

 

def install_log(self, *args, **kwargs): 

return self.install_data(*args, **kwargs) 

 

 

def find_files(dirs, relpath, first=False, default=None): 

paths = [] 

for directory in dirs: 

path = os.path.join(directory, relpath) 

if not os.path.exists(path): 

continue 

paths.append(path) 

if first: 

try: 

return paths[0] 

except IndexError: 

return default 

if not paths and default is not None: 

return [default] 

return paths