symfony api rest bundle
librerias a instalar:
composer require friendsofsymfony/rest-bundle
composer require jms/serializer-bundle
habilitarlos:
new FOS\RestBundle\FOSRestBundle(),
new JMS\SerializerBundle\JMSSerializerBundle(),
para efectos de orden y no poner todo en el AppBundle voy a crear un bundle nuevo en donde manejare los controladores de la api
por consola:
php bin/console generate:bundle
llamemosle p.e ApiRestBundle
actualizar composer.json
en eclipse:
abrir composer.json ir a la pestaña de "autoload"
en el panel de psr-4 click en add ,
en el cuadro de dialogo
namespace: ApiRestBundle\
y en paths seleccionar el floder src/ApiRestBundle
luego por consola ejecutar:
composer dump-autoload
el comando de creacion de bundle
lo agrega automaticamente al AppKernel.php
y tambien genera una entrada en routing.yml
editemos el prefix en el routing, para que las llamadas sean precedidas por "api" entonces quedaria asi:
api_rest:
resource: "@ApiRestBundle/Controller/"
type: annotation
prefix: /api
en config.yml
# JMS serializer configuration
jms_serializer:
metadata:
auto_detection: true
handlers:
datetime:
default_format: 'Y-m-d H:i:s'
# FOSRest Configuration
fos_rest:
body_listener: true
format_listener:
rules:
- { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }
- { path: ^/, priorities: [ html ], fallback_format: html, prefer_extension: true }
param_fetcher_listener: true
view:
view_response_listener: 'force'
formats:
json: true
se asume que se tiene ya una entidad creada en src/AppBundle/Entity
y su correspondiente repository en src/AppBundle/Repository
por ejemplo para Nota.php existe NotaRepository.php (que extiende de \Doctrine\ORM\EntityRepository)
en src/ApiRestBundle/Controller
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
class NotasController extends FOSRestController
{
/**
* @Route("/notas")
* @Method("GET")
*/
public function getAction()
{
$restresult = $this->getDoctrine()->getRepository('AppBundle:Nota')->findAll();
if ($restresult === null)
{
return new View("there are no notas exist", Response::HTTP_NOT_FOUND);
}
return $restresult;
}
}
y listo!
para probar, se puede abriri Postman
y en la url escribir:
http://localhost/api-test/web/app_dev.php/api/notas
deberia devolver algo asi:
[ { "id": 1, "titulo": "prueba", "contenido": "<p>lalalala</p>\r\n\r\n<p><strong>jojoj</strong></p>\r\n\r\n<p><strong>fefefe</strong></p>\r\n\r\n<ol>\r\n\t<li><strong>kakaka</strong></li>\r\n\t<li>huhuhuh</li>\r\n</ol>", "imagen": "24955519_922259481269966_842653723684610281_o.jpg", "esta_activo": true, "posicion": 2, "updated_at": "2017-12-14 04:10:23", "created_at": "2017-12-14 04:10:23" }, { "id": 2, "titulo": "otra prueba", "contenido": "<p>jajajaa</p>", "imagen": "160718114905-03-mind-of-bruce-lee-super-tease.jpg", "esta_activo": false, "posicion": 1, "updated_at": "2017-12-14 04:17:47", "created_at": "2017-12-14 04:17:47" } ]
fuentes:
http://www.phpbuilder.com/articles/tools/frameworks/creating-a-rest-api-in-symfony-3.html
https://jeremycurny.com/2016/03/27/symfony3-rest-api/
http://orgullo.users.sourceforge.net/blog/?p=406
https://www.cloudways.com/blog/rest-api-in-symfony-3-1/
ver
https://gist.github.com/diegonobre/341eb7b793fc841c0bba3f2b865b8d66
easyadmin symfony setear campo updatedAt para todas las entidades
crear // src/AppBundle/Controller/AdminController.php
class AdminController extends BaseAdminController
{
public function preUpdateEntity($entity)
{
if (method_exists($entity, 'setUpdatedAt')) {
$entity->setUpdatedAt(new \DateTime());
}
}
en routing.yml
easy_admin_bundle:
resource: '@AppBundle/Controller/AdminController.php'
class AdminController extends BaseAdminController
{
public function preUpdateEntity($entity)
{
if (method_exists($entity, 'setUpdatedAt')) {
$entity->setUpdatedAt(new \DateTime());
}
}
en routing.yml
easy_admin_bundle:
resource: '@AppBundle/Controller/AdminController.php'
symfony eliminar un bundle
1) quitarlo de AppKernel
2) en config.yml quitar cualquier referencia
3) en composer.json quitar la linea del require.
4) ejecutar composer update, esto borra la carpeta del bundle del directorio de vendor
2) en config.yml quitar cualquier referencia
3) en composer.json quitar la linea del require.
4) ejecutar composer update, esto borra la carpeta del bundle del directorio de vendor
easyadmin cfkeditor
siguiendo las intrucciones de instalacion del bundle cfkeditor
php bin/console ckeditor:install
no hace nada.
asi que continuar con el sgt paso
php bin/console assets:install --symlink
luego ir al archivo
vendor\egeloen\ckeditor-bundle\DependencyInjection\Compiler\ResourceCompilerPass.php
ir a la linea #43
y donde dice
IvoryCKEditorBundle:Form:ckeditor_widget.html.twig
cambiarla por
@IvoryCKEditor/Form/ckeditor_widget.html.twig
y listo.
limpiar la cache
php bin/console ckeditor:install
no hace nada.
asi que continuar con el sgt paso
php bin/console assets:install --symlink
luego ir al archivo
vendor\egeloen\ckeditor-bundle\DependencyInjection\Compiler\ResourceCompilerPass.php
ir a la linea #43
y donde dice
IvoryCKEditorBundle:Form:ckeditor_widget.html.twig
cambiarla por
@IvoryCKEditor/Form/ckeditor_widget.html.twig
y listo.
limpiar la cache
subir aplicacion symfony cpanel
luego de subir el sitio
ir a var/cache/prod
y borrar todo el contenido
ir a var/cache/prod
y borrar todo el contenido
symfony3.3 set charset utf8
si usas xampp:
ir a C:\xampp719\mysql\bin\my.ini
y en
[mnysqld] agregar las sgts lineas:
[mysqld] # Version 5.5.3 introduced "utf8mb4", which is recommended collation-server = utf8mb4_unicode_ci # Replaces utf8_unicode_ci character-set-server = utf8mb4 # Replaces utf8
aumentar memory limit
en php.ini
upload_max_filesize = 1000M
post_max_size = 2000M
memory_limit = 3000M
file_uploads = On
max_execution_time = 180
https://premium.wpmudev.org/blog/increase-memory-limit/
upload_max_filesize = 1000M
post_max_size = 2000M
memory_limit = 3000M
file_uploads = On
max_execution_time = 180
https://premium.wpmudev.org/blog/increase-memory-limit/
crear un dump de una base de datos en unix
desde el shell (no desde consola mysql)
mysqldump -u root -p mi_base_de_datos > dump.sql
simular symfony 4 con 3.4
composer create-project -s beta symfony/skeleton:3.4.x demo34
listo.
http://localhost/demo34/public/
listo.
http://localhost/demo34/public/
symfony4 easyadmin login
-crear la entidad User que implemente la interfaz UserInterface
-en config/packages/security.yaml
security:
encoders:
App\Entity\User:
algorithm: bcrypt
cost: 12
providers:
users:
entity:
class: App:User
property: email #esto es para que el logueo se haga por el email
firewalls:
main:
anonymous: ~
form_login:
username_parameter: _email #esto es para que el logueo se haga por el email
login_path: login
check_path: login
provider: users
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/*, roles: ROLE_ADMIN }
en este caso estamos dando acceso al sitio sólo a los usuarios que tengan el rol ROLE_ADMIN
salvo para el caso de login
-en config/routes.yaml
crear la ruta para logout
logout:
path: /logout
-en config/packages/framework.yaml
habilitar la session
framework:
secret: '%env(APP_SECRET)%'
session:
# The native PHP session handler will be used
handler_id: ~
-crear el controlador que manejará el login
App\Controller\SecurityController
/**
* @Route("/login", name="login")
* @param Request $request
* @param AuthenticationUtils $authUtils
* @return Response
*/
public function loginAction(Request $request, AuthenticationUtils $authUtils)
{
// get the login error if there is one
$error = $authUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
-crear la vista template/security/login.html.twig
{% extends '@EasyAdmin/default/layout.html.twig' %}
{% block header_custom_menu %}
{% endblock header_custom_menu %}
{% block sidebar %}
<section class="sidebar">
</section>
{% endblock sidebar %}
{% block content %}
<div class="container">
<div class="row">
{% if error %}
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><i class="zmdi-close"></i></button>
{{ error.messageKey|trans(error.messageData, 'security') }}
</div>
{% endif %}
<div class="col-xs-12">
<h1>Login</h1>
<form action="{{ path('login') }}" method="post">
<div class="form-group">
<!-- label for="username" class="control-label required">Username:</label-->
<!-- input type="text" id="username" name="_username" value="{{ last_username }}" /-->
<label for="email" class="control-label required">Email:</label>
<input type="text" id="email" name="_email" value="{{ last_username }}" />
</div>
<div class="form-group">
<label for="password" class="control-label required">Password:</label>
<input type="password" id="password" name="_password" />
</div>
<button type="submit" class="btn btn-primary">login</button>
</form>
</div>
</div>
</div>
{% endblock %}
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid('', true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return array('ROLE_ADMIN');
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
public function getId() {
return $this->id;
}
public function setUsername($username) {
$this->username = $username;
return $this;
}
public function setPassword($password) {
$this->password = $password;
return $this;
}
public function getEmail() {
return $this->email;
}
public function setEmail($email) {
$this->email = $email;
return $this;
}
public function getIsActive() {
return $this->isActive;
}
public function setIsActive($isActive) {
$this->isActive = $isActive;
return $this;
}
}
voy a insertar un usuario inicial,
pero como necesito saber cual es el password codificado, utilizo el siguiente comando:
php bin/console security:encode-password
e ingreso el password que le quiero asignar.
por ejemplo para "admin"
me devuelve el siguiente password "$2y$12$c6FDDMJQl/AfflUe4.U74OPb1SLKUyJ.eGoRDiR8f6eVCNcTJOk4a"
entonces en la migration agrego la siguiente linea de insercion:
insert into user(username,email,password) values("israel bazan","israelbazan76@gmail.com",$2y$12$c6FDDMJQl/AfflUe4.U74OPb1SLKUyJ.eGoRDiR8f6eVCNcTJOk4a);
-en config/packages/security.yaml
security:
encoders:
App\Entity\User:
algorithm: bcrypt
cost: 12
providers:
users:
entity:
class: App:User
property: email #esto es para que el logueo se haga por el email
firewalls:
main:
anonymous: ~
form_login:
username_parameter: _email #esto es para que el logueo se haga por el email
login_path: login
check_path: login
provider: users
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/*, roles: ROLE_ADMIN }
en este caso estamos dando acceso al sitio sólo a los usuarios que tengan el rol ROLE_ADMIN
salvo para el caso de login
-en config/routes.yaml
crear la ruta para logout
logout:
path: /logout
-en config/packages/framework.yaml
habilitar la session
framework:
secret: '%env(APP_SECRET)%'
session:
# The native PHP session handler will be used
handler_id: ~
-crear el controlador que manejará el login
App\Controller\SecurityController
/**
* @Route("/login", name="login")
* @param Request $request
* @param AuthenticationUtils $authUtils
* @return Response
*/
public function loginAction(Request $request, AuthenticationUtils $authUtils)
{
// get the login error if there is one
$error = $authUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authUtils->getLastUsername();
return $this->render('security/login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
-crear la vista template/security/login.html.twig
{% extends '@EasyAdmin/default/layout.html.twig' %}
{% block header_custom_menu %}
{% endblock header_custom_menu %}
{% block sidebar %}
<section class="sidebar">
</section>
{% endblock sidebar %}
{% block content %}
<div class="container">
<div class="row">
{% if error %}
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><i class="zmdi-close"></i></button>
{{ error.messageKey|trans(error.messageData, 'security') }}
</div>
{% endif %}
<div class="col-xs-12">
<h1>Login</h1>
<form action="{{ path('login') }}" method="post">
<div class="form-group">
<!-- label for="username" class="control-label required">Username:</label-->
<!-- input type="text" id="username" name="_username" value="{{ last_username }}" /-->
<label for="email" class="control-label required">Email:</label>
<input type="text" id="email" name="_email" value="{{ last_username }}" />
</div>
<div class="form-group">
<label for="password" class="control-label required">Password:</label>
<input type="password" id="password" name="_password" />
</div>
<button type="submit" class="btn btn-primary">login</button>
</form>
</div>
</div>
</div>
{% endblock %}
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", length=64)
*/
private $password;
/**
* @ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid('', true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return array('ROLE_ADMIN');
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
public function getId() {
return $this->id;
}
public function setUsername($username) {
$this->username = $username;
return $this;
}
public function setPassword($password) {
$this->password = $password;
return $this;
}
public function getEmail() {
return $this->email;
}
public function setEmail($email) {
$this->email = $email;
return $this;
}
public function getIsActive() {
return $this->isActive;
}
public function setIsActive($isActive) {
$this->isActive = $isActive;
return $this;
}
}
voy a insertar un usuario inicial,
pero como necesito saber cual es el password codificado, utilizo el siguiente comando:
php bin/console security:encode-password
e ingreso el password que le quiero asignar.
por ejemplo para "admin"
me devuelve el siguiente password "$2y$12$c6FDDMJQl/AfflUe4.U74OPb1SLKUyJ.eGoRDiR8f6eVCNcTJOk4a"
entonces en la migration agrego la siguiente linea de insercion:
insert into user(username,email,password) values("israel bazan","israelbazan76@gmail.com",$2y$12$c6FDDMJQl/AfflUe4.U74OPb1SLKUyJ.eGoRDiR8f6eVCNcTJOk4a);
easyadmin demo
EasyAdmin Demo
A Symfony demo backend to show EasyAdmin features.
How to install this project
git clone https://github.com/javiereguiluz/easy-admin-demo
cd easy-admin-demo
composer install
- Edit
app/config/parameters.yml
and configure credentials to acces a database for this demo. php bin/console doctrine:database:create
php bin/console doctrine:schema:create
php bin/console doctrine:fixtures:load --append
php bin/console assets:install --symlink
php bin/console server:run
- Browse
http://127.0.0.1:8000/admin/
para ingresar asi:
http://localhost/easy-admin-demo/public
en config/routes.yaml
backend:
resource: '../src/Controller/'
type: annotation
en config/packages/doctrine.yaml
doctrine:
dbal:
default_connection: default
connections:
# A collection of different named connections (e.g. default, conn2, etc)
default:
driver: pdo_mysql
dbname: easy-admin-demo-db
host: localhost
port: 3306
user: root
password:
charset: UTF8
# url: 'sqlite:///%ke
symfonny obtener parametros del objeto request
public function buscarProductosPorFacturaIdAction(Request $request)
{
$params = $request->request->all();
var_dump($params);
symfony 4 translation a español
editar en:
config
--services.yaml
parameters:
locale: 'es'
crear en:
--translations
-----messages.es.yml
ejecutar
asi el proyecto reconoce el nuevo archivo creado de translation (en este caso messages.es.yml)
https://symfony.com/doc/current/bundles/EasyAdminBundle/tutorials/i18n.html
config
--services.yaml
parameters:
locale: 'es'
crear en:
--translations
-----messages.es.yml
ejecutar
php bin/console cache:clearphp bin/console cache:warmup
asi el proyecto reconoce el nuevo archivo creado de translation (en este caso messages.es.yml)
https://symfony.com/doc/current/bundles/EasyAdminBundle/tutorials/i18n.html
symfony easyadmin instalacion
1) crear el proyecto de symfony
composer create-project symfony/framework-standard-edition my_project_name
2) descargar el bundle de migrations de doctrine
ir a la carpeta del proyecto creado
composer require doctrine/doctrine-migrations-bundle "^1.0"
3) habilitar el bundle en y setear parametros de configuracion
// app/AppKernel.php
public function registerBundles() {
$bundles = array(
//...
new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(), );
}
// app/config/config.yml
doctrine_migrations:
dir_name: "%kernel.root_dir%/DoctrineMigrations"
namespace: Application\Migrations
table_name: migration_versions
name: Application Migrations
organize_migrations: false # Version >=1.2 Possible values are: "BY_YEAR", "BY_YEAR_AND_MONTH", false
4) descargar bundle de EasyAdmin
ir a la carpeta del proyecto creado
composer require javiereguiluz/easyadmin-bundle
5) habilitar el bundle
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle(),
);
}
// ...
}
6) setear las rutas del bundle
# app/config/routing.yml
easy_admin_bundle:
resource: "@EasyAdminBundle/Controller/AdminController.php"
type: annotation
prefix: /admin
7) preparar web assets para los css/javascripts/fonts
php bin/console assets:install --symlink
8) crear las entidades del proyecto, por ejemplo Provincia y configurar su respectiva entrada
# app/config/config.yml
easy_admin:
entities:
Provincia:
class: AppBundle\Entity\Provincia
9) habilitar el servicio de translator
# app/config/config.yml
framework:
translator: { fallbacks: [ "en" ] }
10) listo, ya podemos acceder al admin
http://localhost:8181/symfosatsaid/web/app_dev.php/admin
composer create-project symfony/framework-standard-edition my_project_name
2) descargar el bundle de migrations de doctrine
ir a la carpeta del proyecto creado
composer require doctrine/doctrine-migrations-bundle "^1.0"
3) habilitar el bundle en y setear parametros de configuracion
// app/AppKernel.php
public function registerBundles() {
$bundles = array(
//...
new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(), );
}
// app/config/config.yml
doctrine_migrations:
dir_name: "%kernel.root_dir%/DoctrineMigrations"
namespace: Application\Migrations
table_name: migration_versions
name: Application Migrations
organize_migrations: false # Version >=1.2 Possible values are: "BY_YEAR", "BY_YEAR_AND_MONTH", false
4) descargar bundle de EasyAdmin
ir a la carpeta del proyecto creado
composer require javiereguiluz/easyadmin-bundle
5) habilitar el bundle
// app/AppKernel.php
// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new EasyCorp\Bundle\EasyAdminBundle\EasyAdminBundle(),
);
}
// ...
}
6) setear las rutas del bundle
# app/config/routing.yml
easy_admin_bundle:
resource: "@EasyAdminBundle/Controller/AdminController.php"
type: annotation
prefix: /admin
7) preparar web assets para los css/javascripts/fonts
php bin/console assets:install --symlink
8) crear las entidades del proyecto, por ejemplo Provincia y configurar su respectiva entrada
# app/config/config.yml
easy_admin:
entities:
Provincia:
class: AppBundle\Entity\Provincia
9) habilitar el servicio de translator
# app/config/config.yml
framework:
translator: { fallbacks: [ "en" ] }
10) listo, ya podemos acceder al admin
http://localhost:8181/symfosatsaid/web/app_dev.php/admin
Git remover archivo del head (commit) y del stage(add)
Remove single file from staging or from commit
Sometimes we accidentally add a file to staging or commit it to git repo. Lets get to how to we can remove it in this tip.
Before going further with tip, lets revisits states in which file might exists,
- Untracked - when you first create the file, it goes in this area
- Staged/ index - when you use
git add
command on the file, it goes in this area - Committed - when you use the
git commit
on the file, it goes in this area - Modified- the file is committed but has the local changes which are not committed or staged yet.
Remove from staging area
To remove from staging, we can use following command-
git rm --cached <file_name>
Here, we are using the
rm
command along with switch --cached
which indicates the file to be removed from the staging or cached area.
For example, we can use following command-
git rm --cached unwanted_file.txt
Remove single file from committed area
Note: In this, it is assumed, you doing it on local latest commit and not the commit which is pushed to remote repository.
Removing file from committed area requires 3 commands to be run, they are as follows-
git reset --soft HEAD^1
Above will undo the latest commit. if you do
git status
you will see files in the staging area. Now, we can easily remove it from staging area, as mentioned from previous point.git rm --cached <file-name>
By running above command, the file will appear in the untracked file section.
Now, we removed the single file, lets commit back those remaining files-
git commit -m "<your-message>"
fuente
git resolver conflictos merge
Resolving a merge conflict using the command line
You can resolve merge conflicts using the command line and a text editor.
Merge conflicts may occur if competing changes are made to the same line of a file or when a file is deleted that another person is attempting to edit. For information on how to resolve these situations, see "Competing line change merge conflicts and "Removed file merge conflicts."
Competing line change merge conflicts
To resolve a merge conflict caused by competing line changes, you must choose which changes to incorporate from the different branches in a new commit.
For example, if you and another person both edited the file styleguide.md on the same lines in different branches of the same Git repository, you'll get a merge conflict error when you try to merge these branches. You must resolve this merge conflict with a new commit before you can merge these branches.
- Open Git Bash.
- Navigate into the local Git repository that has the merge conflict.
cd REPOSITORY-NAME
- Generate a list of the files affected by the merge conflict. In this example, the file styleguide.mdhas a merge conflict.
git status # On branch branch-b # You have unmerged paths. # (fix conflicts and run "git commit") # # Unmerged paths: # (use "git add
..." to mark resolution) # # both modified: styleguide.md # no changes added to commit (use "git add" and/or "git commit -a") - Open your favorite text editor, such as Atom, and navigate to the file that has merge conflicts.
- To see the beginning of the merge conflict in your file, search the file for the conflict marker
<<<<<<<
. When you open the file in your text editor, you'll see the changes from the HEAD or base branch after the line<<<<<<< HEAD
. Next, you'll see=======
, which divides your changes from the changes in the other branch, followed by>>>>>>> BRANCH-NAME
. In this example, one person wrote "open an issue" in the base or HEAD branch and another person wrote "ask your question in IRC" in the compare branch orbranch-a
.If you have questions, please <<<<<<< HEAD open an issue ======= ask your question in IRC. >>>>>>> branch-a
- Decide if you want to keep only your branch's changes, keep only the other branch's changes, or make a brand new change, which may incorporate changes from both branches. Delete the conflict markers
<<<<<<<
,=======
,>>>>>>>
and make the changes you want in the final merge. In this example, both changes are incorporated into the final merge:If you have questions, please open an issue or ask in our IRC channel if it's more urgent.
- Add or stage your changes.
git add .
- Commit your changes with a comment.
git commit -m "Resolved merge conflict by incorporating both suggestions."
You can now merge the branches on the command line or push your changes to your remote repositoryon GitHub and merge your changes in a pull request.
Removed file merge conflicts
To resolve a merge conflict caused by competing changes to a file, where a person deletes a file in one branch and another person edits the same file, you must choose whether to delete or keep the removed file in a new commit.
For example, if you edited a file, such as README.md, and another person removed the same file in another branch in the same Git repository, you'll get a merge conflict error when you try to merge these branches. You must resolve this merge conflict with a new commit before you can merge these branches.
- Open Git Bash.
- Navigate into the local Git repository that has the merge conflict.
cd REPOSITORY-NAME
- Generate a list of the files affected by the merge conflict. In this example, the file README.mdhas a merge conflict.
git status # On branch master # Your branch and 'origin/master' have diverged, # and have 1 and 2 different commits each, respectively. # (use "git pull" to merge the remote branch into yours) # You have unmerged paths. # (fix conflicts and run "git commit") # # Unmerged paths: # (use "git add/rm
..." as appropriate to mark resolution) # # deleted by us: README.md # # no changes added to commit (use "git add" and/or "git commit -a") - Open your favorite text editor, such as Atom, and navigate to the file that has merge conflicts.
- Decide if you want keep the removed file. You may want to view the latest changes made to the removed file in your text editor.To add the removed file back to your repository:
git add README.md
To remove this file from your repository:git rm README.md README.md: needs merge rm 'README.md'
- Commit your changes with a comment.
git commit -m "Resolved merge conflict by keeping README.md file." [branch-d 6f89e49] Merge branch 'branch-c' into branch-d
You can now merge the branches on the command line or push your changes to your remote repositoryon GitHub and merge your changes in a pull request.
Suscribirse a:
Entradas (Atom)
linux ubuntu mint actualizar chrome
desde una terminal: $ sudo apt update $ sudo apt install google-chrome-stable
-
por consola y desde la raiz de tu proyecto php artisan --version
-
en nuestro proyecto creamos una carpeta llamada donde estaran todas nuestras clases, por ejemplo una llamada: MiApp adentro de esta irian b...
-
Integridad al nivel de la base de datos Oracle Oracle valida la integridad de la base de datos y presenta los siguientes mensajes de erro...