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

# coding=utf-8 

""" 

Collections of tools to build EMIZ 

""" 

import importlib 

import os 

import re 

import shlex 

import shutil 

import subprocess 

import sys 

import typing 

import webbrowser 

from contextlib import contextmanager 

from json import loads 

 

import click 

from pkg_resources import DistributionNotFound, get_distribution 

 

# noinspection SpellCheckingInspection 

PYINSTALLER_NEEDED_VERSION = '3.3.dev0+g2fcbe0f' 

 

 

@contextmanager 

def cd(path): 

""" 

Context to temporarily change the working directory 

 

Args: 

path: working directory to cd into 

""" 

old_dir = os.getcwd() 

os.chdir(path) 

try: 

yield 

finally: 

os.chdir(old_dir) 

 

 

def repo_is_dirty() -> bool: 

""" 

Checks if the current repository contains uncommitted or untracked changes 

 

Returns: true if the repository is clean 

""" 

try: 

subprocess.check_call(['git', 'diff', '--quiet', '--cached', 'HEAD', '--']) 

except subprocess.CalledProcessError: 

return True 

 

 

def ensure_repo(): 

""" 

Makes sure the current working directory is EMIZ's Git repository. 

""" 

if not os.path.exists('.git') or not os.path.exists('emiz'): 

click.secho('emiz-build is meant to be ran in EMIZ Git repository.\n' 

'You can clone the repository by running:\n\n' 

'\tgit clone https://github.com/132nd-etcher/EMIZ.git\n\n' 

'Then cd into it and try again.', 

fg='red', err=True) 

exit(-1) 

 

 

def ensure_module(module_name: str): 

""" 

Makes sure that a module is importable. 

 

In case the module cannot be found, print an error and exit. 

 

Args: 

module_name: name of the module to look for 

""" 

try: 

importlib.import_module(module_name) 

except ModuleNotFoundError: 

click.secho( 

f'Module not found: {module_name}\n' 

f'Install it manually with: "pip install {module_name}"\n' 

f'Or install all dependencies with: "pip install -r requirements-dev.txt"', 

fg='red', err=True) 

exit(-1) 

 

 

def find_executable(executable: str, path: str = None) -> typing.Union[str, None]: # noqa: C901 

# noinspection SpellCheckingInspection 

""" 

https://gist.github.com/4368898 

 

Public domain code by anatoly techtonik <techtonik@gmail.com> 

 

Programmatic equivalent to Linux `which` and Windows `where` 

 

Find if ´executable´ can be run. Looks for it in 'path' 

(string that lists directories separated by 'os.pathsep'; 

defaults to os.environ['PATH']). Checks for all executable 

extensions. Returns full path or None if no command is found. 

 

Args: 

executable: executable name to look for 

path: root path to examine (defaults to system PATH) 

 

""" 

 

if not executable.endswith('.exe'): 

executable = f'{executable}.exe' 

 

if executable in find_executable.known_executables: # type: ignore 

return find_executable.known_executables[executable] # type: ignore 

 

click.secho(f'looking for executable: {executable}', fg='green', nl=False) 

 

if path is None: 

path = os.environ['PATH'] 

paths = [os.path.abspath(os.path.join(sys.exec_prefix, 'Scripts'))] + path.split(os.pathsep) 

if os.path.isfile(executable): 

executable_path = os.path.abspath(executable) 

else: 

for path_ in paths: 

executable_path = os.path.join(path_, executable) 

if os.path.isfile(executable_path): 

break 

else: 

click.secho(f' -> not found', fg='red', err=True) 

return None 

 

find_executable.known_executables[executable] = executable_path # type: ignore 

click.secho(f' -> {click.format_filename(executable_path)}', fg='green') 

return executable_path 

 

 

find_executable.known_executables = {} # type: ignore 

 

 

def do_ex(ctx: click.Context, cmd: typing.List[str], cwd: str = '.') -> typing.Tuple[str, str, int]: 

