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

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

#!/usr/bin/python3 

 

""" 

PyLucid Boot Admin 

~~~~~~~~~~~~~~~~~~ 

 

A interactive shell for booting PyLucid. 

 

Note: 

- This file is "self contained". 

- It used **only** stuff from Python lib. 

- So it's "run able" on a bare python 3 installation 

- On debian / ubuntu the 'python3-venv' package is needed! 

 

usage, e.g.: 

 

$ wget https://raw.githubusercontent.com/jedie/PyLucid/pylucid_v3/pylucid/pylucid_boot.py 

$ python3 pylucid_boot.py 

 

pylucid_boot.py> boot ~/PyLucid_env 

 

:created: 08.02.2018 by Jens Diemer, www.jensdiemer.de 

:copyleft: 2018 by the PyLucid team, see AUTHORS for more details. 

:license: GNU General Public License v3 or later (GPLv3+), see LICENSE for more details. 

""" 

 

import sys # isort:skip 

28 ↛ 29line 28 didn't jump to line 29, because the condition on line 28 was never trueif sys.version_info < (3, 5): # isort:skip 

print("\nERROR: Python 3.5 or greater is required!") 

print("(Current Python Verison is %s)\n" % sys.version.split(" ",1)[0]) 

sys.exit(101) 

 

import cmd 

import logging 

import os 

import subprocess 

import traceback 

from pathlib import Path 

 

try: 

import venv 

except ImportError as err: 

# e.g.: debian / ubuntu doesn't have venv installed, isn't it?!? 

print("\nERROR: 'venv' not available: %s (Maybe 'python3-venv' package not installed?!?)" % err) 

 

try: 

import ensurepip 

except ImportError as err: 

# e.g.: debian / ubuntu doesn't have venv installed, isn't it?!? 

print("\nERROR: 'ensurepip' not available: %s (Maybe 'python3-venv' package not installed?!?)" % err) 

 

 

__version__ = "0.4.0" 

 

 

log = logging.getLogger(__name__) 

 

# Note: 

# on 'master' branch: '--pre' flag must not be set: So the last release on PyPi will be installed. 

# on 'develop' branch: set the '--pre' flag and publish 'preview' versions on PyPi. 

# 

DEVELOPER_INSTALL=["-e", "git+https://github.com/jedie/PyLucid.git@master#egg=pylucid"] 

NORMAL_INSTALL=[ 

# "--pre", # https://pip.pypa.io/en/stable/reference/pip_install/#pre-release-versions 

"pylucid" 

] 

 

SELF_FILE_PATH=Path(__file__) # .../pylucid/pylucid_boot.py 

 

SUBPROCESS_TIMEOUT=60 # default timeout for subprocess calls 

 

 

 

class Colorizer: 

""" 

Borrowed from Django: 

https://github.com/django/django/blob/master/django/utils/termcolors.py 

 

>>> c = Colorizer() 

>>> c.supports_colors() 

True 

>>> c.color_support = True 

>>> c.colorize('no color') 

'no color' 

>>> c.colorize('bold', opts=("bold",)) 

'\\x1b[1mbold\\x1b[0m' 

>>> c.colorize("colors!", foreground="red", background="blue", opts=("bold", "blink")) 

'\\x1b[31;44;1;5mcolors!\\x1b[0m' 

""" 

def __init__(self, stdout=sys.stdout, stderr=sys.stderr): 

self._stdout = stdout 

self._stderr = stderr 

 

color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') 

 

self._foreground_colors = dict([(color_names[x], '3%s' % x) for x in range(8)]) 

self._background_colors = dict([(color_names[x], '4%s' % x) for x in range(8)]) 

self._opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} 

 

self.color_support = self._supports_colors() 

 

def _supports_colors(self): 

103 ↛ 104line 103 didn't jump to line 104, because the condition on line 103 was never true if sys.platform in ('win32', 'Pocket PC'): 

return False 

 

# isatty is not always implemented! 

107 ↛ 108line 107 didn't jump to line 108, because the condition on line 107 was never true if hasattr(self._stdout, 'isatty') and self._stdout.isatty(): 

