This commit is contained in:
Waylon Walker 2023-03-13 09:42:39 -05:00
commit 72672d6709
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
32 changed files with 1651 additions and 0 deletions

20
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,20 @@
name: Release
on:
workflow_dispatch:
push:
paths:
- "pyflybygen/**"
- "pyproject.toml"
env:
HATCH_INDEX_USER: __token__
HATCH_INDEX_AUTH: ${{ secrets.pypi_password }}
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: waylonwalker/hatch-action@v3
with:
before-command: "test-lint"
env:
GH_TOKEN: ${{ github.token }}

961
.gitignore vendored Normal file
View file

@ -0,0 +1,961 @@
# Created by https://www.toptal.com/developers/gitignore/api/vim,node,data,emacs,python,pycharm,executable,sublimetext,visualstudio,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=vim,node,data,emacs,python,pycharm,executable,sublimetext,visualstudio,visualstudiocode
### Data ###
*.csv
*.dat
*.efx
*.gbr
*.key
*.pps
*.ppt
*.pptx
*.sdf
*.tax2010
*.vcf
*.xml
### Emacs ###
# -*- mode: gitignore; -*-
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
# Org-mode
.org-id-locations
*_archive
# flymake-mode
*_flymake.*
# eshell files
/eshell/history
/eshell/lastdir
# elpa packages
/elpa/
# reftex files
*.rel
# AUCTeX auto folder
/auto/
# cask packages
.cask/
dist/
# Flycheck
flycheck_*.el
# server auth directory
/server/
# projectiles files
.projectile
# directory configuration
.dir-locals.el
# network security
/network-security.data
### Executable ###
*.app
*.bat
*.cgi
*.com
*.exe
*.gadget
*.jar
*.pif
*.vb
*.wsf
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
### PyCharm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### PyCharm Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml
# ruff
.ruff_cache/
### SublimeText ###
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
### Vim ###
# Swap
[._]*.s[a-v][a-z]
!*.svg # comment out if you don't need vector files
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# Session
Session.vim
Sessionx.vim
# Temporary
.netrwhist
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
*.code-workspace
# Local History for Visual Studio Code
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/vim,node,data,emacs,python,pycharm,executable,sublimetext,visualstudio,visualstudiocode

BIN
.markata.cache/000/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/001/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/002/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/003/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/004/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/005/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/006/cache.db Normal file

Binary file not shown.

BIN
.markata.cache/007/cache.db Normal file

Binary file not shown.

1
.markata.cache/phase.txt Normal file
View file

@ -0,0 +1 @@
configure

View file

@ -0,0 +1,11 @@
# Changes here will be overwritten by Copier; NEVER EDIT MANUALLY
_commit: e40d60d
_src_path: /home/waylon/git/pytool-template
author_github: waylonwalker
author_name: Waylon Walker
description: auto generate project specific pyflyby config
package_name: pyflybygen
package_title: Pyflybygen
package_title_input: pyflybygen
python_package: pyflybygen

3
CHANGELOG.md Normal file
View file

@ -0,0 +1,3 @@
## 0.0.0
init

9
LICENSE.txt Normal file
View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2023-present Waylon S. Walker <waylon@waylonwalker.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

23
README.md Normal file
View file