""" 

Executes a given command 

 

Args: 

ctx: Click context 

cmd: command to run 

cwd: working directory (defaults to ".") 

 

Returns: stdout, stderr, exit_code 

 

""" 

 

def _popen_pipes(cmd_, cwd_): 

def _always_strings(env_dict): 

""" 

On Windows and Python 2, environment dictionaries must be strings 

and not unicode. 

""" 

env_dict.update( 

(key, str(value)) 

for (key, value) in env_dict.items() 

) 

return env_dict 

 

return subprocess.Popen( 

cmd_, 

stdout=subprocess.PIPE, 

stderr=subprocess.PIPE, 

cwd=str(cwd_), 

env=_always_strings( 

dict( 

os.environ, 

# try to disable i18n 

LC_ALL='C', 

LANGUAGE='', 

HGPLAIN='1', 

) 

) 

) 

 

def _ensure_stripped_str(_, str_or_bytes): 

if isinstance(str_or_bytes, str): 

return '\n'.join(str_or_bytes.strip().splitlines()) 

else: 

return '\n'.join(str_or_bytes.decode('utf-8', 'surogate_escape').strip().splitlines()) 

 

exe = find_executable(cmd.pop(0)) 

if not exe: 

exit(-1) 

cmd.insert(0, exe) 

click.secho(f'{cmd}', nl=False, fg='magenta') 

p = _popen_pipes(cmd, cwd) 

out, err = p.communicate() 

click.secho(f' -> {p.returncode}', fg='magenta') 

return _ensure_stripped_str(ctx, out), _ensure_stripped_str(ctx, err), p.returncode 

 

 

def do( 

ctx: click.Context, 

cmd: typing.List[str], 

cwd: str = '.', 

mute_stdout: bool = False, 

mute_stderr: bool = False, 

# @formatter:off 

filter_output: typing.Union[None, typing.Iterable[str]]=None 

# @formatter:on 

) -> str: 

""" 

Executes a command and returns the result 

 

Args: 

ctx: click context 

cmd: command to execute 

cwd: working directory (defaults to ".") 

mute_stdout: if true, stdout will not be printed 

mute_stderr: if true, stderr will not be printed 

filter_output: gives a list of partial strings to filter out from the output (stdout or stderr) 

 

Returns: stdout 

""" 

 

def _filter_output(input_): 

 

def _filter_line(line): 

# noinspection PyTypeChecker 

for filter_str in filter_output: 

if filter_str in line: 

return False 

return True 

 

if filter_output is None: 

return input_ 

return '\n'.join(filter(_filter_line, input_.split('\n'))) 

 

if not isinstance(cmd, (list, tuple)): 

cmd = shlex.split(cmd) 

 

out, err, ret = do_ex(ctx, cmd, cwd) 

if out and not mute_stdout: 

click.secho(f'{_filter_output(out)}', fg='cyan') 

if err and not mute_stderr: 

click.secho(f'{_filter_output(err)}', fg='red') 

if ret: 

click.secho(f'command failed: {cmd}', err=True, fg='red') 

exit(ret) 

return out 

 

 

def get_gitversion() -> dict: 

""" 

Uses GitVersion (https://github.com/GitTools/GitVersion) to infer project's current version 

 

Returns Gitversion JSON output as a dict 

""" 

if os.environ.get('APPVEYOR'): 

exe = find_executable('gitversion', r'C:\ProgramData\chocolatey\bin') 

else: 

exe = find_executable('gitversion') 

if not exe: 