return True 

else: 

return False 

 

def colorize(self, text, foreground=None, background=None, opts=()): 

""" 

Returns your text, enclosed in ANSI graphics codes. 

""" 

116 ↛ 119line 116 didn't jump to line 119, because the condition on line 116 was never false if not self.color_support: 

return text 

 

code_list = [] 

 

if foreground: 

code_list.append(self._foreground_colors[foreground]) 

if background: 

code_list.append(self._background_colors[background]) 

 

for option in opts: 

code_list.append(self._opt_dict[option]) 

 

if not code_list: 

return text 

 

return "\x1b[%sm%s\x1b[0m" % (';'.join(code_list), text) 

 

def _out_err(self, func, *args, flush=False, **kwargs): 

text = self.colorize(*args, **kwargs) 

func.write("%s\n" % text) 

if flush: 

func.flush() 

 

def out(self, *args, flush=False, **kwargs): 

""" colorize and print to stdout """ 

self._out_err(self._stdout, *args, flush=flush, **kwargs) 

 

def err(self, *args, flush=False, **kwargs): 

""" colorize and print to stderr """ 

self._out_err(self._stderr, *args, flush=flush, **kwargs) 

 

def demo(self): 

for background_color in sorted(self._background_colors.keys()): 

line = ["%10s:" % background_color] 

for foreground_color in sorted(self._foreground_colors.keys()): 

line.append( 

self.colorize(" %s " % foreground_color, 

foreground=foreground_color, background=background_color 

) 

) 

 

for opt in sorted(self._opt_dict.keys()): 

line.append( 

self.colorize(" %s " % opt, 

background=background_color, opts=(opt,) 

) 

) 

 

self.out("".join(line), background=background_color) 

 

 

colorizer = Colorizer() 

# colorizer.demo() 

 

 

class VerboseSubprocess: 

""" 

Verbose Subprocess 

""" 

def __init__(self, *popenargs, env_updates=None, timeout=SUBPROCESS_TIMEOUT, universal_newlines=True, stderr=subprocess.STDOUT, **kwargs): 

""" 

:param popenargs: 'args' for subprocess.Popen() 

:param env_updates: dict to overwrite os.environ. 

:param timeout: pass to subprocess.Popen() 

:param kwargs: pass to subprocess.Popen() 

""" 

self.popenargs = popenargs 

self.kwargs = kwargs 

 

self.kwargs["timeout"] = timeout 

self.kwargs["universal_newlines"] = universal_newlines 

self.kwargs["stderr"] = stderr 

 

self.args_str = " ".join([str(x) for x in self.popenargs]) 

 

self.env_updates = env_updates 

193 ↛ 194line 193 didn't jump to line 194, because the condition on line 193 was never true if self.env_updates is not None: 

env=os.environ.copy() 

env.update(env_updates) 

self.kwargs["env"] = env 

 

def print_call_info(self): 

print("") 

print("_"*79) 

 

kwargs_txt=[] 

for key, value in self.kwargs.items(): 

if key == "env": 

continue 

key = colorizer.colorize(key, foreground="magenta", opts=("bold",)) 

value = colorizer.colorize(value, foreground="green", opts=("bold",)) 

kwargs_txt.append("%s=%s" % (key, value)) 

 

txt = "Call: '{args}' with: {kwargs}".format( 

args=colorizer.colorize(self.args_str, foreground="cyan", opts=("bold",)), 

kwargs=", ".join(kwargs_txt) 

) 

 

215 ↛ 216line 215 didn't jump to line 216, because the condition on line 215 was never true if self.env_updates is not None: 

txt += colorizer.colorize(" env:", foreground="magenta", opts=("bold",)) 

txt += colorizer.colorize(repr(self.env_updates), opts=("bold",)) 

 

print(txt) 

print("", flush=True) 

 

def print_exit_code(self, exit_code): 

txt = "\nExit code %r from %r\n" % (exit_code, self.args_str) 

224 ↛ 225line 224 didn't jump to line 225, because the condition on line 224 was never true if exit_code: 

colorizer.err(txt, foreground="red", flush=True) 