@ -0,0 +1,23 @@
# PyFlyByGen
Generates pyflyby configurations for your project based on existing imports.
[![PyPI - Version](https://img.shields.io/pypi/v/{{ package_name }}.svg)](https://pypi.org/project/{{ package_name }})
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/{{ package_name }}.svg)](https://pypi.org/project/{{ package_name }})
---
**Table of Contents**
- [Installation](#installation)
- [License](#license)
## Installation
```console
pip install pyflybygen
```
## License
`pyflybygen` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

4
pyflybygen/__about__.py Normal file
View file

@ -0,0 +1,4 @@
# SPDX-FileCopyrightText: 2023-present Waylon S. Walker <waylon@waylonwalker.com>
#
# SPDX-License-Identifier: MIT
__version__ = "0.0.0.dev1"

3
pyflybygen/__init__.py Normal file
View file

@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2023-present Waylon S. Walker <waylon@waylonwalker.com>
#
# SPDX-License-Identifier: MIT

View file

59
pyflybygen/cli/app.py Normal file
View file

@ -0,0 +1,59 @@
from pathlib import Path
import more_itertools
import typer
from pyflybygen.cli.common import verbose_callback
from pyflybygen.cli.config import config_app
from pyflybygen.cli.tui import tui_app
from pyflybygen.pyflybygen import get_imports
app = typer.Typer(
name="pyflybygen",
help="A rich terminal report for coveragepy.",
)
app.add_typer(config_app)
app.add_typer(tui_app)
def version_callback(value: bool) -> None:
"""Callback function to print the version of the pyflybygen package.
Args:
value (bool): Boolean value to determine if the version should be printed.
Raises:
typer.Exit: If the value is True, the version will be printed and the program will exit.
Example:
version_callback(True)
"""
if value:
from pyflybygen.__about__ import __version__
typer.echo(f"{__version__}")
raise typer.Exit()
@app.callback(invoke_without_command=True)
def main(
version: bool = typer.Option(
None,
"--version",
callback=version_callback,
is_eager=True,
),
verbose: bool = typer.Option(
False,
callback=verbose_callback,
help="show the log messages",
),
) -> None:
imports = more_itertools.flatten(
[get_imports(p.read_text()) for p in Path(".").glob("**/*.py")]
)
print("\n".join(set(imports)))
if __name__ == "__main__":
typer.run(main)

6
pyflybygen/cli/common.py Normal file
View file

@ -0,0 +1,6 @@
from pyflybygen.console import console
def verbose_callback(value: bool) -> None:
if value:
console.quiet = False

29
pyflybygen/cli/config.py Normal file
View file

@ -0,0 +1,29 @@
from rich.console import Console
import typer
from pyflybygen.cli.common import verbose_callback
from pyflybygen.config import config as configuration
config_app = typer.Typer()
@config_app.callback()
def config(
verbose: bool = typer.Option(
False,
callback=verbose_callback,
help="show the log messages",
),
):
"configuration cli"
@config_app.command()
def show(
verbose: bool = typer.Option(
False,
callback=verbose_callback,
help="show the log messages",
),
):
Console().print(configuration)

18
pyflybygen/cli/tui.py Normal file
View file

@ -0,0 +1,18 @@
import typer
from pyflybygen.cli.common import verbose_callback
from pyflybygen.tui.app import run_app
tui_app = typer.Typer()
@tui_app.callback(invoke_without_command=True)
def i(
verbose: bool = typer.Option(
False,
callback=verbose_callback,
help="show the log messages",
),
):
"interactive tui"
run_app()

3
pyflybygen/config.py Normal file
View file

@ -0,0 +1,3 @@
from pyflybygen.standard_config import load
config = load("pyflybygen")

4
pyflybygen/console.py Normal file
View file

@ -0,0 +1,4 @@
from rich.console import Console
console = Console()
console.quiet = True

53
pyflybygen/pyflybygen.py Normal file
View file

@ -0,0 +1,53 @@
from tree_sitter_languages import get_language, get_parser
class CapturePoint:
def __init__(self, node):
self.start_point = node[0].start_point[0]
self.end_point = node[0].end_point[0]
def __eq__(self, o):
return self.start_point == o.start_point and self.end_point == o.end_point
def __repr__(self):
return f"{self.start_point}:{self.end_point}"
def __hash__(self):
return hash(repr(self))
def get_imports(content):
language = get_language("python")
content = content
content_lines = content.split("\n")
parser = get_parser("python")
tree = parser.parse(content.encode())
wild_imports = set(
CapturePoint(n)
for n in language.query(
"(import_from_statement (wildcard_import) @wildcard) @import_wild"
).captures(tree.root_node)
)
import_froms = list(
set(
CapturePoint(n)
for n in language.query("(import_from_statement) @import_from").captures(
tree.root_node
)
)
- wild_imports
)
imports = list(
set(
CapturePoint(n)
for n in language.query("(import_statement) @import").captures(
tree.root_node
)
)
)
import_lines = [
(" ".join(content_lines[s.start_point : s.end_point + 1])).strip()
for s in imports + import_froms
]
return import_lines

View file

@ -0,0 +1,239 @@
"""Standard Config.
A module to load tooling config from a users project space.
Inspired from frustrations that some tools have a tool.ini, .tool.ini,
setup.cfg, or pyproject.toml. Some allow for global configs, some don't. Some
properly follow the users home directory, others end up in a weird temp
directory. Windows home directory is only more confusing. Some will even
respect the users `$XDG_HOME` directory.
This file is for any project that can be configured in plain text such as `ini`
or `toml` and not requiring a .py file. Just name your tool and let users put
config where it makes sense to them, no need to figure out resolution order.
## Usage:
``` python
from standard_config import load
# Retrieve any overrides from the user
overrides = {'setting': True}
config = load('my_tool', overrides)
```
## Resolution Order
* First global file with a tool key
* First local file with a tool key
* Environment variables prefixed with `TOOL`
* Overrides
### Tool Specific Ini files
Ini file formats must include a `<tool>` key.
``` ini
[my_tool]
setting = True
```
### pyproject.toml
Toml files must include a `tool.<tool>` key
``` toml
[tool.my_tool]
setting = True
```
### setup.cfg
setup.cfg files must include a `tool:<tool>` key
``` ini
[tool:my_tool]
setting = True
```
### global files to consider
* <home>/tool.ini
* <home>/.tool
* <home>/.tool.ini
* <home>/.config/tool.ini
* <home>/.config/.tool
* <home>/.config/.tool.ini
### local files to consider
* <project_home>/tool.ini
* <project_home>/.tool
* <project_home>/.tool.ini
* <project_home>/pyproject.toml
* <project_home>/setup.cfg
"""
import os
from pathlib import Path
from typing import Dict, List, Union
import anyconfig
# path_spec_type = List[Dict[str, Union[Path, str, List[str\}\}\}\}
path_spec_type = List
def _get_global_path_specs(tool: str) -> path_spec_type:
"""
Generate a list of standard pathspecs for global config files.
Args:
tool (str): name of the tool to configure
"""
try:
home = Path(os.environ["XDG_HOME"])
except KeyError:
home = Path.home()
return [
{"path_specs": home / f"{tool}.ini", "ac_parser": "ini", "keys": [tool]},
{"path_specs": home / f".{tool}", "ac_parser": "ini", "keys": [tool]},
{"path_specs": home / f".{tool}.ini", "ac_parser": "ini", "keys": [tool]},
{
"path_specs": home / ".config" / f"{tool}.ini",
"ac_parser": "ini",
"keys": [tool],
},
{
"path_specs": home / ".config" / f".{tool}",
"ac_parser": "ini",
"keys": [tool],
},
{
"path_specs": home / ".config" / f".{tool}.ini",
"ac_parser": "ini",
"keys": [tool],
},
]
def _get_local_path_specs(tool: str, project_home: Union[str, Path]) -> path_spec_type:
"""
Generate a list of standard pathspecs for local, project directory config files.
Args:
tool (str): name of the tool to configure
"""
return [
{
"path_specs": Path(project_home) / f"{tool}.ini",
"ac_parser": "ini",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f".{tool}",
"ac_parser": "ini",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f".{tool}.ini",
"ac_parser": "ini",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f"{tool}.yml",
"ac_parser": "yaml",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f".{tool}.yml",
"ac_parser": "yaml",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f"{tool}.toml",
"ac_parser": "toml",
"keys": [tool],
},
{
"path_specs": Path(project_home) / f".{tool}.toml",
"ac_parser": "toml",
"keys": [tool],
},
{
"path_specs": Path(project_home) / "pyproject.toml",
"ac_parser": "toml",
"keys": ["tool", tool],
},
{
"path_specs": Path(project_home) / "setup.cfg",
"ac_parser": "ini",
"keys": [f"tool.{tool}"],
},
]
def _get_attrs(attrs: list, config: Dict) -> Dict:
"""Get nested config data from a list of keys.
specifically written for pyproject.toml which needs to get `tool` then `<tool>`
"""
for attr in attrs:
config = config[attr]
return config
def _load_files(config_path_specs: path_spec_type) -> Dict:
"""Use anyconfig to load config files stopping at the first one that exists.
config_path_specs (list): a list of pathspecs and keys to load
"""
for file in config_path_specs:
if file["path_specs"].exists():
config = anyconfig.load(**file)
else:
# ignore missing files
continue
try:
return _get_attrs(file["keys"], config)
except KeyError:
# ignore incorrect keys
continue
return {}
def _load_env(tool: str) -> Dict:
"""Load config from environment variables.
Args:
tool (str): name of the tool to configure
"""
vars = [var for var in os.environ.keys() if var.startswith(tool.upper())]
return {
var.lower().strip(tool.lower()).strip("_").strip("-"): os.environ[var]
for var in vars
}
def load(tool: str, project_home: Union[Path, str] = ".", overrides: Dict = {}) -> Dict:
"""Load tool config from standard config files.
Resolution Order
* First global file with a tool key
* First local file with a tool key
* Environment variables prefixed with `TOOL`
* Overrides
Args:
tool (str): name of the tool to configure
"""
global_config = _load_files(_get_global_path_specs(tool))
local_config = _load_files(_get_local_path_specs(tool, project_home))
env_config = _load_env(tool)
return {**global_config, **local_config, **env_config, **overrides}

18
pyflybygen/tui/app.css Normal file
View file

@ -0,0 +1,18 @@
Screen {
align: center middle;
layers: main footer;
}
Sidebar {
height: 100vh;
width: auto;
min-width: 20;
background: $secondary-background-darken-2;
dock: left;
margin-right: 1;
layer: main;
}
Footer {
layer: footer;
}

62
pyflybygen/tui/app.py Normal file
View file

@ -0,0 +1,62 @@
from pathlib import Path
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.css.query import NoMatches
from textual.widgets import Footer, Static
from pyflybygen.config import config
config["tui"] = {}
config["tui"]["bindings"] = {}
class Sidebar(Static):
def compose(self) -> ComposeResult:
yield Container(
Static("sidebar"),
id="sidebar",
)
class Tui(App):
"""A Textual app to manage requests."""
CSS_PATH = Path("__file__").parent / "app.css"
BINDINGS = [tuple(b.values()) for b in config["tui"]["bindings"]]
def compose(self) -> ComposeResult:
"""Create child widgets for the app."""
yield Container(Static("hello world"))
yield Footer()
def action_toggle_dark(self) -> None:
"""An action to toggle dark mode."""
self.dark = not self.dark
def action_toggle_sidebar(self):
try:
self.query_one("PromptSidebar").remove()
except NoMatches:
self.mount(Sidebar())
def run_app():
import os
import sys
from textual.features import parse_features
dev = "--dev" in sys.argv
features = set(parse_features(os.environ.get("TEXTUAL", "")))
if dev:
features.add("debug")
features.add("devtools")
os.environ["TEXTUAL"] = ",".join(sorted(features))
app = Tui()
app.run()
if __name__ == "__main__":
run_app()

103
pyproject.toml Normal file
View file

@ -0,0 +1,103 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "pyflybygen"
description = 'generate project pyflyby configurations'
readme = "README.md"
requires-python = ">=3.7"
license = "MIT"
keywords = []
authors = [
{ name = "Waylon S. Walker", email = "waylon@waylonwalker.com" },
]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = [
"rich",
"textual",
"typer",
"anyconfig",
"tree_sitter_languages",
'more_itertools',
'coverage',
'coverage-rich',
]
dynamic = ["version"]
[project.urls]
Documentation = "https://github.com/waylonwalker/pyflybygen#readme"
Issues = "https://github.com/waylonwalker/pyflybygen/issues"
Source = "https://github.com/waylonwalker/pyflybygen"
Changelog = "https://github.com/waylonwalker/pyflybygen"
[project.scripts]
pyflybygen = "pyflybygen.cli.app:app"
[tool.hatch.version]
path = "pyflybygen/__about__.py"
[tool.hatch.envs.default]
dependencies = [
"ipython",
"mypy",
"pyflyby",
"pytest",
"pytest-cov",
"pytest-mock",
"pytest-rich",
"ruff",
"black",
]
[tool.hatch.envs.default.scripts]
test = "coverage run -m pytest"
cov = "coverage-rich report"
lint = "ruff pyflybygen"
format = "black pyflybygen"
format-check = "black --check pyflybygen"
build-docs = "markata build"
lint-test = [
"lint",
"format-check",
# "test",
# "cov",
]
test-lint = "lint-test"
[[tool.hatch.envs.test.matrix]]
python = ["37", "38", "39", "310", "311"]
[tool.coverage.run]
branch = true
parallel = true
omit = [
"pyflybygen/__about__.py",
]
[tool.coverage.report]
exclude_lines = [
"no cov",
"if __name__ == .__main__.:",
"if TYPE_CHECKING:",
]
[tool.pytest.ini_options]
addopts = "-ra -q --rich"
asyncio_mode = "auto"
testpaths = ["tests"]
[tool.coverage_rich]
fail-under=80
[tool.ruff]
ignore=['E501'] # let black control line length errors

3
tests/__init__.py Normal file
View file

@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: 2023-present Waylon S. Walker <waylon@waylonwalker.com>
#
# SPDX-License-Identifier: MIT

2
tests/test_pass.py Normal file
View file

@ -0,0 +1,2 @@
def test_pass():
...

17
tmp.py Normal file
View file

@ -0,0 +1,17 @@
from pathlib import Path
statements = """
from __future__ import (absolute_import,
division)
import os
import collections, itertools
from math import *
from gzip import open as gzip_open
from subprocess import check_output, Popen
"""
imports = more_itertools.flatten(
[get_imports(p.read_text()) for p in Path(".").glob("**/*.py")]
)
print("\n".join(set(imports)))