click.secho( 

'"gitversion.exe" not been found in your PATH.\n' 

'GitVersion is used to infer the current version from the Git repository.\n' 

'setuptools_scm plans on switching to using the Semver scheme in the future; when that happens, ' 

'I\'ll remove the dependency to GitVersion.\n' 

'In the meantime, GitVersion can be obtained via Chocolatey (recommended): ' 

'https://chocolatey.org/packages/GitVersion.Portable\n' 

'If you already have chocolatey installed, you can simply run the following command (as admin):\n\n' 

'\t\t"choco install gitversion.portable -pre -y"\n\n' 

'If you\'re not comfortable using the command line, there is a GUI tool for Chocolatey available at:\n\n' 

'\t\thttps://github.com/chocolatey/ChocolateyGUI/releases\n\n' 

'Or you can install directly from :\n\n' 

'\t\thttps://github.com/GitTools/GitVersion/releases', 

err=True, 

) 

exit(-1) 

return loads(subprocess.getoutput([exe]).rstrip()) 

 

 

def get_pep440_version(version: str) -> str: 

""" 

Converts a Semver to a PEP440 version 

 

Args: 

version: valid Semver string 

 

Returns: valid PEP440 version 

""" 

import semantic_version 

 

convert_prereleases = { 

'alpha': 'a', 

'beta': 'b', 

'exp': 'rc', 

'patch': 'post', 

} 

 

semver = semantic_version.Version.coerce(version) 

version_str = f'{semver.major}.{semver.minor}.{semver.patch}' 

prerelease = semver.prerelease 

 

# Pre-release 

if prerelease: 

assert isinstance(prerelease, tuple) 

 

# Convert the pre-release tag to a valid PEP440 tag and strip it 

if prerelease[0] in convert_prereleases: 

version_str += convert_prereleases[prerelease[0]] 

prerelease = prerelease[1:] 

else: 

raise ValueError(f'unknown pre-release tag: {prerelease[0]}') 

 

# If there is a distance to the last tag, add a ".dev[distance]" suffix 

if re.match(r'[\d]+', prerelease[-1]): 

version_str += f'{prerelease[-1]}' 

# prerelease = prerelease[:-1] 

 

# Regular release 

# else: 

# version_str = f'{version_str.major}.{version_str.minor}.{version_str.patch}' 

 

# Add SemVer, Sha and last commit date to the build tag 

# local_version = re.sub(r'[^a-zA-Z0-9\.]', '.', __version__.get('FullSemVer')) 

# commit_date = re.sub(r'-0', '.', __version__.get('CommitDate')) 

# version += f'+{local_version}.{__version__.get("Sha")}.{commit_date}'.replace('-', '.') 

 

return version_str 

 

 

def _write_requirements(ctx: click.Context, packages_list, outfile, prefix_list=None): 

with open('temp', 'w') as source_file: 

source_file.write('\n'.join(packages_list)) 

packages, _, ret = do_ex( 

ctx, 

[ 

'pip-compile', 

'--index', 

'--upgrade', 

'--annotate', 

'--no-header', 

'-n', 

'temp' 

] 

) 

os.remove('temp') 

with open(outfile, 'w') as req_file: 

if prefix_list: 

for prefix in prefix_list: 

req_file.write(f'{prefix}\n') 

for package in packages.splitlines(): 

req_file.write(f'{package}\n') 

 

 

def _install_pyinstaller(ctx: click.Context, force: bool = False): 

""" 

Installs pyinstaller package from a custom repository 

 

The latest official master branch of Pyinstaller does not work with the version of Python I'm using at this time 

 

Args: 

ctx: lick context (passed automatically by Click) 

force: uses "pip --upgrade" to force the installation of this specific version of PyInstaller 

""" 

repo = r'git+https://github.com/132nd-etcher/pyinstaller.git@develop#egg=pyinstaller==3.3.dev0+g2fcbe0f' 

if force: 

do(ctx, ['pip', 'install', '--upgrade', repo]) 

else: 

do(ctx, ['pip', 'install', repo]) 

 

 

def _get_version(ctx): 

try: 

return get_distribution('emiz').version 

except DistributionNotFound: 

return 'not installed' 

 

 

# noinspection PyUnusedLocal 

def _print_version(ctx: click.Context, param, value): 

if not value or ctx.resilient_parsing: 

return 

 