else: 

colorizer.out(txt, foreground="green", flush=True) 

 

def verbose_call(self, check=True): 

""" 

run subprocess.call() 

 

:param check: if True and subprocess exit_code !=0: sys.exit(exit_code) after run. 

:return: process exit code 

""" 

self.print_call_info() 

 

try: 

exit_code = subprocess.call(self.popenargs, **self.kwargs) 

except KeyboardInterrupt: 

print("\nExit %r\n" % self.args_str, flush=True) 

exit_code=None # good idea?!? 

 

sys.stderr.flush() 

 

self.print_exit_code(exit_code) 

247 ↛ 248line 247 didn't jump to line 248, because the condition on line 247 was never true if check and exit_code: 

sys.exit(exit_code) 

 

return exit_code 

 

def verbose_output(self, check=True): 

""" 

run subprocess.check_output() 

 

:param check: if True and subprocess exit_code !=0: sys.exit(exit_code) after run. 

:return: process output 

""" 

self.print_call_info() 

 

try: 

return subprocess.check_output(self.popenargs, **self.kwargs) 

except subprocess.CalledProcessError as err: 

print("\n%s" % err) 

265 ↛ 266line 265 didn't jump to line 266, because the condition on line 265 was never true if check: 

sys.exit(err.returncode) 

raise 

 

 

def display_errors(func): 

def wrapped(*args, **kwargs): 

try: 

return func(*args, **kwargs) 

except Exception as err: 

traceback.print_exc(file=sys.stderr) 

return "%s: %s" % (err.__class__.__name__, err) 

 

return wrapped 

 

 

class Cmd2(cmd.Cmd): 

""" 

Enhanced version of 'Cmd' class: 

- command alias 

- methods can be called directly from commandline: e.g.: ./foobar.py --help 

- Display 

""" 

own_filename = SELF_FILE_PATH.name # Path(__file__).name ;) 

version = __version__ 

 

command_alias = { # used in self.precmd() 

"q": "quit", "EOF": "quit", "exit": "quit", 

"": "help", # Just hit ENTER -> help 

"--help": "help", "-h": "help", "-?": "help", 

} 

 

unknown_command="*** Unknown command: %r ***\n" 

 

# Will be append to 'doc_leader' in self.do_help(): 

complete_hint="\nUse <{key}> to command completion.\n" 

missing_complete="\n(Sorry, no command completion available.)\n" # if 'readline' not available 

 

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

super().__init__(*args, **kwargs) 

 

intro_line = '{filename} shell v{version}'.format( 

filename=self.own_filename, 

version=self.version 

) 

intro_line = colorizer.colorize(intro_line, foreground="blue", background="black", opts=("bold",)) 

 

self.intro = ( 

'\n{intro_line}\n' 

'Type help or ? to list commands.\n' 

).format(intro_line=intro_line) 

 

self.prompt = colorizer.colorize(self.own_filename, foreground="cyan") 

self.prompt += colorizer.colorize("> ", opts=("bold",)) 

 

self.doc_header = "Available commands (type help <topic>):\n" 

self.doc_leader = ( 

"\nHint: All commands can be called directly from commandline.\n" 

"e.g.: $ ./{filename} help\n" 

).format( 

filename=self.own_filename, 

) 

 

# e.g.: $ pylucid_admin.py boot /tmp/PyLucid-env -> run self.do_boot("/tmp/PyLucid-env") on startup 

args = sys.argv[1:] 

330 ↛ exitline 330 didn't return from function '__init__', because the condition on line 330 was never false if args: 

self.cmdqueue = [" ".join(args)] 

 

def default(self, line): 

""" Called on an input line when the command prefix is not recognized. """ 

colorizer.err(self.unknown_command % line, foreground="red") 

 

@display_errors 

def _complete_list(self, items, text, line, begidx, endidx): 

if text: 

return [x for x in items if x.startswith(text)] 

else: 

return items 

 

@display_errors 

def _complete_path(self, text, line, begidx, endidx): 

