Compare commits

...

9 Commits

Author SHA1 Message Date
Moritz Hölting 8a3ef9759c update to use shulkerscript branch feature/variables 2026-04-02 13:18:49 +02:00
Moritz Hölting 488a9b2470 fix clap command name & add notice if zip feature is disabled 2026-04-02 13:17:05 +02:00
Moritz Hölting 7c7980ab5e update install scripts 2026-04-02 13:16:20 +02:00
Moritz Hölting 0cd993c4ed prepare release of version 0.1.0 2026-04-02 13:16:20 +02:00
Moritz Hölting 86ffd27e0b change to dual license and final fixes for release 2026-04-02 13:15:12 +02:00
Moritz Hölting e82e17da68 add CONTRIBUTING and CODE_OF_CONDUCT 2026-04-02 13:13:22 +02:00
Moritz Hölting 3c9bd6c6bf implement basic migration subcommand 2026-04-02 13:13:22 +02:00
Moritz Hölting 39ccbf560f update dependency version and add check flag to build 2026-04-02 13:12:18 +02:00
Moritz Hölting 5deff21348 update shulkerscript-lang dependency 2026-04-02 13:09:54 +02:00
26 changed files with 3217 additions and 99 deletions

20
.github/workflows/publish.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Publish
on:
release:
types: [created]
jobs:
publish:
name: Publish to crates.io
runs-on: ubuntu-latest
permissions:
contents: read
env:
CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
with:
key: publish
- run: cargo publish --token ${CRATES_TOKEN}

83
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,83 @@
name: Release
on:
release:
types: [created]
permissions:
contents: write
jobs:
release:
name: Building ${{ matrix.platform.os_name }}
runs-on: ${{ matrix.platform.os }}
strategy:
fail-fast: false
matrix:
platform:
- os_name: Linux-x86_64
os: ubuntu-latest
target: x86_64-unknown-linux-musl
- os_name: Linux-aarch64
os: ubuntu-latest
target: aarch64-unknown-linux-musl
- os_name: Linux-arm
os: ubuntu-latest
target: arm-unknown-linux-musleabi
- os_name: Linux-i686
os: ubuntu-latest
target: i686-unknown-linux-musl
- os_name: Windows-aarch64
os: windows-latest
target: aarch64-pc-windows-msvc
- os_name: Windows-i686
os: windows-latest
target: i686-pc-windows-msvc
- os_name: Windows-x86_64
os: windows-latest
target: x86_64-pc-windows-msvc
- os_name: macOS-x86_64
os: macOS-latest
target: x86_64-apple-darwin
- os_name: macOS-aarch64
os: macOS-latest
target: aarch64-apple-darwin
steps:
- uses: actions/checkout@v4
- name: Cache cargo & target directories
uses: Swatinem/rust-cache@v2
with:
key: "release"
- name: Build binary
uses: houseabsolute/actions-rust-cross@v0
with:
command: "build"
target: ${{ matrix.platform.target }}
toolchain: stable
args:
"--locked --release"
strip: true
- name: Package as .tar.gz (Linux)
if: ${{ contains(matrix.platform.os, 'ubuntu') }}
run: |
mv target/${{ matrix.platform.target }}/release/shulkerscript ./shulkerscript
tar -czvf shulkerscript-${{ matrix.platform.target }}.tar.gz shulkerscript
echo UPLOAD_FILE=shulkerscript-${{ matrix.platform.target }}.tar.gz >> $GITHUB_ENV
- name: Package as .zip (Windows)
if: ${{ contains(matrix.platform.os, 'windows') }}
shell: bash
run: |
mv target/${{ matrix.platform.target }}/release/shulkerscript.exe ./shulkerscript.exe
pwsh -command ". 'Compress-Archive' shulkerscript.exe shulkerscript-${{ matrix.platform.target }}.zip"
echo UPLOAD_FILE=shulkerscript-${{ matrix.platform.target }}.zip >> $GITHUB_ENV
- name: Package as .zip (macOS)
if: ${{ contains(matrix.platform.os, 'macOS') }}
run: |
mv target/${{ matrix.platform.target }}/release/shulkerscript ./shulkerscript
zip shulkerscript-${{ matrix.platform.target }}.zip shulkerscript
echo UPLOAD_FILE=shulkerscript-${{ matrix.platform.target }}.zip >> $GITHUB_ENV
- name: Upload artifact to release
shell: bash
run: gh release upload ${{ github.event.release.tag_name }} $UPLOAD_FILE
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

19
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Cargo test
on:
push:
branches:
- main
- development
- 'releases/**'
pull_request:
env:
CARGO_TERM_COLOR: always
jobs:
test:
name: Cargo test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: cargo test --verbose

View File

@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
### Changed
### Removed
## [0.1.0] - 2024-10-01
### Added
- Subcommand `init` to initialize a new project
- Creates a new project directory with default files
- Subcommand `build` to build a project
@ -16,9 +24,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Allows changing the output directory and setting a assets directory
- Subcommand `clean` to clean the output directory
- Subcommand `watch` to watch for changes and run a command
- Subcommand `migrate` to migrate a datapack to a shulkerscript project
- Subcommand `lang-debug` to debug the language parser
- Allows to print the parsed tokens, AST and shulkerbox datapack representation
### Changed
### Removed
[unreleased]: https://github.com/moritz-hoelting/shulkerscript-cli/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/moritz-hoelting/shulkerscript-cli/releases/tag/v0.1.0