ensure_repo() 

 

click.secho(_get_version(ctx), fg='green') 

exit(0) 

 

 

# @click.group(invoke_without_command=True) 

@click.group(chain=True) 

@click.option('-v', '--version', 

is_flag=True, is_eager=True, expose_value=False, callback=_print_version, default=False, 

help='Print version and exit') 

@click.pass_context 

def cli(ctx): 

""" 

emiz-build is a tool that handles all the tasks to build a working EMIZ application 

 

This tool is installed as a setuptools entry point, which means it should be accessible from your terminal once EMIZ 

is installed in develop mode. 

 

Just activate your venv and type the following in whatever shell you fancy: 

""" 

ensure_repo() 

ctx.obj = { 

'version': _get_version(ctx) 

} 

click.secho(ctx.obj['version'], fg='green') 

 

# if ctx.invoked_subcommand is None: 

# Checks.safety(ctx) 

# Checks.flake8(ctx) 

# Checks.pytest(ctx) 

# # Checks.pylint() # TODO 

# # Checks.prospector() # TODO 

# HouseKeeping.compile_qt_resources(ctx) 

# HouseKeeping.write_changelog(ctx, commit=True) 

# HouseKeeping.write_requirements(ctx) 

# Make.install_pyinstaller(ctx) 

# Make.freeze(ctx) 

# Make.patch_exe(ctx) 

# Make.build_doc(ctx) 

 

 

@cli.command() 

@click.option('--prod/--no-prod', default=True, help='Whether or not to write "requirement.txt"') 

@click.option('--test/--no-test', default=True, help='Whether or not to write "requirement-test.txt"') 

@click.option('--dev/--no-dev', default=True, help='Whether or not to write "requirement-dev.txt"') 

@click.pass_context 

def reqs(ctx: click.Context, prod, test, dev): 

""" 

Write requirements files 

""" 

if not find_executable('pip-compile'): 

click.secho('Missing module "pip-tools".\n' 

'Install it manually with: "pip install pip-tools"\n' 

'Or install all dependencies with: "pip install -r requirements-dev.txt"', 

err=True, fg='red') 

exit(-1) 

if prod: 

sys.path.insert(0, os.path.abspath('.')) 

from setup import install_requires 

_write_requirements( 

ctx, 

packages_list=install_requires, 

outfile='requirements.txt' 

) 

sys.path.pop(0) 

if test: 

"""Writes requirements-test.txt""" 

from setup import test_requires 

_write_requirements( 

ctx, 

packages_list=test_requires, 

outfile='requirements-test.txt', 

prefix_list=['-r requirements.txt'] 

) 

if dev: 

"""Writes requirements-dev.txt""" 

from setup import dev_requires 

_write_requirements( 

ctx, 

packages_list=dev_requires, 

outfile='requirements-dev.txt', 

prefix_list=['-r requirements.txt', '-r requirements-test.txt'] 

) 

 

 

@cli.command() 

@click.pass_context 

def chglog(ctx): 

""" 

Writes the changelog 

 

Returns: 

bool: returns true if changes have been committed to the repository 

""" 

ensure_module('gitchangelog') 

find_executable('git') 

""" 

Write the changelog using "gitchangelog" (https://github.com/vaab/gitchangelog) 

""" 

changelog = do(ctx, ['gitchangelog', '0.4.1..HEAD'], mute_stdout=True) 

with open('CHANGELOG.rst', mode='w') as f: 

f.write(re.sub(r'(\s*\r\n){2,}', '\r\n', changelog)) 

 

 

@cli.command() 

@click.pass_context 

def pytest(ctx): 

""" 

Runs Pytest (https://docs.pytest.org/en/latest/) 

""" 

ensure_module('pytest') 

do(ctx, ['pytest']) 

 

 

@cli.command() 

@click.pass_context 

def flake8(ctx): 

""" 

Runs Flake8 (http://flake8.pycqa.org/en/latest/) 

""" 

