From be51ce036f8d5c935a5bb2d21768831a4efd0d17 Mon Sep 17 00:00:00 2001 From: I'm Liam Date: Fri, 13 Jul 2018 22:19:43 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20Initial=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .editorconfig | 15 ++ .gitattributes | 11 ++ .gitignore | 6 + .scrutinizer.yml | 18 +++ .styleci.yml | 5 + CHANGELOG.md | 7 + CONTRIBUTING.md | 47 ++++++ LICENSE.md | 21 +++ README.md | 86 +++++++++++ composer.json | 40 +++++ src/EnvironmentSetCommand.php | 147 +++++++++++++++++++ src/EnvironmentSetCommandServiceProvider.php | 28 ++++ 12 files changed, 431 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .scrutinizer.yml create mode 100644 .styleci.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 src/EnvironmentSetCommand.php create mode 100644 src/EnvironmentSetCommandServiceProvider.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cd8eb86 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bb6265e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/.scrutinizer.yml export-ignore +/tests export-ignore +/.editorconfig export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f006265 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build +composer.lock +docs +vendor +coverage +SCRATCH.md diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..1165e72 --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,18 @@ +filter: + excluded_paths: [tests/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true diff --git a/.styleci.yml b/.styleci.yml new file mode 100644 index 0000000..3f78bdd --- /dev/null +++ b/.styleci.yml @@ -0,0 +1,5 @@ +preset: laravel + +disabled: + - single_class_element_per_statement + - self_accessor diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4713a2b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `laravel-env-set-command` will be documented in this file + +## 1.0.0 - 2018-07-13 + +- Initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9cec6f1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skill sets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..77601c2 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Liam Hammett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f85839e --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# Laravel `set:env` Command + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/imliam/laravel-env-set-command.svg)](https://packagist.org/packages/imliam/laravel-env-set-command) +[![Total Downloads](https://img.shields.io/packagist/dt/imliam/laravel-env-set-command.svg)](https://packagist.org/packages/imliam/laravel-env-set-command) +[![License](https://img.shields.io/github/license/imliam/laravel-env-set-command.svg)](LICENSE.md) + +Set a .env file variable from the command line. + + + +- [Laravel `set:env` Command](#laravel-setenv-command) + - [Installation](#installation) + - [Usage](#usage) + - [Changelog](#changelog) + - [Contributing](#contributing) + - [Security](#security) + - [Credits](#credits) + - [License](#license) + + + +## Installation + +You can install the package with [Composer](https://getcomposer.org/) using the following command: + +```bash +composer require imliam/laravel-env-set-command:^1.0.0 +``` + +## Usage + +When running the `env:set` artisan command, you must provide both a key and value as two arguments. + +```bash +$ php artisan env:set app_name Example +# Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'Example' +``` + +You can also set values with spaces by wrapping them in quotes. + +```bash +$ php artisan env:set app_name "Example App" +# Environment variable with key 'APP_NAME' has been changed from 'Laravel' to '"Example App"' +``` + +The command will also create new environment variables if an existing one does not exist. + +```bash +$ php artisan env:set editor=vscode +# Environment variable with key 'EDITOR' has been set to 'vscode' +``` + +Instead of two arguments split by a space, you can also mimic the `.env` file format by supplying `KEY=VALUE`. + +```bash +$ php artisan env:set app_name=Example +# Environment variable with key 'APP_NAME' has been changed from 'Laravel' to 'Example' +``` + +The command will do its best to stop any invalid inputs. + +```bash +$ php artisan env:set @pp_n@me Laravel +# Invalid environment key. Only use letters and underscores +``` + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +### Security + +If you discover any security related issues, please email liam@liamhammett.com instead of using the issue tracker. + +## Credits + +- [Liam Hammett](https://github.com/imliam) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..2bff4a1 --- /dev/null +++ b/composer.json @@ -0,0 +1,40 @@ +{ + "name": "imliam/laravel-env-set-command", + "description": "Set a .env file variable from the command line", + "keywords": [ + "imliam", + "laravel-env-set-command", + "environment", + "variables", + "env", + "artisan" + ], + "homepage": "https://github.com/imliam/laravel-env-set-command", + "license": "MIT", + "authors": [ + { + "name": "Liam Hammett", + "email": "liam@liamhammett.com", + "homepage": "https://liamhammett.com", + "role": "Developer" + } + ], + "require": { + "php": "^7.1" + }, + "autoload": { + "psr-4": { + "ImLiam\\EnvironmentSetCommand\\": "src" + } + }, + "config": { + "sort-packages": true + }, + "extra": { + "laravel": { + "providers": [ + "ImLiam\\EnvironmentSetCommand\\EnvironmentSetCommandServiceProvider" + ] + } + } +} diff --git a/src/EnvironmentSetCommand.php b/src/EnvironmentSetCommand.php new file mode 100644 index 0000000..ea6b7e1 --- /dev/null +++ b/src/EnvironmentSetCommand.php @@ -0,0 +1,147 @@ +getKeyValue(); + } catch (\InvalidArgumentException $e) { + return $this->error($e->getMessage()); + } + + $envFilePath = app()->environmentFilePath(); + $contents = file_get_contents($envFilePath); + + if ($oldValue = $this->getOldValue($contents, $key)) { + $contents = str_replace("{$key}={$oldValue}", "{$key}={$value}", $contents); + $this->writeFile($envFilePath, $contents); + + return $this->info("Environment variable with key '{$key}' has been changed from '{$oldValue}' to '{$value}'"); + } + + $contents = $contents . "\n{$key}={$value}\n"; + $this->writeFile($envFilePath, $contents); + + return $this->info("A new environment variable with key '{$key}' has been set to '{$value}'"); + } + + /** + * Overwrite the contents of a file. + * + * @param string $path + * @param string $contents + * @return boolean + */ + protected function writeFile(string $path, string $contents): bool + { + $file = fopen($path, 'w'); + fwrite($file, $contents); + + return fclose($file); + } + + /** + * Get the old value of a given key from an environment file. + * + * @param string $envFile + * @param string $key + * @return string + */ + protected function getOldValue(string $envFile, string $key): string + { + // Match the given key at the beginning of a line + preg_match("/^{$key}=[^\r\n]*/m", $envFile, $matches); + + if (count($matches)) { + return substr($matches[0], strlen($key) + 1); + } + + return ''; + } + + /** + * Determine what the supplied key and value is from the current command. + * + * @return array + */ + protected function getKeyValue(): array + { + $key = $this->argument('key'); + $value = $this->argument('value'); + + if (! $value) { + $parts = explode('=', $key, 2); + + if (count($parts) !== 2) { + throw new InvalidArgumentException('No value was set'); + } + + $key = $parts[0]; + $value = $parts[1]; + } + + if (! $this->isValidKey($key)) { + throw new InvalidArgumentException('Invalid argument key'); + } + + if (! is_bool(strpos($value, ' '))) { + $value = '"' . $value . '"'; + } + + return [strtoupper($key), $value]; + } + + /** + * Check if a given string is valid as an environment variable key. + * + * @param string $key + * @return boolean + */ + protected function isValidKey(string $key): bool + { + if (str_contains($key, '=')) { + throw new InvalidArgumentException("Environment key should not contain '='"); + } + + if (!preg_match('/^[a-zA-Z_]+$/', $key)) { + throw new InvalidArgumentException('Invalid environment key. Only use letters and underscores'); + } + + return true; + } +} diff --git a/src/EnvironmentSetCommandServiceProvider.php b/src/EnvironmentSetCommandServiceProvider.php new file mode 100644 index 0000000..706ba0c --- /dev/null +++ b/src/EnvironmentSetCommandServiceProvider.php @@ -0,0 +1,28 @@ +app->bind('command.env:set', EnvironmentSetCommand::class); + + $this->commands([ + 'command.env:set' + ]); + } +}