70
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,70 @@
# Code of Conduct - Shulkerscript CLI
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## 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
* 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
## Our Responsibilities
Project maintainers are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers 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, or to ban
temporarily or permanently any contributor for other behaviors that they deem
inappropriate, threatening, offensive, or harmful.
## 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 e-mail 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 [shulkerscript@hoelting.dev](mailto:shulkerscript@hoelting.dev).
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.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://contributor-covenant.org/), version
[1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/code_of_conduct.md) and
[2.0](https://www.contributor-covenant.org/version/2/0/code_of_conduct/code_of_conduct.md),
and was generated by [contributing-gen](https://github.com/bttger/contributing-gen).

147
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,147 @@
<!-- omit in toc -->
# Contributing to Shulkerscript CLI
First off, thanks for taking the time to contribute! ❤️
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
<!-- omit in toc -->
## Table of Contents
- [Code of Conduct](#code-of-conduct)
- [I Have a Question](#i-have-a-question)
- [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Your First Code Contribution](#your-first-code-contribution)
- [Improving The Documentation](#improving-the-documentation)
- [Styleguides](#styleguides)
- [Commit Messages](#commit-messages)
- [Join The Project Team](#join-the-project-team)
## Code of Conduct
This project and everyone participating in it is governed by the
[Shulkerscript CLI Code of Conduct](https://github.com/moritz-hoelting/shulkerscript-cli/blob/main/CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report unacceptable behavior
to .
## I Have a Question
> If you want to ask a question, we assume that you have read the available [Documentation](https://shulkerscript.hoelting.dev/).
> When asking about a missing feature, please make sure that it is not already on the [Roadmap](https://shulkerscript.hoelting.dev/roadmap).
Before you ask a question, it is best to search for existing [Issues](https://github.com/moritz-hoelting/shulkerscript-cli/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
If you then still feel the need to ask a question and need clarification, we recommend either [writing an email](mailto:shulkerscript@hoelting.dev) or opening an issue on GitHub:
- Open an [Issue](https://github.com/moritz-hoelting/shulkerscript-cli/issues/new).
- Provide as much context as you can about what you're running into.
- Add the `Question` label to the issue.
- Provide project and platform versions (Windows/Linux/macOS), depending on what seems relevant.
We will then take care of the issue as soon as possible.
## I Want To Contribute
> ### Legal Notice <!-- omit in toc -->
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
### Reporting Bugs
<!-- omit in toc -->
#### Before Submitting a Bug Report
A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://shulkerscript.hoelting.dev/). If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/moritz-hoelting/shulkerscript-cli/issues?q=label%3Abug).
- Collect information about the bug:
- Stack trace (Traceback)
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
- Version of the CLI.
- Possibly your input and the output
- Can you reliably reproduce the issue? And can you also reproduce it with older versions?
<!-- omit in toc -->
#### How Do I Submit a Good Bug Report?
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to .
<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
- Open an [Issue](https://github.com/moritz-hoelting/shulkerscript-cli/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.
Once it's filed:
- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
<!-- You might want to create an issue template for bugs and errors that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for Shulkerscript CLI, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
<!-- omit in toc -->
#### Before Submitting an Enhancement
- Make sure that you are using the latest version.
- Read the [documentation](https://shulkerscript.hoelting.dev/) carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](https://github.com/moritz-hoelting/shulkerscript-cli/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
<!-- omit in toc -->
#### How Do I Submit a Good Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://github.com/moritz-hoelting/shulkerscript-cli/issues).
- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- **Explain why this enhancement would be useful** to most Shulkerscript CLI users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
<!-- You might want to create an issue template for enhancement suggestions that can be used as a guide and that defines the structure of the information to be included. If you do so, reference it here in the description. -->
### Your First Code Contribution
Think about which part of the project your idea fits into. Do you want to work on [the cli](https://github.com/moritz-hoelting/shulkerscript-cli), [the language](https://github.com/moritz-hoelting/shulkerscript-lang) or [the datapack generation](https://github.com/moritz-hoelting/shulkerbox)?
- Make sure you have [Rust](https://www.rust-lang.org/tools/install) installed.
- Fork the repository and clone it to your local machine.
- Create a new branch for your feature or bug fix.
- Make your changes and commit them to your branch.
- Push your changes to your fork.
- Open a pull request in the original repository and describe the changes you made.
### Improving The Documentation
If you want to improve the documentation, you can do so by editing the [documentation repository](https://github.com/moritz-hoelting/shulkerscript-webpage).
- Make sure you have [Node.js](https://nodejs.org/en/download) and [PNPM](https://pnpm.io/installation) installed.
- Fork the repository and clone it to your local machine.
- Create a new branch for your changes.
- Start the development server with `pnpm dev --open`.
- Make your changes and commit them to your branch.
- Push your changes to your fork.
- Open a pull request in the original repository and describe the changes you made.
## Join The Project Team
We are always looking for new contributors to the project. If you are interested in joining the project team, please contact us at [shulkerscript@hoelting.dev](mailto:shulkerscript@hoelting.dev).
<!-- omit in toc -->
## Attribution
This guide is based on the **contributing-gen**. [Make your own](https://github.com/bttger/contributing-gen)!

1797
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,11 +4,14 @@ version = "0.1.0"
edition = "2021"
authors = ["Moritz Hölting <moritz@hoelting.dev>"]
categories = ["command-line-utilities", "compilers"]
description = "Command line tool to compile ShulkerScript projects"
description = "Command line tool to compile Shulkerscript projects"
categories = ["command-line-utilities", "compilers", "game-development"]
keywords = ["minecraft", "datapack", "mcfunction"]
repository = "https://github.com/moritz-hoelting/shulkerscript-cli"
homepage = "https://shulkerscript.hoelting.dev/"
readme = "README.md"
license = "MIT"
license = "MIT OR Apache-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -17,30 +20,33 @@ name = "shulkerscript"
path = "src/main.rs"
[features]
default = ["zip", "lua", "watch"]
default = ["lua", "migrate", "watch", "zip"]
lang-debug = []
lua = ["shulkerscript/lua"]
migrate = ["dep:indoc", "dep:serde_json", "dep:walkdir"]
watch = ["dep:notify-debouncer-mini", "dep:ctrlc"]
zip = ["shulkerbox/zip"]
zip = ["shulkerscript/zip"]
[dependencies]
clap = { version = "4.5.4", features = ["derive", "env", "deprecated"] }
colored = "2.1.0"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
toml = "0.8.12"
shulkerscript = { git = "https://github.com/moritz-hoelting/shulkerscript-lang.git", features = ["shulkerbox"], default-features = false, rev = "a0a27cda96e1922b019b216961c39f7ef7991d22" }
shulkerbox = { git = "https://github.com/moritz-hoelting/shulkerbox.git", default-features = false, rev = "a2d20dab8ea97bbd873edafb23afaad34292457f" }
git2 = { version = "0.19.0", default-features = false }
path-absolutize = "3.1.1"
anyhow = "1.0.95"
clap = { version = "4.5.32", features = ["deprecated", "derive", "env"] }
colored = "3.0.0"
const_format = "0.2.34"
ctrlc = { version = "3.4.5", optional = true }
dotenvy = "0.15.7"
notify-debouncer-mini = { version = "0.4.1", default-features = false, optional = true }
ctrlc = { version = "3.4.4", optional = true }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
# waiting for pull request to be merged
inquire = { git = "https://github.com/moritz-hoelting/rust-inquire.git", branch = "main", package = "inquire" }
camino = "1.1.7"
human-panic = "2.0.0"
anyhow = "1.0.86"
pathdiff = "0.2.1"
git2 = { version = "0.20.0", default-features = false }
human-panic = "2.0.2"
indoc = { version = "2.0.5", optional = true }
inquire = "0.7.5"
notify-debouncer-mini = { version = "0.7.0", default-features = false, optional = true }
path-absolutize = "3.1.1"
pathdiff = "0.2.3"
serde = { version = "1.0.217", features = ["derive"] }
serde_json = { version = "1.0.138", optional = true }
# shulkerscript = { version = "0.1.0", features = ["fs_access", "shulkerbox"], default-features = false }
shulkerscript = { git = "https://github.com/moritz-hoelting/shulkerscript-lang", features = ["fs_access", "shulkerbox"], default-features = false, rev = "1ed2919ab0375e625f55997e8ad3505b2137efb0" }
thiserror = "2.0.11"
toml = "0.9.5"
tracing = "0.1.41"
tracing-subscriber = "0.3.19"
walkdir = { version = "2.5.0", optional = true }

201
LICENSE-APACHE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
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 2024 Moritz Hölting <moritz@hoelting.dev>
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.

View File

@ -3,12 +3,30 @@
This is a cli tool for the shulkerscript language. It can be used to initialize a new project, and to compile and package a project.
## Installation
```bash
cargo install --git https://github.com/moritz-hoelting/shulkerscript-cli.git
### From release (Windows)
```powershell
iex (iwr "https://raw.githubusercontent.com/moritz-hoelting/shulkerscript-cli/main/install.ps1").Content
```
### From release (Linux / macOS)
```bash
curl -sfSL https://raw.githubusercontent.com/moritz-hoelting/shulkerscript-cli/main/install.sh | bash
```
### From source
```bash
cargo install shulkerscript-cli
```
## VS Code Extension
A VS Code extension is available [here](https://marketplace.visualstudio.com/items?itemName=moritz-hoelting.shulkerscript-lang) to provide syntax highlighting and snippets for Shulkerscript files.
## Usage
Read the [documentation](https://shulkerscript.hoelting.dev) for more information on the language and cli.
### Initialize a new project
```bash
shulkerscript init [OPTIONS] [PATH]

120
install.ps1 Normal file
View File

@ -0,0 +1,120 @@
# Error setup
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 3.0
Set-PSDebug -Strict
# Variables
$REPO = "moritz-hoelting/shulkerscript-cli"
$PROGRAM_DISPLAY_NAME = "Shulkerscript CLI"
$LATEST_RELEASE_URL = "https://api.github.com/repos/$REPO/releases/latest"
$BIN_NAME = "shulkerscript"
$CRATE_NAME = "shulkerscript-cli"
$INSTALL_PATH = Join-Path $env:USERPROFILE "AppData\Local\Programs\$BIN_NAME"
$PATH_REGISTRY = "Registry::HKEY_CURRENT_USER\Environment"
function Remove-Old-Version {
if ( (Test-Path variable:INSTALLED_VERSION) -and ($INSTALL_PATH -notlike "*\.cargo\bin*") ) {
Write-Host Removing old version at $INSTALL_PATH
Remove-Item -Path "$INSTALL_PATH" -Force -Recurse
}
}
# Determine the OS and architecture
$OS = 'windows'
$ARCH = $env:PROCESSOR_ARCHITECTURE
if ($ARCH -eq 'AMD64') {
$ARCH = 'x86_64'
} elseif ($ARCH -eq 'x86') {
$ARCH = 'i686'
} else {
Write-Host "Unsupported architecture: $ARCH" -ForegroundColor Red
return "Error"
}
# Fetch the latest release data from GitHub
try {
$LATEST_RELEASE_DATA = Invoke-RestMethod -Uri $LATEST_RELEASE_URL -Method Get
}
catch {
Write-Host "Failed to fetch latest release data." -ForegroundColor Red
return "Error"
}
# Get the latest version number
$LATEST_VERSION = $LATEST_RELEASE_DATA.tag_name
# Check if the CLI is already installed and get the current version
if (Get-Command $BIN_NAME -ErrorAction Ignore) {
$INSTALLED_VERSION = (& $BIN_NAME --version | Select-String -Pattern '\d+\.\d+\.\d+(-(rc|beta|alpha)(\.\d+)?)?' | Select-Object -First 1).Matches.Value
$CLEAN_LATEST_VERSION = (Write-Output $LATEST_VERSION | Select-String -Pattern '\d+\.\d+\.\d+(-(rc|beta|alpha)(\.\d+)?)?').Matches.Value
Write-Host "Installed version: v$INSTALLED_VERSION"
Write-Host "Latest version: v$CLEAN_LATEST_VERSION"
if ($INSTALLED_VERSION -eq $CLEAN_LATEST_VERSION) {
Write-Host "$PROGRAM_DISPLAY_NAME is already up to date."
return
}
else {
Write-Host "A new version is available. Upgrading..."
$INSTALL_PATH = Split-Path -Parent (Get-Command $BIN_NAME).Path
}
}
else {
Write-Host "$PROGRAM_DISPLAY_NAME is not installed. Installing version $LATEST_VERSION..."
}
# Use cargo-binstall if available
if (Get-Command cargo-binstall -ErrorAction SilentlyContinue) {
Write-Host "cargo-binstall is available. Installing/upgrading using cargo-binstall..."
cargo-binstall --git "https://github.com/$REPO" --force --locked --no-confirm $CRATE_NAME
Remove-Old-Version
return
}
# Get the download url of the latest release
$DOWNLOAD_URL = ($LATEST_RELEASE_DATA.assets | Where-Object {$_.browser_download_url -match "$OS" -and $_.browser_download_url -match "$ARCH"} | Select-Object -First 1).browser_download_url
if ([string]::IsNullOrEmpty($DOWNLOAD_URL)) {
# if there is no prebuilt binary, try to build from source
if (Get-Command cargo -ErrorAction SilentlyContinue) {
Write-Host "No prebuilt binary available for your platform. Building from source..."
cargo install --force --locked $CRATE_NAME
Remove-Old-Version
return
}
else {
Write-Host "No prebuilt binary available for your platform. Please install Rust and Cargo using https://rustup.rs and try again."
return "Error"
}
}
# Create a temporary directory
$TEMP = [System.IO.Path]::GetTempPath()
$TEMP_DIR = Join-Path $TEMP (New-Guid).ToString("N")
Remove-Item -Path "$TEMP_DIR" -Recurse -Force -ErrorAction Ignore | Out-Null
New-Item -ItemType Directory -Path $TEMP_DIR | Out-Null
# Download and extract the binary
Invoke-WebRequest -Uri $DOWNLOAD_URL -OutFile "$TEMP_DIR\$BIN_NAME.zip"
Expand-Archive -Path "$TEMP_DIR\$BIN_NAME.zip" -DestinationPath $TEMP_DIR -Force
# Create install location and move binary
New-Item -ItemType Directory -Path $INSTALL_PATH -Force | Out-Null
Move-Item -Path "$TEMP_DIR\$BIN_NAME.exe" -Destination "$INSTALL_PATH\$BIN_NAME.exe" -Force
# Remove temp dir
Remove-Item -Path "$TEMP_DIR" -Recurse -Force -ErrorAction Ignore | Out-Null
# Add binary to PATH
$REGEX_INSTALL_PATH = [regex]::Escape($INSTALL_PATH)
$ARR_PATH = $env:Path -split ';' | Where-Object {$_ -match "^$REGEX_INSTALL_PATH\\?"}
if (-not $ARR_PATH) {
Write-Host "Not found in current PATH, adding..."
$OLD_PATH = (Get-ItemProperty -Path "$PATH_REGISTRY" -Name PATH).path
$NEW_PATH = "$OLD_PATH;$INSTALL_PATH"
Set-ItemProperty -Path "$PATH_REGISTRY" -Name PATH -Value $NEW_PATH
$env:PATH="$NEW_PATH"
}
Write-Host "$PROGRAM_DISPLAY_NAME has been successfully installed/upgraded to version $LATEST_VERSION."

98
install.sh Normal file
View File

@ -0,0 +1,98 @@
#!/bin/bash
# Error setup
set -euo pipefail
# Variables
REPO="moritz-hoelting/shulkerscript-cli"
PROGRAM_DISPLAY_NAME="Shulkerscript CLI"
LATEST_RELEASE_URL="https://api.github.com/repos/$REPO/releases/latest"
BIN_NAME="shulkerscript"
CRATE_NAME="shulkerscript-cli"
INSTALL_PATH="$HOME/bin/$BIN_NAME"
function removeOldVersion() {
if [ ! -z ${INSTALLED_VERSION+x} ] && [[ $INSTALL_PATH != *"/.cargo/bin/"* ]]; then
rm -f $INSTALL_PATH
hash -d $BIN_NAME &> /dev/null || true
fi
}
# Determine the OS and architecture
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
# Fetch the latest release data from GitHub
LATEST_RELEASE_DATA=$(curl -s $LATEST_RELEASE_URL)
# Get the latest version number
LATEST_VERSION=$(echo "$LATEST_RELEASE_DATA" | grep 'tag_name' | cut -d '"' -f 4)
# Check if the CLI is already installed and get the current version
if which $BIN_NAME &> /dev/null; then
INSTALLED_VERSION=$($BIN_NAME --version | grep -m 1 -oE '[0-9]+\.[0-9]+\.[0-9]+(-(rc|beta|alpha)(\.\d+)?)?')
CLEAN_LATEST_VERSION=$(echo $LATEST_VERSION | grep -oE '[0-9]+\.[0-9]+\.[0-9]+(-(rc|beta|alpha)(\.\d+)?)?')
echo "Installed version: v$INSTALLED_VERSION"
echo "Latest version: v$CLEAN_LATEST_VERSION"
if [ "$INSTALLED_VERSION" == "$CLEAN_LATEST_VERSION" ]; then
echo "$PROGRAM_DISPLAY_NAME is already up to date."
exit 0
else
echo "A new version is available. Upgrading..."
INSTALL_PATH=$(which $BIN_NAME)
fi
else
echo "$PROGRAM_DISPLAY_NAME is not installed. Installing version $LATEST_VERSION..."
fi
# Use cargo-binstall if available
if which cargo-binstall &> /dev/null; then
echo "Found cargo-binstall. Installing/upgrading using cargo-binstall..."
cargo-binstall --git "https://github.com/$REPO" --force --locked --no-confirm $CRATE_NAME
# Remove old version
removeOldVersion
exit 0
fi
# Get the download url of the latest release
DOWNLOAD_URL=$(echo "$LATEST_RELEASE_DATA" | awk "/browser_download_url/ && /$OS/ && /$ARCH/" | cut -d '"' -f 4)
if [ -z "$DOWNLOAD_URL" ]; then
# if there is no prebuilt binary, try to build from source
if which cargo &> /dev/null; then
echo "No prebuilt binary available for your platform. Building from source..."
cargo install --force --locked $CRATE_NAME
removeOldVersion
exit 0
else
echo "No prebuilt binary available for your platform. Please install Rust and Cargo using https://rustup.rs and try again."
exit 1
fi
fi
if [[ "$DOWNLOAD_URL" == *"tar.gz" ]]; then
ARCHIVE_TYPE="tar.gz"
elif [[ "$DOWNLOAD_URL" == *"zip" ]]; then
ARCHIVE_TYPE="zip"
else
echo "Unsupported archive type."
exit 1
fi
# Create a temporary directory
TEMP_DIR=$(mktemp -d)
# Download and extract the binary
curl -L -s $DOWNLOAD_URL -o $TEMP_DIR/$BIN_NAME.$ARCHIVE_TYPE
if [[ "$ARCHIVE_TYPE" == "tar.gz" ]]; then
tar -xzf $TEMP_DIR/$BIN_NAME.$ARCHIVE_TYPE -C $TEMP_DIR
else
unzip $TEMP_DIR/$BIN_NAME.$ARCHIVE_TYPE -d $TEMP_DIR
fi
chmod +x "$TEMP_DIR/$BIN_NAME"
mv "$TEMP_DIR/$BIN_NAME" "$INSTALL_PATH"
echo "$PROGRAM_DISPLAY_NAME has been successfully installed/upgraded to version $LATEST_VERSION."

View File

@ -2,12 +2,19 @@ use crate::subcommands::{self, BuildArgs, CleanArgs, InitArgs};
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use const_format::formatcp;
use tracing::Level;
use tracing_subscriber::FmtSubscriber;
static VERSION: &str = formatcp!(
"v{cli_version}\nshulkerscript-lang v{lang_version}",
cli_version = env!("CARGO_PKG_VERSION"),
lang_version = shulkerscript::VERSION
);
#[derive(Debug, Clone, Parser)]
#[command(version, about, long_about = None)]
pub struct Args {
#[command(name = "shulkerscript", version = VERSION, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
cmd: Command,
/// Enable tracing output
@ -31,14 +38,17 @@ pub enum Command {
/// Build the project.
Build(BuildArgs),
/// Clean build artifacts.
/// This will remove the `dist` directory.
/// This will remove the output directory.
Clean(CleanArgs),
#[cfg(feature = "watch")]
/// Watch for changes and execute commands.
Watch(subcommands::WatchArgs),
#[cfg(feature = "lang-debug")]
/// Build the project and dump the intermediate state.
LangDebug(subcommands::LangDebugArgs),
#[cfg(feature = "migrate")]
/// Migrate a regular datapack to a Shulkerscript project.
Migrate(subcommands::MigrateArgs),
#[cfg(feature = "watch")]
/// Watch for changes and execute commands.
Watch(subcommands::WatchArgs),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, ValueEnum)]
@ -51,7 +61,7 @@ pub enum TracingLevel {
Error,
}
impl Args {
impl Cli {
pub fn run(&self) -> Result<()> {
if let Some(level) = self.trace {
setup_tracing(level)?;
@ -67,10 +77,12 @@ impl Command {
Command::Init(args) => subcommands::init(args)?,
Command::Build(args) => subcommands::build(args)?,
Command::Clean(args) => subcommands::clean(args)?,
#[cfg(feature = "watch")]
Command::Watch(args) => subcommands::watch(args)?,
#[cfg(feature = "lang-debug")]
Command::LangDebug(args) => subcommands::lang_debug(args)?,
#[cfg(feature = "migrate")]
Command::Migrate(args) => subcommands::migrate(args)?,
#[cfg(feature = "watch")]
Command::Watch(args) => subcommands::watch(args)?,
}
Ok(())
@ -111,6 +123,6 @@ mod tests {
#[test]
fn verify_cli() {
Args::command().debug_assert();
Cli::command().debug_assert();
}
}

View File

@ -1,6 +1,7 @@
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use shulkerscript::shulkerbox;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProjectConfig {
@ -12,6 +13,8 @@ pub struct ProjectConfig {
pub struct PackConfig {
pub name: String,
pub description: String,
#[serde(alias = "main-namespace")]
pub main_namespace: Option<String>,
#[serde(rename = "format", alias = "pack_format")]
pub pack_format: u8,
pub version: String,
@ -20,7 +23,7 @@ pub struct PackConfig {
impl PackConfig {
pub const DEFAULT_NAME: &'static str = "shulkerscript-pack";
pub const DEFAULT_DESCRIPTION: &'static str = "A Minecraft datapack created with shulkerscript";
pub const DEFAULT_PACK_FORMAT: u8 = 48;
pub const DEFAULT_PACK_FORMAT: u8 = shulkerbox::datapack::Datapack::LATEST_FORMAT;
}
impl Default for PackConfig {
@ -28,6 +31,7 @@ impl Default for PackConfig {
Self {
name: Self::DEFAULT_NAME.to_string(),
description: Self::DEFAULT_DESCRIPTION.to_string(),
main_namespace: None,
pack_format: Self::DEFAULT_PACK_FORMAT,
version: "0.1.0".to_string(),
}

View File

@ -11,8 +11,8 @@ pub enum Error {
NotDirectoryError(PathBuf),
#[error("An error occured because the path is neither a pack directory or a pack.toml file.")]
InvalidPackPathError(PathBuf),
#[error("An error occured because the feature {0} is not enabled.")]
FeatureNotEnabledError(String),
#[error("An error occured because {0} is not allowed as a namespace.")]
InvalidNamespaceError(String),
#[error("An error occured because the pack version does not support a used feature")]
IncompatiblePackVersionError,
}

View File

@ -1,3 +1,33 @@
//! This crate is the cli app of the Shulkerscript language for creating Minecraft datapacks.
//!
//! # Installation
//! ```bash
//! cargo install shulkerscript-cli
//! ```
//!
//! # Usage
//! An extended description of the commands can be found in the readme or by running `shulkerscript --help`.
//!
//! ### Initialize a new project
//! ```bash
//! shulkerscript init [OPTIONS] [PATH]
//! ```
//!
//! ### Build a project
//! ```bash
//! shulkerscript build [OPTIONS] [PATH]
//! ```
//!
//! ### Clean the output directory
//! ```bash
//! shulkerscript clean [OPTIONS] [PATH]
//! ```
//!
//! ### Watch for changes
//! ```bash
//! shulkerscript watch [OPTIONS] [PATH]
//! ```
pub mod cli;
pub mod config;
pub mod error;

View File

@ -2,15 +2,25 @@ use std::process::ExitCode;
use clap::Parser;
use shulkerscript_cli::{cli::Args, terminal_output::print_info};
use shulkerscript_cli::{cli::Cli, terminal_output::print_info};
fn main() -> ExitCode {
human_panic::setup_panic!();
human_panic::setup_panic!(human_panic::Metadata::new(
env!("CARGO_PKG_NAME"),
const_format::formatcp!(
"{cli_version};lib={lib_version}",
cli_version = env!("CARGO_PKG_VERSION"),
lib_version = shulkerscript::VERSION
),
)
.authors(env!("CARGO_PKG_AUTHORS").replace(":", ", "))
.homepage(env!("CARGO_PKG_HOMEPAGE")));
if dotenvy::dotenv().is_ok() {
print_info("Using environment variables from .env file");
}
let args = Args::parse();
let args = Cli::parse();
match args.run() {
Ok(_) => ExitCode::SUCCESS,

View File

@ -1,16 +1,18 @@
use anyhow::Result;
use path_absolutize::Absolutize;
use shulkerbox::{
util::compile::CompileOptions,
virtual_fs::{VFile, VFolder},
use shulkerscript::{
base::{FsProvider, PrintHandler},
shulkerbox::{
util::compile::CompileOptions,
virtual_fs::{VFile, VFolder},
},
};
use shulkerscript::base::FsProvider;
use crate::{
config::ProjectConfig,
error::Error,
terminal_output::{print_error, print_info, print_success, print_warning},
util,
util::{self, get_project_main_namespace},
};
use std::{
borrow::Cow,
@ -35,19 +37,19 @@ pub struct BuildArgs {
#[arg(short, long)]
pub assets: Option<PathBuf>,
/// Package the project to a zip file.
#[cfg(feature = "zip")]
#[arg(short, long)]
pub zip: bool,
/// Skip validating the project for pack format compatibility.
#[arg(long)]
pub no_validate: bool,
/// Check if the project can be built without actually building it.
#[arg(long, conflicts_with = "output")]
#[cfg_attr(feature = "zip", arg(conflicts_with = "zip"))]
pub check: bool,
}
pub fn build(args: &BuildArgs) -> Result<()> {
if args.zip && !cfg!(feature = "zip") {
print_error("The zip feature is not enabled. Please install with the `zip` feature enabled to use the `--zip` option.");
return Err(Error::FeatureNotEnabledError("zip".to_string()).into());
}
let path = util::get_project_path(&args.path).unwrap_or(args.path.clone());
let dist_path = args
.output
@ -55,7 +57,16 @@ pub fn build(args: &BuildArgs) -> Result<()> {
.map(Cow::Borrowed)
.unwrap_or_else(|| Cow::Owned(path.join("dist")));
let and_package_msg = if args.zip { " and packaging" } else { "" };
let zip = {
#[cfg(feature = "zip")]
{
args.zip
}
#[cfg(not(feature = "zip"))]
false
};
let and_package_msg = if zip { " and packaging" } else { "" };
let mut path_display = format!("{}", path.display());
if path_display.is_empty() {
@ -76,7 +87,14 @@ pub fn build(args: &BuildArgs) -> Result<()> {
)?;
let datapack = shulkerscript::transpile(
&PrintHandler::new(),
&FsProvider::default(),
&get_project_main_namespace(&project_config).map_err(|namespace| {
print_error(format!(
"The automatically generated namespace is too short: '{namespace}'. Please specify a namespace in the pack.toml file.",
));
Error::InvalidNamespaceError(namespace)
})?,
project_config.pack.pack_format,
&script_paths,
)?;
@ -127,31 +145,35 @@ pub fn build(args: &BuildArgs) -> Result<()> {
compiled
};
let dist_extension = if args.zip { ".zip" } else { "" };
let dist_extension = if zip { ".zip" } else { "" };
let dist_path = dist_path.join(project_config.pack.name + dist_extension);
#[cfg(feature = "zip")]
if args.zip {
output.zip_with_comment(
&dist_path,
format!(
"{} - v{}",
&project_config.pack.description, &project_config.pack.version
),
)?;
if args.check {
print_success("Project is valid and can be built.");
} else {
#[cfg(feature = "zip")]
if args.zip {
output.zip_with_comment(
&dist_path,
format!(
"{} - v{}",
&project_config.pack.description, &project_config.pack.version
),
)?;
} else {
output.place(&dist_path)?;
}
#[cfg(not(feature = "zip"))]
output.place(&dist_path)?;
print_success(format!(
"Finished building{and_package_msg} project to {}",
dist_path.absolutize_from(path)?.display()
));
}
#[cfg(not(feature = "zip"))]
output.place(&dist_path)?;
print_success(format!(
"Finished building{and_package_msg} project to {}",
dist_path.absolutize_from(path)?.display()
));
Ok(())
}
@ -183,7 +205,7 @@ fn _get_script_paths(path: &Path, prefix: &str) -> std::io::Result<Vec<(String,
prefix.to_string()
+ path
.file_stem()
.expect("ShulkerScript files are not allowed to have empty names")
.expect("Shulkerscript files are not allowed to have empty names")
.to_str()
.expect("Invalid characters in filename"),
path,

View File

@ -59,7 +59,7 @@ pub fn clean(args: &CleanArgs) -> Result<()> {
for delete_path in delete_paths {
if delete_path.exists() {
if verbose {
print_info(&format!("Deleting {:?}", delete_path));
print_info(format!("Deleting {:?}", delete_path));
}
if delete_path.is_file() {
std::fs::remove_file(&delete_path)?;

View File

@ -10,6 +10,7 @@ use clap::ValueEnum;
use git2::{
IndexAddOption as GitIndexAddOption, Repository as GitRepository, Signature as GitSignature,
};
use inquire::validator::Validation;
use path_absolutize::Absolutize;
use crate::{
@ -228,6 +229,11 @@ fn initialize_interactive(args: &InitArgs) -> Result<()> {
match inquire::Text::new("Enter the pack format:")
.with_help_message("This will determine the Minecraft version compatible with your pack, find more on the Minecraft wiki")
.with_default(PackConfig::DEFAULT_PACK_FORMAT.to_string().as_str())
.with_validator(|v: &str| Ok(
v.parse::<u8>()
.map(|_| Validation::Valid)
.unwrap_or(Validation::Invalid(
inquire::validator::ErrorMessage::Custom("Invalid pack format".to_string())))))
.prompt() {
Ok(res) => res.parse().ok(),
Err(_) => {
@ -270,8 +276,21 @@ fn initialize_interactive(args: &InitArgs) -> Result<()> {
"This will be the icon of your datapack, visible in the datapack selection screen [use \"-\" for default]",
)
.with_autocomplete(autocompleter)
.with_validator(|s: &str| {
if s == "-" {
Ok(Validation::Valid)
} else {
let path = Path::new(s);
if path.exists() && path.is_file() && path.extension().is_some_and(|ext| ext == "png") {
Ok(Validation::Valid)
} else {
Ok(Validation::Invalid(
inquire::validator::ErrorMessage::Custom("Invalid file path. Path must exist and point to a png".to_string()),
))
}
}
})
.with_default("-")
// .with_autocomplete()
.prompt()
{
Ok(res) if &res == "-" => None,

View File

@ -1,7 +1,7 @@
use clap::ValueEnum;
use anyhow::Result;
use shulkerscript::base::FsProvider;
use shulkerscript::base::{FsProvider, PrintHandler};
use std::path::PathBuf;
use crate::{config::PackConfig, util};
@ -26,6 +26,7 @@ pub enum DumpState {
Tokens,
#[default]
Ast,
#[value(alias = "dp")]
Datapack,
}
@ -33,7 +34,14 @@ pub fn lang_debug(args: &LangDebugArgs) -> Result<()> {
let file_provider = FsProvider::default();
match args.dump {
DumpState::Tokens => {
let tokens = shulkerscript::tokenize(&file_provider, &args.path)?;
let tokens = shulkerscript::tokenize(
&PrintHandler::new(),
&file_provider,
&args.path,
args.path.file_stem().map_or(String::from("main"), |s| {
s.to_string_lossy().into_owned().to_string()
}),
)?;
if args.pretty {
println!("{:#?}", tokens);
} else {
@ -41,7 +49,14 @@ pub fn lang_debug(args: &LangDebugArgs) -> Result<()> {
}
}
DumpState::Ast => {
let ast = shulkerscript::parse(&file_provider, &args.path)?;
let ast = shulkerscript::parse(
&PrintHandler::new(),
&file_provider,
&args.path,
args.path.file_stem().map_or(String::from("main"), |s| {
s.to_string_lossy().into_owned().to_string()
}),
)?;
if args.pretty {
println!("{:#?}", ast);
} else {
@ -55,7 +70,9 @@ pub fn lang_debug(args: &LangDebugArgs) -> Result<()> {
.join("src"),
)?;
let datapack = shulkerscript::transpile(
&PrintHandler::new(),
&file_provider,
"main_namespace",
PackConfig::DEFAULT_PACK_FORMAT,
&program_paths,
)?;

379
src/subcommands/migrate.rs Normal file
View File

@ -0,0 +1,379 @@
use anyhow::Result;
use path_absolutize::Absolutize as _;
use shulkerscript::shulkerbox::virtual_fs::{VFile, VFolder};
use std::{
borrow::Cow,
fs::{self, File},
io::BufReader,
path::{Path, PathBuf},
};
use walkdir::WalkDir;
use crate::{
terminal_output::{print_error, print_info, print_success},
util::Relativize as _,
};
#[derive(Debug, clap::Args, Clone)]
#[command(allow_missing_positional = true)]
pub struct MigrateArgs {
/// The path of the project to migrate.
#[arg(default_value = ".")]
pub path: PathBuf,
/// The path of the folder to create the Shulkerscript project.
pub target: PathBuf,
/// Force migration even if some features will be lost.
#[arg(short, long)]
pub force: bool,
}
pub fn migrate(args: &MigrateArgs) -> Result<()> {
let base_path = args.path.as_path();
let base_path = if base_path.is_absolute() {
Cow::Borrowed(base_path)
} else {
base_path.absolutize().unwrap_or(Cow::Borrowed(base_path))
}
.ancestors()
.find(|p| p.join("pack.mcmeta").exists())
.map(|p| p.relativize().unwrap_or_else(|| p.to_path_buf()));
if let Some(base_path) = base_path {
print_info(format!(
"Migrating from {:?} to {:?}",
base_path, args.target
));
let mcmeta_path = base_path.join("pack.mcmeta");
let mcmeta: serde_json::Value =
serde_json::from_reader(BufReader::new(fs::File::open(&mcmeta_path)?))?;
if !args.force && !is_mcmeta_compatible(&mcmeta) {
print_error("Your datapack uses features in the pack.mcmeta file that are not yet supported by Shulkerscript.");
print_error(
r#""features", "filter", "overlays" and "language" will get lost if you continue."#,
);
print_error("Use the force flag to continue anyway.");
return Err(anyhow::anyhow!("Incompatible mcmeta."));
}
let mcmeta = serde_json::from_value::<McMeta>(mcmeta)?;
let mut root = VFolder::new();
root.add_file("pack.toml", generate_pack_toml(&base_path, &mcmeta)?);
let data_path = base_path.join("data");
if data_path.exists() && data_path.is_dir() {
for namespace in data_path.read_dir()? {
let namespace = namespace?;
if namespace.file_type()?.is_dir() {
handle_namespace(&mut root, &namespace.path())?;
}
}
} else {
print_error("Could not find a data folder.");
}
root.place(&args.target)?;
let logo_path = base_path.join("pack.png");
if logo_path.exists() {
fs::copy(logo_path, args.target.join("pack.png"))?;
}
print_success("Migration successful.");
Ok(())
} else {
let msg = format!(
"Could not find a valid datapack to migrate at {}.",
args.path.display()
);
print_error(&msg);
Err(anyhow::anyhow!("{}", &msg))
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
struct McMeta {
pack: McMetaPack,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
struct McMetaPack {
description: String,
pack_format: u8,
}
fn is_mcmeta_compatible(mcmeta: &serde_json::Value) -> bool {
mcmeta.as_object().is_some_and(|mcmeta| {
mcmeta.len() == 1
&& mcmeta.contains_key("pack")
&& mcmeta["pack"]
.as_object()
.is_some_and(|pack| !pack.contains_key("supported_formats"))
})
}
fn generate_pack_toml(base_path: &Path, mcmeta: &McMeta) -> Result<VFile> {
// check if there are any directories in namespaces other than `functions`, `function` and `tags`
let mut err = false;
let requires_assets_dir = base_path.join("data").read_dir()?.any(|entry_i| {
if let Ok(entry_i) = entry_i {
if let Ok(metadata_i) = entry_i.metadata() {
metadata_i.is_dir()
&& entry_i
.path()
.read_dir()
.map(|mut dir| {
dir.any(|entry_ii| {
if let Ok(entry_ii) = entry_ii {
["functions", "function", "tags"]
.contains(&entry_ii.file_name().to_string_lossy().as_ref())
} else {
err = true;
true
}
})
})
.inspect_err(|_| {
err = true;
})
.unwrap_or_default()
} else {
err = true;
true
}
} else {
err = true;
true
}
});
if err {
print_error("Error reading data directory");
return Err(anyhow::anyhow!("Error reading data directory"));
}
let assets_dir_fragment = requires_assets_dir.then(|| {
toml::toml! {
[compiler]
assets = "./assets"
}
});
let name = base_path
.absolutize()?
.file_name()
.expect("No file name")
.to_string_lossy()
.into_owned();
let description = mcmeta.pack.description.as_str();
let pack_format = mcmeta.pack.pack_format;
let main_fragment = toml::toml! {
[pack]
name = name
description = description
format = pack_format
version = "0.1.0"
};
let assets_dir_fragment_text = assets_dir_fragment
.map(|fragment| toml::to_string_pretty(&fragment))
.transpose()?;
// stringify the toml fragments and add them to the pack.toml file
toml::to_string_pretty(&main_fragment)
.map(|mut text| {
if let Some(assets_dir_fragment_text) = assets_dir_fragment_text {
text.push('\n');
text.push_str(&assets_dir_fragment_text);
}
VFile::Text(text)
})
.map_err(|e| e.into())
}
fn handle_namespace(root: &mut VFolder, namespace: &Path) -> Result<()> {
let namespace_name = namespace
.file_name()
.expect("path cannot end with ..")
.to_string_lossy();
// migrate all subfolders of namespace
for subfolder in namespace.read_dir()? {
let subfolder = subfolder?;
if !subfolder.file_type()?.is_dir() {
continue;
}
let filename = subfolder.file_name();
let filename = filename.to_string_lossy();
if ["function", "functions"].contains(&filename.as_ref()) {
// migrate functions
for entry in WalkDir::new(subfolder.path()).min_depth(1) {
let entry = entry?;
if entry.file_type().is_file()
&& entry.path().extension().unwrap_or_default() == "mcfunction"
{
handle_function(root, namespace, &namespace_name, entry.path())?;
}
}
} else if filename.as_ref() == "tags" {
// migrate tags
for tag_type in subfolder.path().read_dir()? {
handle_tag_type_dir(root, &namespace_name, &tag_type?.path())?;
}
} else {
// copy all other files to the asset folder
let vfolder = VFolder::try_from(subfolder.path().as_path())?;
root.add_existing_folder(&format!("assets/data/{namespace_name}/{filename}"), vfolder);
}
}
Ok(())
}
fn handle_function(
root: &mut VFolder,
namespace: &Path,
namespace_name: &str,
function: &Path,
) -> Result<()> {
let function_path = pathdiff::diff_paths(function, namespace.join("function"))
.expect("function path is always a subpath of namespace/function")
.to_string_lossy()
.replace('\\', "/");
let function_path = function_path
.trim_start_matches("./")
.trim_end_matches(".mcfunction");
// indent lines and prefix comments with `///` and commands with `/`
let content = fs::read_to_string(function)?
.lines()
.map(|l| {
if l.trim_start().starts_with('#') {
format!(" {}", l.replacen('#', "///", 1))
} else if l.is_empty() {
String::new()
} else {
format!(" /{}", l)
}
})
.collect::<Vec<_>>()
.join("\n");
let function_name = function_path
.split('/')
.next_back()
.expect("split always returns at least one element")
.replace(|c: char| !c.is_ascii_alphanumeric(), "_");
// generate the full content of the function file
let full_content = indoc::formatdoc!(
r#"// This file was automatically migrated by Shulkerscript CLI v{version} from file "{function}"
namespace "{namespace_name}";
#[deobfuscate = "{function_path}"]
fn {function_name}() {{
{content}
}}
"#,
version = env!("CARGO_PKG_VERSION"),
function = function.display()
);
root.add_file(
&format!("src/functions/{namespace_name}/{function_path}.shu"),
VFile::Text(full_content),
);
Ok(())
}
fn handle_tag_type_dir(root: &mut VFolder, namespace: &str, tag_type_dir: &Path) -> Result<()> {
let tag_type = tag_type_dir
.file_name()
.expect("cannot end with ..")
.to_string_lossy();
// loop through all tag files in the tag type directory
for entry in WalkDir::new(tag_type_dir).min_depth(1) {
let entry = entry?;
if entry.file_type().is_file() && entry.path().extension().unwrap_or_default() == "json" {
handle_tag(root, namespace, tag_type_dir, &tag_type, entry.path())?;
}
}
Ok(())
}
fn handle_tag(
root: &mut VFolder,
namespace: &str,
tag_type_dir: &Path,
tag_type: &str,
tag: &Path,
) -> Result<()> {
let tag_path = pathdiff::diff_paths(tag, tag_type_dir)
.expect("tag path is always a subpath of tag_type_dir")
.to_string_lossy()
.replace('\\', "/");
let tag_path = tag_path.trim_start_matches("./").trim_end_matches(".json");
if let Ok(content) = serde_json::from_reader::<_, Tag>(BufReader::new(File::open(tag)?)) {
// generate "of <type>" if the tag type is not "function"
let of_type = if tag_type == "function" {
String::new()
} else {
format!(r#" of "{tag_type}""#)
};
let replace = if content.replace { " replace" } else { "" };
// indent, quote and join the values
let values = content
.values
.iter()
.map(|t| format!(r#" "{t}""#))
.collect::<Vec<_>>()
.join(",\n");
let generated = indoc::formatdoc!(
r#"// This file was automatically migrated by Shulkerscript CLI v{version} from file "{tag}"
namespace "{namespace}";
tag "{tag_path}"{of_type}{replace} [
{values}
]
"#,
version = env!("CARGO_PKG_VERSION"),
tag = tag.display(),
);
root.add_file(
&format!("src/tags/{namespace}/{tag_type}/{tag_path}.shu"),
VFile::Text(generated),
);
Ok(())
} else {
print_error(format!(
"Could not read tag file at {}. Required attribute of entries is not yet supported",
tag.display()
));
Err(anyhow::anyhow!(
"Could not read tag file at {}",
tag.display()
))
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
struct Tag {
#[serde(default)]
replace: bool,
values: Vec<String>,
}

View File

@ -7,12 +7,17 @@ pub use build::{build, BuildArgs};
mod clean;
pub use clean::{clean, CleanArgs};
#[cfg(feature = "watch")]
mod watch;
#[cfg(feature = "watch")]
pub use watch::{watch, WatchArgs};
#[cfg(feature = "lang-debug")]
mod lang_debug;
#[cfg(feature = "lang-debug")]
pub use lang_debug::{lang_debug, LangDebugArgs};
#[cfg(feature = "migrate")]
mod migrate;
#[cfg(feature = "migrate")]
pub use migrate::{migrate, MigrateArgs};
#[cfg(feature = "watch")]
mod watch;
#[cfg(feature = "watch")]
pub use watch::{watch, WatchArgs};

View File

@ -11,7 +11,7 @@ use colored::Colorize;
use notify_debouncer_mini::{new_debouncer, notify::*, DebounceEventResult};
use crate::{
cli::Args,
cli::Cli,
error::Result,
terminal_output::{print_error, print_info, print_warning},
util,
@ -74,7 +74,7 @@ pub fn watch(args: &WatchArgs) -> Result<()> {
let prog_name = std::env::args()
.next()
.unwrap_or(env!("CARGO_PKG_NAME").to_string());
Args::parse_from(iter::once(prog_name.as_str()).chain(split.clone()))
Cli::parse_from(iter::once(prog_name.as_str()).chain(split.clone()))
})
.collect::<Vec<_>>();
@ -168,7 +168,7 @@ pub fn watch(args: &WatchArgs) -> Result<()> {
}
}
fn run_cmds(cmds: &[Args], no_execute: bool, shell_cmds: &[String], initial: bool) {
fn run_cmds(cmds: &[Cli], no_execute: bool, shell_cmds: &[String], initial: bool) {
if initial {
print_info("Running commands initially...");
} else {

View File

@ -5,11 +5,11 @@ use std::{
path::{Path, PathBuf},
};
use camino::Utf8PathBuf;
use inquire::{autocompletion::Replacement, Autocomplete};
use path_absolutize::Absolutize;
use crate::config::ProjectConfig;
pub fn get_project_path<P>(base_path: P) -> Option<PathBuf>
where
P: AsRef<Path>,
@ -22,15 +22,45 @@ where
}
.ancestors()
.find(|p| p.join("pack.toml").exists())
.map(|p| relativize(p).unwrap_or_else(|| p.to_path_buf()))
.map(|p| p.relativize().unwrap_or_else(|| p.to_path_buf()))
}
pub fn relativize<P>(path: P) -> Option<PathBuf>
pub fn get_project_main_namespace(project_config: &ProjectConfig) -> Result<String, String> {
project_config
.pack
.main_namespace
.as_ref()
.cloned()
.map_or_else(
|| {
let namespace = project_config
.pack
.name
.to_lowercase()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
.collect::<String>();
if namespace.len() < 5 {
Err(namespace)
} else {
Ok(namespace)
}
},
Ok,
)
}
pub trait Relativize {
fn relativize(&self) -> Option<PathBuf>;
}
impl<P> Relativize for P
where
P: AsRef<Path>,
{
let cwd = env::current_dir().ok()?;
pathdiff::diff_paths(path, cwd)
fn relativize(&self) -> Option<PathBuf> {
let cwd = env::current_dir().ok()?;
pathdiff::diff_paths(self, cwd)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@ -68,17 +98,20 @@ impl PathAutocomplete {
if !self.cache.contains_key(parent) {
tracing::trace!("Cache miss for \"{}\", reading dir", parent);
let parent_path = Utf8PathBuf::from(parent);
let parent_path = PathBuf::from(parent);
if !parent_path.exists() || !parent_path.is_dir() {
return Err("Path does not exist");
}
let entries = parent_path
.read_dir_utf8()
.read_dir()
.map_err(|_| "Could not read dir")?
.filter_map(|entry| {
entry.ok().map(|entry| {
entry.file_name().to_string() + if entry.path().is_dir() { "/" } else { "" }
entry.ok().and_then(|entry| {
Some(
entry.file_name().into_string().ok()?.to_string()
+ if entry.path().is_dir() { "/" } else { "" },
)
})
})
.collect::<Vec<_>>();
@ -134,7 +167,7 @@ impl Autocomplete for PathAutocomplete {
} else if let Some(first) = self
.get_cached(parent)?
.iter()
.find(|entry| entry.starts_with(current))
.find(|entry| current.is_empty() || entry.starts_with(current))
{
let completion = format!("{parent}/{first}");
self.update_input(&completion)?;