""" 

complete a command argument with a existing path 

 

usage e.g.: 

class FooCmd(Cmd2): 

def complete_foobar(self, text, line, begidx, endidx): 

return self._complete_path(text, line, begidx, endidx) 

 

def do_foobar(self, path): # 'path' is type string! 

print("path:", path) 

""" 

try: 

destination = line.split(" ", 1)[1] 

except IndexError: 

destination = "." 

 

if destination=="~": 

return [os.sep] 

 

destination = Path(destination).expanduser().resolve() 

 

if not destination.is_dir(): 

destination = destination.parent.resolve() 

 

if destination.is_dir(): 

complete_list = [x.stem + os.sep for x in destination.iterdir() if x.is_dir()] 

if text: 

if text in complete_list: 

return [text + os.sep] 

 

complete_list = [x for x in complete_list if x.startswith(text)] 

else: 

complete_list = [] 

 

return complete_list 

 

def get_doc_line(self, command): 

""" 

return the first line of the DocString. 

If no DocString: return None 

""" 

assert command.startswith("do_") 

doc=getattr(self, command, None).__doc__ 

if doc is not None: 

doc = doc.strip().split("\n",1)[0] 

return doc 

 

_complete_hint_added=False 

def do_help(self, arg): 

""" 

List available commands with "help" or detailed help with "help cmd". 

""" 

398 ↛ 400line 398 didn't jump to line 400, because the condition on line 398 was never true if arg: 

# Help for one command 

return super().do_help(arg) 

 

# List available commands: 

 

self.stdout.write("%s\n" % self.doc_leader) 

self.stdout.write("%s\n" % self.doc_header) 

 

commands = [name for name in self.get_names() if name.startswith("do_")] 

commands.sort() 

max_length = max([len(name) for name in commands]) 

 

for command in commands: 

doc_line = self.get_doc_line(command) or "(Undocumented command)" 

 

command = command[3:] # remove "do_" 

 

command = "{cmd:{width}}".format(cmd=command, width=max_length) 

command = colorizer.colorize(command, opts=("bold",)) 

 

self.stdout.write(" {cmd} - {doc}\n".format( 

cmd=command, 

doc=doc_line 

)) 

 

self.stdout.write("\n") 

 

def do_quit(self, arg): 

"Exit this interactiv shell" 

print("\n\nbye") 

return True 

 

def precmd(self, line): 

""" 

1. Apply alias list 

2. print first DocString line (if exists), before start the command 

""" 

try: 

line=self.command_alias[line] 

except KeyError: 

pass 

 

cmd = line.split(" ",1)[0] 

doc_line = self.get_doc_line("do_%s" % cmd) 

if doc_line: 

colorizer.out("\n\n *** %s ***\n" % doc_line, background="cyan", opts=("bold",)) 

 

return line 

 

def postcmd(self, stop, line): 

# stop if we are called with commandline arguments 

450 ↛ 452line 450 didn't jump to line 452, because the condition on line 450 was never false if len(sys.argv)>1: 

stop = True 

return stop 

 

 

class PyLucidEnvBuilder(venv.EnvBuilder): 

verbose = True 

 

def __init__(self, requirements): 

super().__init__(with_pip=True) 

self.requirements = requirements 

 

def ensure_directories(self, env_dir): 

print(" * Create the directories for the environment.") 

return super().ensure_directories(env_dir) 

 

def create_configuration(self, context): 

print(" * Create 'pyvenv.cfg' configuration file.") 

return super().create_configuration(context) 

 

def setup_python(self, context): 

print(" * Set up a Python executable in the environment.") 

return super().setup_python(context) 

 

def _setup_pip(self, context): 

print(" * Installs or upgrades pip in a virtual environment.") 

return super()._setup_pip(context) 

 

def setup_scripts(self, context): 

print(" * Set up scripts into the created environment.") 

return super().setup_scripts(context) 

 

def post_setup(self, context): 

""" 

Set up any packages which need to be pre-installed into the 

virtual environment being created. 

 

:param context: The information for the virtual environment 

creation request being processed. 

""" 

print(" * post-setup modification") 

 

def call_new_python(*args, **kwargs): 