ensure_module('flake8') 

do(ctx, ['flake8']) 

 

 

@cli.command() 

@click.pass_context 

def prospector(ctx): 

""" 

Runs Landscape.io's Prospector (https://github.com/landscapeio/prospector) 

 

This includes flake8 & Pylint 

""" 

ensure_module('prospector') 

do(ctx, ['prospector']) 

 

 

@cli.command() 

@click.pass_context 

@click.argument('src', type=click.Path(exists=True), default='emiz') 

@click.option('-r', '--reports', is_flag=True, help='Display full report') 

@click.option('-f', '--format', 'format_', 

type=click.Choice(['text', 'parseable', 'colorized', 'json']), default='colorized') 

def pylint(ctx, src, reports, format_): 

""" 

Analyze a given python SRC (module or package) with Pylint (SRC must exist) 

 

Default module: "./emiz" 

""" 

ensure_module('pylint') 

cmd = ['pylint', src, f'--output-format={format_}'] 

if reports: 

cmd.append('--reports=y') 

do(ctx, cmd) 

 

 

@cli.command() 

@click.pass_context 

def safety(ctx): 

""" 

Runs Pyup's Safety tool (https://pyup.io/safety/) 

""" 

ensure_module('safety') 

do(ctx, ['safety', 'check', '--bare']) 

 

 

@cli.command() 

@click.option('-s', '--show', is_flag=True, help='Show the doc in browser') 

@click.option('-c', '--clean', is_flag=True, help='Clean build') 

@click.option('-p', '--publish', is_flag=True, help='Upload doc') 

@click.pass_context 

def doc(ctx, show, clean, publish): 

""" 

Builds the documentation using Sphinx (http://www.sphinx-doc.org/en/stable) 

""" 

if clean and os.path.exists('./doc/html'): 

shutil.rmtree('./doc/html') 

if os.path.exists('./doc/api'): 

shutil.rmtree('./doc/api') 

do(ctx, [ 

'sphinx-apidoc', 

'emiz', 

'-o', 'doc/api', 

'-H', 'EMIZ API', 

'-A', '132nd-etcher', 

'-V', f'{ctx.obj["semver"]}\n({ctx.obj["pep440"]})', 

# '-P', 

'-f', 

]) 

do(ctx, [ 

'sphinx-build', 

'-b', 

'html', 

'doc', 

'doc/html' 

]) 

if show: 

webbrowser.open_new_tab(f'file://{os.path.abspath("./doc/html/index.html")}') 

if publish: 

output_filter = [ 

'warning: LF will be replaced by CRLF', 

'The file will have its original line endings', 

'Checking out files:' 

] 

if not os.path.exists('./emiz-doc'): 

do(ctx, ['git', 'clone', r'https://github.com/132nd-etcher/emiz-doc.git'], filter_output=output_filter) 

with cd('./emiz-doc'): 

do(ctx, ['git', 'pull']) 

if os.path.exists('./docs'): 

shutil.rmtree('./docs') 

shutil.copytree('../doc/html', './docs') 

do(ctx, ['git', 'add', '.'], filter_output=output_filter) 

do(ctx, ['git', 'commit', '-m', 'automated doc build'], filter_output=output_filter) 

do(ctx, ['git', 'push'], filter_output=output_filter) 

 

 

@cli.command() 

@click.pass_context 

def pre_push(ctx): 

""" 

This is meant to be used as a Git pre-push hook 

""" 

ctx.invoke(reqs) 

ctx.invoke(chglog) 

ctx.invoke(chglog) 

ctx.invoke(flake8) 

ctx.invoke(safety) 

if repo_is_dirty(): 

click.secho('Repository is dirty', err=True, fg='red') 

exit(-1) 

 

 

@cli.command() 

@click.pass_context 

def test_local_build(ctx): 

""" 

This is meant to be used as a Git pre-push hook 

""" 

ctx.invoke(flake8) 

ctx.invoke(pytest)