diff --git a/CHANGES.md b/CHANGES.md index 72a5166..1b8a6c7 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,12 @@ # Release notes +## 0.0.9 +Oct 15, 2024 +- Add **prj_files** function +- Add return bool into **prj_test** function +- Add Apache v2 license +- Fix creation docs folder into **prj_docs** function + ## 0.0.8 Sep 23, 2024 - Add **prj_tox** function diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..20bcc4f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[INSERT CONTACT METHOD]. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0d6afb0 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,29 @@ +# Contributing to PSP + +Thank you for your interest in contributing to PSP! There are many ways to contribute +and we appreciate all of them. + +The best way to get started is by reading the README and CODE\_OF\_CONDUCT files. + +Also read the documentation of [Python](https://docs.python.org/3/) project, before write or add a piece of code. + +Bug fixes, feature additions, tests, documentation and more can be contributed via issues and/or pull requests. +**All contributions are welcome**. + +## Bug fixes, feature additions, etc. + +Please send a pull request to the `main` branch. +Tests or documentation without bug fixes or feature additions are welcome too. +Feel free to ask questions via issues, discussions, or mail. + +- Fork the PSP repository. +- Create a branch from `main`. +- Develop bug fixes, features, tests, etc. +- Create a pull request to pull the changes from your branch to the PSP `main`. + +## Guidelines + +- Separate code commits from reformatting commits. +- Follow [Rust Style Guide](https://doc.rust-lang.org/nightly/style-guide/). +- Include release notes as needed or appropriate with your bug fixes, feature additions. +- Do not add to the changelog for proposed changes, as that is updated after changes are merged. diff --git a/Cargo.toml b/Cargo.toml index 9d0fb15..f17a964 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,10 @@ [package] name = "psp" -version = "0.0.8" +version = "0.0.9" edition = "2021" authors = ["matteoguadrini "] description = "PSP (Python Scaffolding Projects)" +license = "Apache License 2.0" readme = "README.md" repository = "https://github.com/MatteoGuadrini/psp" diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..b62a9b5 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,194 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index ed42a64..e29c1c3 100644 --- a/README.md +++ b/README.md @@ -2,91 +2,120 @@ `psp` is a blazing fast command line utility to scaffold your _Python_ project, written in Rust. -> [!NOTE] -> This project is WIP: beta +- ⚡️ 10-100x faster +- 🛠️ `pyproject.toml` support +- 🤝 Python 3.13 compatibility +- 📦 Unit-test and [pytest](https://docs.pytest.org/) supports +- 🔧 Automatically dependencies installation +- 📏 [tox](https://tox.wiki/en/stable/) configuration supports and other remotes CI +- ⌨️ [MkDocs](https://www.mkdocs.org/) and [Sphinx](https://www.sphinx-doc.org/) documentation supports +- 🌎 Github and Gitlab remote repository supports -![Demo](https://i.ibb.co/KcZtw58/psp008.gif) +psp -```console -psp # Press Enter -Welcome to PSP (Python Scaffolding Projects): 0.0.8 -> Name of Python project: test -> Do you want to start git repository? Yes -> Do you want unit test files? Yes -> Do you want to create a virtual environment? Yes -> Install dependencies: scipy numpy -> Select CI provider: CircleCI -> Select git remote provider: Github -> Username of Github: MatteoGuadrini -> Do you want to configure tox? Yes -> Select document generator: Sphinx -Project `test` created -``` +> [!NOTE] +> This project is WIP: beta The result is: ```console -tree test --filelimit=10 -a -test # project folder -├── pyproject.toml # python package configuration file -├── .circleci # CI folder -│   └── config.yml # CI configuration file -├── docs # documentation folder: Sphinx/MKDocs -│   ├── build -│   ├── make.bat -│   ├── Makefile -│   └── source -│   ├── conf.py -│   ├── index.rst -│   ├── _static -│   └── _templates -├── .git # git folder -│   ├── branches -│   ├── config -│   ├── description -│   ├── HEAD -│   ├── hooks [14 entries exceeds filelimit, not opening dir] -│   ├── info -│   │   └── exclude -│   ├── objects -│   │   ├── info -│   │   └── pack -│   └── refs -│   ├── heads -│   └── tags -├── .github # Github issue and merge templates -│   ├── ISSUE_TEMPLATE -│   │   ├── bug.yml -│   │   ├── config.yml -│   │   └── feature.yml -│   └── PULL_REQUEST_TEMPLATE -│   └── pull_request_template.md -├── .gitignore # git ignore file -├── test # python package -│   └── __init__.py -├── tests # tests package for modules -│   ├── __init__.py -│   └── test_test.py # test module "test_" -├── tox.ini # Tox configuration files -└── venv # virtual environment +$> tree test/ --filelimit=10 -a +test # Project folder +├── LICENSE.md # License file +├── pyproject.toml # Python package configuration file +├── README.md # Readme file +├── CHANGES.md # List of changes +├── .circleci # CI folder +│ └── config.yml # CI configuration file +├── CODE_OF_CONDUCT.md # Code of Conduct +├── CONTRIBUTING.md # Contributing guide lines +├── docs # Documentation folder: Sphinx/MKDocs +│ ├── build +│ ├── make.bat +│ ├── Makefile +│ └── source +│ ├── conf.py +│ ├── index.rst +│ ├── _static +│ └── _templates +├── .git # Git folder +│ ├── branches +│ ├── config +│ ├── description +│ ├── HEAD +│ ├── hooks [14 entries exceeds filelimit, not opening dir] +│ ├── info +│ │ └── exclude +│ ├── objects +│ │ ├── info +│ │ └── pack +│ └── refs +│ ├── heads +│ └── tags +├── .github # Github issue and merge templates +│ ├── ISSUE_TEMPLATE +│ │ ├── bug.yml +│ │ ├── config.yml +│ │ └── feature.yml +│ └── PULL_REQUEST_TEMPLATE +│ └── pull_request_template.md +├── .gitignore # Git ignore file +├── test # Python package +│ └── __init__.py +├── tests # Tests package for modules +│ ├── __init__.py +│ └── test_test.py # Test module "test_" +├── tox.ini # Tox configuration files +└── venv # Virtual environment ├── bin [33 entries exceeds filelimit, not opening dir] ├── include - │   └── python3.12 + │ └── python3.12 ├── lib - │   └── python3.12 - │   └── site-packages [68 entries exceeds filelimit, not opening dir] + │ └── python3.12 + │ └── site-packages [68 entries exceeds filelimit, not opening dir] ├── lib64 -> lib └── pyvenv.cfg -30 directories, 20 files +30 directories, 39 files +``` + +And `git` status is: + +```console +$> git status +On branch main + +No commits yet +... +$> git remote get-url origin +git@github.com:MatteoGuadrini/test.git ``` ## Prerequisites -`psp` has three prerequisetes installed on own machine: +`psp` has four prerequisetes installed on own machine: - `git` - `python3` - `pip` +- `curl` + +### Ubuntu prerequisites installation + +```console +sudo apt install -y python3 python3-pip git curl +``` + +### Red Hat prerequisites installation + +```console +sudo dnf install -y python3 python3-pip git curl +``` + +### Arch prerequisites installation + +```console +sudo pacman -Qi python3 python3-pip git curl +``` ## Installation @@ -97,13 +126,13 @@ To install compiled file into your machine, download it: For all users: ```console sudo -i -curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.8/psp_linux > /usr/bin/psp +curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.9/psp_linux > /usr/bin/psp chmod +x /usr/bin/psp ``` For current user: ```console -curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.8/psp_linux > $HOME/.local/bin/psp +curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.9/psp_linux > $HOME/.local/bin/psp chmod +x $HOME/.local/bin/psp ``` @@ -111,15 +140,32 @@ chmod +x $HOME/.local/bin/psp ```console sudo su - -curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.8/psp_macos > /usr/bin/psp +curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.9/psp_macos > /usr/bin/psp chmod +x /usr/bin/psp ``` +### Packages + +For **Debian/Ubuntu**: + +```console +curl -L https://github.com/MatteoGuadrini/psp/releases/download/v0.0.9/psp.deb +sudo dpkg -i psp.deb +``` + +For **Fedora/Mageia/OpenSuse**: + +```console +sudo rpm -i https://github.com/MatteoGuadrini/psp/releases/download/v0.0.9/psp.rpm +``` + +### Compile as your own + Instead, if you compile this project as own, follow this steps: ```console git clone https://github.com/MatteoGuadrini/psp.git -cd psp && cargo build && sudo cp -var target/release/psp /usr/bin/psp +cd psp && cargo build --release && sudo cp -var target/release/psp /usr/bin/psp ``` ## Features @@ -134,9 +180,10 @@ cd psp && cargo build && sudo cp -var target/release/psp /usr/bin/psp - [x] Prepare Github/Gitlab files - [x] Prepare tox environment - [x] Prepare docs folder for sphinx/mkdocs documentation -- [ ] Prepare README, LICENSE, CONTRIBUTING, CODE_OF_CONDUCT and CHANGES files +- [x] Prepare README, LICENSE, CONTRIBUTING, CODE_OF_CONDUCT and CHANGES files - [ ] Add build and deploy dependencies to distribute package -- [ ] Add _quick_, _nodocs_ and _full_ argument for rapid configuration +- [ ] Add Dockerfile for your project +- [ ] Add _quick_, _simple_ and _full_ argument for rapid configuration ## Open source _psp_ is an open source project. Any contribute, It's welcome. @@ -178,4 +225,4 @@ Thanks to [Zed IDE](https://zed.dev/) and for license of [RustRover](https://www Special thanks go to my wife, who understood the hours of absence for this development. Thanks to my children, for the daily inspiration they give me and to make me realize, that life must be simple. -Thanks, Rust! +Thanks, Rust Community! diff --git a/src/main.rs b/src/main.rs index ec86440..93ff7be 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ use std::{ }; // Constants -const VERSION: &str = "0.0.8"; +const VERSION: &str = "0.0.9"; // Utility functions @@ -48,10 +48,15 @@ fn make_file(file: &str, content: String) -> std::io::Result<()> { // Function for prompt text fn prompt_text(question: &str, default: &str, help: &str) -> String { - let answer = if default != "None" { - Text::new(question).with_default(default).prompt() + let answer = if help != "None" && default != "None" { + Text::new(question) + .with_help_message(help) + .with_default(default) + .prompt() } else if help != "None" { Text::new(question).with_help_message(help).prompt() + } else if default != "None" { + Text::new(question).with_default(default).prompt() } else { Text::new(question).prompt() }; @@ -86,16 +91,35 @@ fn prompt_select(question: &str, options: Vec<&str>, help: &str) -> String { // Core functions // Project name -fn prj_name() -> String { - let name = prompt_text("Name of Python project:", "prj", "None"); - let root = format!("{name}"); - let package = format!("{}", name.to_lowercase()); +fn prj_name() -> (String, String) { + let name = prompt_text( + "Name of Python project:", + "pyprj", + "Type name or absolute path", + ); + // Check if absolute path + let package: String = if name.contains('/') { + let parts: Vec<&str> = name.split('/').collect(); + let last = parts.last(); + if !last.is_none() { + last.unwrap().to_lowercase().to_string() + } else { + String::new() + } + } else { + name.to_lowercase() + }; + // Check if package is empty + if package.is_empty() { + eprintln!("error: remove trailing slash to {name}"); + exit(1) + } + let root = name.clone(); let project = format!("{root}/{package}"); // Make directories structure let dir_ret = make_dirs(format!("{project}").as_str()); if let Err(e) = dir_ret { eprintln!("error: {}", e); - exit(4); } // Make file structures let file_ret = make_file( @@ -103,9 +127,9 @@ fn prj_name() -> String { "#! /usr/bin/env python3 # -*- encoding: utf-8 -*- # vim: se ts=4 et syn=python: +# Generated by psp (https://github.com/MatteoGuadrini/psp) - - +__version__ = '0.0.1' " .to_string(), ); @@ -113,7 +137,25 @@ fn prj_name() -> String { eprintln!("error: {}", e); exit(4); } - name + let main_file = make_file( + format!("{project}/__main__.py").as_str(), + format!( + "#! /usr/bin/env python3 +# -*- encoding: utf-8 -*- +# vim: se ts=4 et syn=python: +# Generated by psp (https://github.com/MatteoGuadrini/psp) + +from .__init__ import __version__ +print(f'{} {{__version__}}') +", + package.to_lowercase() + ), + ); + if let Err(e) = main_file { + eprintln!("error: {}", e); + exit(4); + } + (root, package) } // Project git @@ -128,12 +170,13 @@ fn prj_git(name: &str) -> bool { // Check if command exit successfully if !output.status.success() { eprintln!("error: something wrong with `git init`"); - exit(5) + return false; } // Create .gitignore file let file_ret = make_file( format!("{name}/.gitignore").as_str(), - "### Python ### + "# Generated by psp (https://github.com/MatteoGuadrini/psp) +### Python ### __pycache__/ *.py[cod] *$py.class @@ -171,7 +214,7 @@ docs/_build/ ); let ret = if let Err(e) = file_ret { eprintln!("error: {}", e); - exit(5); + false } else { true }; @@ -181,21 +224,23 @@ docs/_build/ } // Project unit tests -fn prj_test(name: &str) { +fn prj_test(root: &str, name: &str) -> bool { let confirm = prompt_confirm("Do you want unit test files?", true, "None"); if confirm { + let project_name = name.to_lowercase(); // Make directories structure - let dir_ret = make_dirs(format!("{name}/tests").as_str()); + let dir_ret = make_dirs(format!("{root}/tests").as_str()); if let Err(e) = dir_ret { eprintln!("error: {}", e); - exit(6); + return false; } // Make file structures let init_file = make_file( - format!("{name}/tests/__init__.py").as_str(), + format!("{root}/tests/__init__.py").as_str(), "#! /usr/bin/env python3 # -*- encoding: utf-8 -*- # vim: se ts=4 et syn=python: +# Generated by psp (https://github.com/MatteoGuadrini/psp) " @@ -203,15 +248,15 @@ fn prj_test(name: &str) { ); if let Err(e) = init_file { eprintln!("error: {}", e); - exit(6); + return false; } - let project_name = name.to_lowercase(); let all_module = make_file( - format!("{name}/tests/test_{name}.py").as_str(), + format!("{root}/tests/test_{project_name}.py").as_str(), format!( "#! /usr/bin/env python3 # -*- encoding: utf-8 -*- # vim: se ts=4 et syn=python: +# Generated by psp (https://github.com/MatteoGuadrini/psp) import unittest @@ -235,8 +280,11 @@ if __name__ == '__main__': ); if let Err(e) = all_module { eprintln!("error: {}", e); - exit(6); + return false; } + return true; + } else { + return false; } } @@ -295,14 +343,37 @@ fn prj_deps(name: &str, venv: bool) -> Vec { } // Project pyproject.toml -fn prj_toml(name: &str, deps: &Vec) { +fn prj_toml(root: &str, name: &str, deps: &Vec, mut license: String) { + let mut classifiers = vec!["Programming Language :: Python :: 3"]; + // Check dependencies let requirements = if deps.contains(&"No".to_string()) { "[]".to_string() } else { format!("{deps:?}") }; + // Check license + if license == "None" { + license = String::new(); + } else if license == "MIT" { + license = "MIT License".to_string(); + classifiers.push("License :: OSI Approved :: MIT License") + } else if license == "Apache" { + license = "Apache Software License".to_string(); + classifiers.push("License :: OSI Approved :: Apache Software License") + } else if license == "Creative Commons" { + license = "Common Public License".to_string(); + classifiers.push("License :: OSI Approved :: Common Public License") + } else if license == "Mozilla" { + license = "Mozilla Public License 2.0 (MPL 2.0)".to_string(); + classifiers.push("License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)") + } else if license == "Gnu Public License" { + license = "GNU General Public License v3 (GPLv3)".to_string(); + classifiers.push("License :: OSI Approved :: GNU General Public License v3 (GPLv3)") + } let content = format!( - "[build-system] + "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +[build-system] requires = ['setuptools', 'wheel'] build-backend = 'setuptools.build_meta' @@ -310,28 +381,30 @@ build-backend = 'setuptools.build_meta' name = '{}' version = '0.0.1' readme = 'README.md' -license = '' +license = {{text = '{}'}} authors = [{{name = 'psp', email = 'psp@example.com'}}] maintainers = [{{name = 'psp', email = 'psp@example.com'}}] description = 'A simple but structured Python project' requires-python = '>=3.12' -classifiers = ['Programming Language :: Python :: 3'] +classifiers = {:?} dependencies = {} [project.urls] -homepage = '' -documentation = '' -repository = '' -changelog = '' +homepage = 'https://www.python.org/' +documentation = 'https://docs.python.org/3/' +repository = 'https://github.com/python' +changelog = 'https://docs.python.org/3/whatsnew/changelog.html' ", name.to_lowercase(), + license, + classifiers, requirements ); // Write pyproject.toml - let pyproject = make_file(format!("{name}/pyproject.toml").as_str(), content); + let pyproject = make_file(format!("{root}/pyproject.toml").as_str(), content); if let Err(e) = pyproject { eprintln!("error: {}", e); - exit(7); + return; } } @@ -349,12 +422,14 @@ fn prj_ci(name: &str, deps: &Vec) { let travis = make_file( format!("{name}/.travis.yml").as_str(), format!( - "language: python + "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +language: python cache: pip python: - - 3.10 - 3.11 - 3.12 + - 3.13 before_install: - sudo apt-get update - sudo apt-get install python3-pip @@ -378,7 +453,9 @@ script: let circle = make_file( format!("{name}/.circleci/config.yml").as_str(), format!( - "version: 2.1 + "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +version: 2.1 jobs: build-and-test: docker: @@ -411,7 +488,7 @@ jobs: } // Project Gitlab/Github -fn prj_remote(name: &str) { +fn prj_remote(root: &str, name: &str) { let options = vec!["None", "Gitlab", "Github"]; let remote = prompt_select("Select git remote provider:", options, "None"); if remote.as_str() != "None" { @@ -430,7 +507,7 @@ fn prj_remote(name: &str) { ); let output = std::process::Command::new("git") .args(["remote", "add", "origin", &remote_path]) - .current_dir(name) + .current_dir(root) .output() .expect("git should be installed"); // Check if command exit successfully @@ -443,10 +520,10 @@ fn prj_remote(name: &str) { // Make remote files and folders // Gitlab if remote.as_str() == "Gitlab" { - let issue_folder = format!("{}/.{}/issue_templates", name, remote.to_lowercase()); + let issue_folder = format!("{}/.{}/issue_templates", root, remote.to_lowercase()); let merge_folder = format!( "{}/.{}/merge_request_templates", - name, + root, remote.to_lowercase() ); let dir_ret = make_dirs(issue_folder.as_str()); @@ -458,7 +535,9 @@ fn prj_remote(name: &str) { eprintln!("error: {}", e); } let feature_content = format!( - "## Description + " + +## Description Description of the proposal @@ -480,7 +559,9 @@ Additional context eprintln!("error: {}", e); } let bug_content = format!( - "## Description of problem + " + +## Description of problem Provide a concise description of the bug @@ -507,7 +588,9 @@ Additional context eprintln!("error: {}", e); } let merge_content = format!( - "## What does this MR do and why? + " + +## What does this MR do and why? %{{first_multiline_commit}} @@ -529,8 +612,8 @@ Numbered steps to set up and validate the change are strongly suggested. } // Github } else if remote.as_str() == "Github" { - let issue_folder = format!("{}/.{}/ISSUE_TEMPLATE", name, remote.to_lowercase()); - let merge_folder = format!("{}/.{}/PULL_REQUEST_TEMPLATE", name, remote.to_lowercase()); + let issue_folder = format!("{}/.{}/ISSUE_TEMPLATE", root, remote.to_lowercase()); + let merge_folder = format!("{}/.{}/PULL_REQUEST_TEMPLATE", root, remote.to_lowercase()); let dir_ret = make_dirs(issue_folder.as_str()); if let Err(e) = dir_ret { eprintln!("error: {}", e); @@ -548,7 +631,9 @@ Numbered steps to set up and validate the change are strongly suggested. eprintln!("error: {}", e); } let feature_content = format!( - "name: Feature Request + "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +name: Feature Request description: File a feature request. title: '[Feature]: ' labels: ['enhancement'] @@ -592,7 +677,9 @@ body: eprintln!("error: {}", e); } let bug_content = format!( - "name: Bug Report + "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +name: Bug Report description: File a bug report. title: '[Bug]: ' labels: ['bug'] @@ -647,7 +734,10 @@ body: eprintln!("error: {}", e); } let merge_content = format!( - "# Title of Pull Request + " + +# Title of Pull Request + --- name: Tracking issue about: Use this template for tracking new features. @@ -655,6 +745,7 @@ title: '[DATE]: [FEATURE NAME]' labels: enhancement assignees: {} --- + ## Describe your changes ## Issue ticket number and link @@ -702,8 +793,10 @@ fn prj_tox(name: &str, venv: bool) { return; } // Write tox.ini - let tox_ini_content = "[tox] -envlist = py310, py311, py312 + let tox_ini_content = "# Generated by psp (https://github.com/MatteoGuadrini/psp) + +[tox] +envlist = py311, py312, py313 isolated_build = True [testenv] @@ -718,99 +811,232 @@ commands = pytest tests" } } -fn prj_docs(name: &str, venv: bool) { +fn prj_docs(root: &str, name: &str, venv: bool) { let options = vec!["None", "Sphinx", "MKDocs"]; - let docs = prompt_select("Select document generator:", options, "None"); - let docs_home = format!("{name}/docs"); - // Create docs folder - let docs_folder = make_dirs(format!("{docs_home}").as_str()); - if let Err(e) = docs_folder { - eprintln!("error: {}", e); - exit(4); - } - if docs.as_str() == "Sphinx" { - // Install sphinx - let mut pip = std::process::Command::new("pip3"); - // Activate venv - if venv { - pip.env("PATH", "venv/bin"); + let docs = prompt_select("Select documention generator:", options, "None"); + if docs != "None" { + let docs_home = format!("{root}/docs"); + // Create docs folder + let docs_folder = make_dirs(format!("{docs_home}").as_str()); + if let Err(e) = docs_folder { + eprintln!("error: {}", e); + exit(4); } - let output = pip - .arg("install") - .arg("--timeout=10") - .arg("--retries=1") - .arg("sphinx") - .current_dir(&name) - .output() - .expect("pip should be installed"); - // Check if command exit successfully - if !output.status.success() { - eprintln!("error: sphinx installation failed"); - return; + if docs.as_str() == "Sphinx" { + // Install sphinx + let mut pip = std::process::Command::new("pip3"); + // Activate venv + if venv { + pip.env("PATH", "venv/bin"); + } + let output = pip + .arg("install") + .arg("--timeout=10") + .arg("--retries=1") + .arg("sphinx") + .current_dir(&root) + .output() + .expect("pip should be installed"); + // Check if command exit successfully + if !output.status.success() { + eprintln!("error: sphinx installation failed"); + return; + } + // Start documentation; + let sphinx_bin = "../venv/bin/sphinx-quickstart".to_string(); + let mut sphinx_quickstart = std::process::Command::new(sphinx_bin); + // Activate venv + if venv { + sphinx_quickstart.env("PATH", "venv/bin"); + } + let output = sphinx_quickstart + .arg("--quiet") + .arg("--sep") + .arg(format!("--project={}", name.to_lowercase())) + .arg("--author=''") + .arg("-v='0.0.1'") + .arg("--ext-autodoc") + .arg("--ext-doctest") + .arg("--ext-viewcode") + .arg("--makefile") + .current_dir(docs_home) + .output() + .expect("sphinx-quickstart should be installed"); + // Check if command exit successfully + if !output.status.success() { + eprintln!("error: sphinx documentation creation failed"); + } + } else if docs.as_str() == "MKDocs" { + // Install mkdocs + let mut pip = std::process::Command::new("pip3"); + // Activate venv + if venv { + pip.env("PATH", "venv/bin"); + } + let output = pip + .arg("install") + .arg("--timeout=10") + .arg("--retries=1") + .arg("mkdocs") + .current_dir(&root) + .output() + .expect("pip should be installed"); + // Check if command exit successfully + if !output.status.success() { + eprintln!("error: mkdocs installation failed"); + return; + } + // Start documentation; + let mkdocs_bin = "venv/bin/mkdocs".to_string(); + let mut mkdocs_new = std::process::Command::new(mkdocs_bin); + // Activate venv + if venv { + mkdocs_new.env("PATH", "venv/bin"); + } + let output = mkdocs_new + .arg("new") + .arg("--quiet") + .arg(".") + .current_dir(&root) + .output() + .expect("mkdocs should be installed"); + // Check if command exit successfully + if !output.status.success() { + eprintln!("error: mkdocs documentation creation failed"); + } } - // Start documentation; - let sphinx_bin = format!("../venv/bin/sphinx-quickstart"); - let mut sphinx_quickstart = std::process::Command::new(sphinx_bin); - // Activate venv - if venv { - sphinx_quickstart.env("PATH", "venv/bin"); + } +} + +fn prj_files(root: &str, name: &str) { + let confirm = prompt_confirm( + "Do you want create common files?", + true, + "Create README, CONTRIBUTING, CODE_OF_CONDUCT and CHANGES", + ); + if confirm { + // Create README + let readme_content = format!( + " + +# Welcome to {name} + +## Install {name} +```console +pip install . +``` + +## Acknowledgments +Thanks Python Community!" + ); + let readme = make_file(format!("{root}/README.md").as_str(), readme_content); + if let Err(e) = readme { + eprintln!("error: {}", e); } - let output = sphinx_quickstart - .arg("--quiet") - .arg("--sep") - .arg(format!("--project={}", name.to_lowercase())) - .arg("--author=''") - .arg("-v='0.0.1'") - .arg("--ext-autodoc") - .arg("--ext-doctest") - .arg("--ext-viewcode") - .arg("--makefile") - .current_dir(docs_home) - .output() - .expect("sphinx-quickstart should be installed"); - // Check if command exit successfully - if !output.status.success() { - eprintln!("error: sphinx documentation creation failed"); + // Create CHANGES + let changes_content = format!( + " + +# Release notes of {name} + +## 0.0.1 +- Start **{name}** project" + ); + let changes = make_file(format!("{root}/CHANGES.md").as_str(), changes_content); + if let Err(e) = changes { + eprintln!("error: {}", e); } - } else if docs.as_str() == "MKDocs" { - // Install mkdocs - let mut pip = std::process::Command::new("pip3"); - // Activate venv - if venv { - pip.env("PATH", "venv/bin"); + // Create CONTRIBUTING + let contributing_content = format!( + " + +# Contributing to {name} + +Bug fixes, feature additions, tests, documentation and more can be contributed via issues and/or pull requests. +**All contributions are welcome**. + +## Bug fixes, feature additions, etc. + +Please send a pull request to the `main` branch. +Please include documentation and tests for new features. +Tests or documentation without bug fixes or feature additions are welcome too. +Feel free to ask questions via issues, discussions, or mail. + +- Fork the {name} repository. +- Create a branch from `main`. +- Develop bug fixes, features, tests, etc. +- Run the test suite. +- Create a pull request to pull the changes from your branch to the {name} `main`. + +### Guidelines + +- Separate code commits from reformatting commits. +- Provide tests for any newly added code. +- Follow PEP 8. +- Include release notes as needed or appropriate with your bug fixes, feature additions and tests. +- Do not add to the changelog for proposed changes, as that is updated after changes are merged. +" + ); + let contributing = make_file( + format!("{root}/CONTRIBUTING.md").as_str(), + contributing_content, + ); + if let Err(e) = contributing { + eprintln!("error: {}", e); } - let output = pip - .arg("install") - .arg("--timeout=10") - .arg("--retries=1") - .arg("mkdocs") - .current_dir(&name) + // Create CODE_OF_CONDUCT + let output = std::process::Command::new("curl") + .arg("-oCODE_OF_CONDUCT.md") + .arg("-k") + .arg("https://www.contributor-covenant.org/version/2/1/code_of_conduct/code_of_conduct.md") + .current_dir(&root) .output() - .expect("pip should be installed"); + .expect("curl should be installed"); // Check if command exit successfully if !output.status.success() { - eprintln!("error: mkdocs installation failed"); - return; + eprintln!("error: CODE_OF_CONDUCT download failed"); } - // Start documentation; - let mkdocs_bin = format!("venv/bin/mkdocs"); - let mut mkdocs_new = std::process::Command::new(mkdocs_bin); - // Activate venv - if venv { - mkdocs_new.env("PATH", "venv/bin"); - } - let output = mkdocs_new - .arg("new") - .arg("--quiet") - .arg(".") + } +} + +fn prj_license(name: &str) -> String { + // Select license + let options = vec![ + "None", + "MIT", + "Apache", + "Creative Commons", + "Mozilla", + "Gnu Public License", + ]; + let license = prompt_select("Select license:", options, "None"); + let mut license_url = String::new(); + if license == "MIT" { + license_url.push_str("https://www.mit.edu/~amini/LICENSE.md") + } else if license == "Apache" { + license_url.push_str("https://www.apache.org/licenses/LICENSE-2.0.txt") + } else if license == "Creative Commons" { + license_url.push_str("https://creativecommons.org/licenses/by/4.0/legalcode.txt") + } else if license == "Mozilla" { + license_url.push_str("https://www.mozilla.org/media/MPL/2.0/index.f75d2927d3c1.txt") + } else if license == "Gnu Public License" { + license_url.push_str("https://www.gnu.org/licenses/gpl-3.0.md") + } + if !license_url.is_empty() { + // Create LICENSE + let output = std::process::Command::new("curl") + .arg("-oLICENSE.md") + .arg("-k") + .arg(license_url) .current_dir(&name) .output() - .expect("mkdocs should be installed"); + .expect("curl should be installed"); // Check if command exit successfully if !output.status.success() { - eprintln!("error: mkdocs documentation creation failed"); + eprintln!("error: LICENSE download failed"); } } + license } // Main program @@ -818,31 +1044,38 @@ fn main() { // Print welcome screen and version println!("Welcome to PSP (Python Scaffolding Projects): {VERSION}"); // Check dependencies tools - check_tool("python3"); - check_tool("git"); - check_tool("pip3"); + let tools = ["python3", "git", "pip3", "curl"]; + for tool in tools { + check_tool(tool); + } // Create project structure by name - let name = prj_name(); - // Start git - let git = prj_git(&name); - // Unit tests - prj_test(&name); + let (root, name) = prj_name(); // Virtual Environment - let venv = prj_venv(&name); - // Install dependencies - let deps = prj_deps(&name, venv); - // CI configuration - prj_ci(&name, &deps); + let venv = prj_venv(&root); + // Start git + let git = prj_git(&root); // Git remote if git { - prj_remote(&name); + prj_remote(&root, &name); } - // Write pyproject.toml - prj_toml(&name, &deps); - // Tox - prj_tox(&name, venv); + // Unit tests + let tests = prj_test(&root, &name); + // Install dependencies + let deps = prj_deps(&root, venv); // Documentation - prj_docs(&name, venv); + prj_docs(&root, &name, venv); + if tests { + // Tox + prj_tox(&root, venv); + // CI configuration + prj_ci(&root, &deps); + } + // Common files + prj_files(&root, &name); + // License + let license = prj_license(&root); + // Write pyproject.toml + prj_toml(&root, &name, &deps, license); // Finish scaffolding process - println!("Project `{name}` created") + println!("Python project `{name}` created at {root}/") }