""" 

Do the same as bin/activate so that <args> runs in a "activated" virtualenv. 

""" 

kwargs.update({ 

"env_updates": { 

"VIRTUAL_ENV": context.env_dir, 

"PATH": "%s:%s" % (context.bin_path, os.environ["PATH"]), 

} 

}) 

VerboseSubprocess(*args, **kwargs).verbose_call( 

check=True # sys.exit(return_code) if return_code != 0 

) 

 

call_new_python("pip", "install", "--upgrade", "pip") 

 

# Install PyLucid 

# in normal mode as package from PyPi 

# in dev. mode as editable from github 

call_new_python( 

"pip", "install", 

# "--verbose", 

*self.requirements 

) 

 

# Check if ".../bin/pylucid_admin" exists 

pylucid_admin_path = Path(context.bin_path, "pylucid_admin") 

if not pylucid_admin_path.is_file(): 

print("ERROR: pylucid_admin not found here: '%s'" % pylucid_admin_path) 

VerboseSubprocess("ls", "-la", str(context.bin_path)).verbose_call() 

sys.exit(-1) 

 

# Install all requirements by call 'pylucid_admin update_env' from installed PyLucid 

call_new_python("pylucid_admin", "update_env", timeout=240) # extended timeout for slow Travis ;) 

 

 

class PyLucidBootShell(Cmd2): 

 

#_________________________________________________________________________ 

# Normal user commands: 

 

def _resolve_path(self, path): 

return Path(path).expanduser().resolve() 

 

def complete_boot(self, text, line, begidx, endidx): 

# print("text: %r" % text) 

# print("line: %r" % line) 

return self._complete_path(text, line, begidx, endidx) 

 

def _parse_requirements(self, requirement_string): 

requirements = [] 

for line in requirement_string.splitlines(): 

line = line.strip() 

if line and not line.startswith("#"): 

 

line = line.split("# ", 1)[0] # Remove pip-compile comments e.g.: "... # via foo" 

line = line.rstrip() 

 

if line.startswith("-e"): # split editables 

requirements += line.split(" ") 

else: 

requirements.append(line) 

return requirements 

 

def _boot(self, destination, requirements): 

""" 

Create a PyLucid virtualenv and install requirements. 

""" 

destination = Path(destination).expanduser() 

561 ↛ 565line 561 didn't jump to line 565, because the condition on line 561 was never false if destination.exists(): 

self.stdout.write("\nERROR: Path '%s' already exists!\n" % destination) 

sys.exit(1) 

 

self.stdout.write("Create virtualenv: '%s'...\n\n" % destination) 

 

builder = PyLucidEnvBuilder(requirements) 

builder.create(str(destination)) 

 

self.stdout.write("\n") 

 

if not destination.is_dir(): 

self.stdout.write("ERROR: Creating virtualenv!\n") 

sys.exit(1) 

else: 

self.stdout.write("virtualenv created at: '%s'\n" % destination) 

 

def do_boot(self, destination): 

""" 

Bootstrap PyLucid virtualenv in "normal" mode. 

 

usage: 

> boot [path] 

 

Create a PyLucid virtualenv in the given [path]. 

Install packages via PyPi and read-only sources from github. 

 

The destination path must not exist yet! 

 

(used the requirements/normal_installation.txt) 

""" 

self._boot(destination, requirements=NORMAL_INSTALL) 

complete_boot = complete_boot 

 

def do_boot_developer(self, destination): 

""" 

Bootstrap PyLucid virtualenv in "developer" mode. 

All own projects installed as editables via github HTTPS (readonly) 

 

**Should be only used for developing/contributing. All others: Use normal 'boot' ;) ** 

 

usage: 

> boot_developer [path] 

 

Create a PyLucid virtualenv in the given [path]. 

Install packages via PyPi and read-only sources from github. 

 

The destination path must not exist yet! 

 

(used the requirements/developer_installation.txt) 

""" 

self._boot(destination, requirements=DEVELOPER_INSTALL) 

complete_boot_developer = complete_boot 

 

 

def main(): 

PyLucidBootShell().cmdloop() 

 

 

if __name__ == '__main__': 

main()