One place for hosting & domains

      Version

      Git vs SVN: Pros and Cons of Each Version Control System


      Version Control Systems (VCS), like Git and SVN, track and manage code changes and provide an efficient way to collaborate on software development projects. A VCS is especially useful as a software development project grows in size and complexity, but even the simplest projects can benefit from tracking code changes with a VCS.

      Git and SVN are two of the most popular open source VCS solutions. Git has recently skyrocketed in popularity due to its use by developers collaborating on open-source projects. SVN, on the other hand, has been more commonly used in enterprise software development projects.

      This guide discusses the features and pros and cons of Git and SVN to help you choose the best VCS for your software development project.

      What is the Git Version Control System?

      Git
      is a distributed version control system. In this type of VCS, a project contributor creates a local repository that is a full clone of a central repository. With a local clone of the central repository, each contributor is able to work on the project completely offline on their own computer. When changes are ready, contributors can push and merge them with the central repository.

      Git has immense support from the open-source community. It has quickly become one of the most used version control systems for software development projects.

      What is SVN?

      Apache Subversion
      (SVN), is a centralized version control system. When working with this type of VCS, all project files exist on a central repository server. The central repository has a “trunk,” which contains the current, stable version of the project. When working on new features, contributors can make “branches” from the trunk. Each branch is stored in a sub-folder on the central repository. When changes are ready, a branch can be merged into the trunk.

      SVN has a long and successful history and stands as a titan in the version control world. It has widespread usage for enterprise projects, with features like granular access control that make it excel in that context.

      Git vs SVN: Pros and Cons

      To help you understand how these two version control solutions match up, this section walks you through the pros and cons of each.

      Git Pros and Cons

      Git’s pros are the following:

      • Operates locally. Contributors work on clones of the main repository, which they can continue to work on offline, without a network connection to the main repository. Contributors only need to connect when changes are ready to be pushed. This also helps limit network traffic to the main repository.

      • Avoids having a single point of failure. The repository is distributed in local copies, so there is less to worry about if a failure occurs on the main repository. The main repository can be restored from one of the local copies.

      • Handles merging from multiple contributors effectively. Contributors all work independently on their copies of the main repository. Git then provides a robust system for reconciling and merging each contributor’s changes. Staging is part of this, allowing contributors to focus on particular features without affecting others.

      Git’s cons are the following:

      • Has a higher learning curve. Using Git to collaborate on a project requires that you make your changes locally, stage those changes, and merge the changes back into the main branch. This process can get complicated, especially for non-technical users.

      • Lacks granular access control. Git supports applying limits on a contributor’s ability to create branches and merge changes on the main repository. However, you cannot restrict access to specific parts of the repository. Anyone with access to the repository has access to everything in the repository, with local repositories being clones of the entire codebase.

      • Does not effectively handle storing large binary files. Git cannot compress these files effectively, meaning that the repository size can grow exponentially with each change to a large binary file.

      SVN Pros and Cons

      SVN’s pros are the following:

      • Takes an easier approach. The path between
        creating a new feature branch
        and merging it into the trunk is relatively short and intuitive to grasp. This makes SVN a tool that requires less training when getting started and can be effectively taken up by non-technical contributors.

      • Facilitates a top-down approach. Since everything is centralized in an SVN repository, there is a single instance of the entire repository. This allows for granular repository access control. Each contributor’s access can be limited to particular directories and files. SVN is a good choice when you need to manage security hierarchies within a repository.

      • Efficiently stores large binary files. Teams that need to store binary files, especially when those binary files change frequently, can do so without worrying about exponential storage increases with each change. While this is not a concern for every team, this feature can be a significant boon for some workflows and version control use cases.

      SVN’s cons are the following:

      • Provides limited offline capabilities. Everything operates on a centralized repository using a client-server approach. When contributors are offline and unable to access the server, they essentially lose the ability to contribute. This also entails a higher level of traffic to the main repository’s server, since contributors have to access it constantly.

      • The centralized repository server can be a single point of failure. Since contributors do not make local copies of the entire repository, unless a backup copy is made, there is only one instance of the entire repository. If an issue occurs with the instance, such as data corruption, it can have dire repercussions on a software development project.

      Advantages of Git Over SVN

      The ability to work locally and offline is one major advantage to Git. SVN requires contributors to be connected to the main repository server, which essentially eliminates working offline.

      Git also outperforms SVN when it comes to merging and conflict resolution. Git has been designed for an open-source setting where numerous contributors may be working on the same parts of a codebase. To allow for this type of collaboration, Git has built up a robust system for resolving merge conflicts that makes the process smoother, and more manageable.

      Git’s distributed model of version control helps mitigate the potential for loss of the main repository. Since contributors clone the main repository, the risk of completely losing your main repository is greatly reduced. On the other hand, SVN’s centralized model of version control creates the potential for a single point of failure should anything happen to the main repository.

      Advantages of SVN Over Git

      SVN’s centralized repository model makes it easier to manage contributions and contributors. Git does not support codebase access restrictions — a contributor who has access to the repository has access to the entire repository. SVN, by contrast, provides granular control, allowing for limits on particular contributors down to the directory, and file levels.

      SVN also makes contributing easier. Git has robust conflict handling, but its system can often be daunting for newcomers. SVN’s system is more approachable, because the path between creating a new feature and merging it into the trunk is shorter and simpler.

      SVN wins out on some performance considerations. It handles network traffic exceptionally well. So, while contributors may have to be connected to the server to complete work, the network load for this is managed efficiently. Also, SVN compresses and stores large binaries quite efficiently. If your project includes large binary files, you might consider using SVN.

      Which Should You Use?

      Each of the version control systems covered here — SVN and Git — has its particular strengths and weaknesses. Each one fits different use cases better than the other, and neither one wins out over the other one outright.

      • Use SVN when you need a VCS that favors top-down management, easy contributions, and does not require you to work entirely offline. SVN often comes out on top for enterprise usage specifically for its granular access control, and it is the clear choice if you need to set up security hierarchies.

        To get started with SVN, be sure to read through our guide
        How to Install and Use the Subversion CLI Client
        .

      • Use Git when you need numerous contributors to work in parallel, where you expect lots of potential merge conflicts, and when you need contributors to be able to work locally offline. Because it handles merge conflicts, Git makes sense for most open-source projects, where contributors often work without external coordination. Git shines in a wide range of environments with complex codebases and distributed teams.

        To learn more and start working with Git, check out our guide
        Getting Started with Git
        .

      Conclusion

      SVN and Git are both powerful version control systems that each use a different approach to managing and merging code changes. Git uses a distributed model, whereas SVN uses a centralized model. Which VCS that you choose largely depends on your software development project’s requirements. After reading this guide, you should be able to select the best version control system for your needs.



      Source link

      Why You Should Update Your PHP Version (& How to Do It)


      Regularly updating your site’s copy of WordPress ensures that your website will have a high level of performance and security. If you forget to update your site’s PHP version though, you’re leaving your site vulnerable to both hackers and potential performance bottlenecks. Yikes!

      Fortunately, it’s fairly easy to check your site’s current PHP version and proceed with upgrades if it happens to be outdated. This process can contribute to faster load times, improved security, and support for new functionality.

      This article will discuss what PHP is, and why you should consider updating it. Then, we’ll show you how to check your current PHP version and upgrade it if needed. Let’s get started!

      An Introduction to PHP

      update your PHP version

      PHP is a programming and scripting language that plays an important role in WordPress development. PHP takes data from the database and converts it into an HTML web page whenever someone visits your website.

      As a website owner, you might never need to learn PHP coding. However, after downloading WordPress, you’ll automatically receive all of the PHP files that make up WordPress core:

      WordPress folder in FTP client

      Although these files have been written for you — and are just waiting for your content, themes, and plugins — there are some scenarios where you can benefit from editing PHP files:

      Since PHP is one of the key languages behind WordPress, learning a little bit about how to work with it will open up the scope of projects that you are able to do.

      It’s likely that you won’t have to edit your PHP files. Still, learning the language can be handy for developers who wish to create new software or customizations.

      Why You Should Update Your PHP Version

      You might already be familiar with the importance of updating your WordPress, themes, and plugins. It’s also crucial to regularly update your PHP version:

      PHP 8.1 released

      Currently, WordPress recommends upgrading your PHP version to at least 7.4. This isn’t required, but older versions may have reached their end of life, meaning they no longer have active support for bug fixes or security updates.

      Here are the main benefits of upgrading your sites to the latest PHP version:

      • Better security: Older PHP versions can be more vulnerable to cyberattacks.
      • Improved performance: Upgraded PHP can improve load times through internal code improvements and reduced memory usage.
      • More support: Currently supported versions have active support, with regular bug fixes and security patches.

      Take it from our Director of IT Operations, Luke Odom:

      “Running a modern, supported, version of PHP is one of the best things you can do for the health, security, and speed of your website. Let’s compare an outdated PHP version to an old car. Sure, it will run and get you from point A to B, but without modern safety sensors, technology, fuel efficiency, and GPS navigation you may find yourself in some trouble a bit more easily.”

      Ultimately, your website will be faster and more secure when it’s running on the latest version of PHP. Many web hosts provide automatic updates for their customers, but if you’re not with one of these hosts, you can follow this manual process.

      How to Check Your Current PHP Version

      Before you get started, you should check which PHP version is currently supporting your website. If you’ve installed WordPress 5.0 or higher, you can view your PHP version in your dashboard.

      First, go to Tools > Site Health:

      WordPress Tools Site Health

      On the Site Health page, click on Info. Then find the Server section:

      view server Site Health in WordPress

      Here, you should be able to see your current PHP version:

      view your server's PHP version

      Another simple method for checking your PHP version is using your web host’s control panel. For DreamHost websites, click on the Manage button next to your domain:

      manage websites in DreamPress Panel

      Then, find the section labeled PHP. This will list your site’s PHP version:

      modify your PHP version

      The latest PHP release is 8.1. If you have a version older than 7.4 — the version that the WordPress project suggests — you can proceed with the following steps.

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      How to Update Your PHP Version (In 4 Easy Steps)

      Once you decide to update your version of PHP, we recommend taking a few precautions. Firstly, consider backing up your website. If anything goes wrong, you can roll back your version of PHP and then revert your site to the backed-up version.

      Next, make sure your website is fully up to date. In your dashboard, go to the Updates page and install the latest versions of WordPress, themes, and plugins:

      WordPress Proxy Cache plugin

      After taking these preventative steps, you can start manually updating your PHP version. As a simpler alternative, you can also contact your hosting provider. The host can typically handle this process for you.

      Step 1: Create a Staging Site

      Updating your PHP version can cause software conflicts on your website. Therefore, it’s wise to test the update in a staging area initially. This creates a separate, safe environment to implement changes rather than breaking your live site.

      With many hosting providers, you can create a staging site through your control panel. For this tutorial, we’ll be using the DreamHost panel.

      If you have a managed DreamHost plan, you can set up your staging site in minutes. Simply open your control panel and navigate to WordPress > Managed WordPress > Manage:

      DreamPress managed WordPress settings in PanelOn the next page, go to Staging. Then, click on Create Staging Site:

      create a one click staging site with DreamPress managed WordPress hosting

      This will set up your staging site on an automatically generated subdomain. After this, you can update your PHP version without editing your live site.

      Step 2: Change Your PHP Version

      No matter your hosting provider, you can usually change your website’s PHP version through your control panel. This process will look different based on your host, but you’ll want to look for a MultiPHP Manager or PHP Selector.

      To edit your DreamHost staging site, you can simply scroll down to the Configure PHP section. This section will list your current PHP version and the most recent update option:

      change PHP version

      To update PHP, click on Change PHP to v8.1. If successful, this section will indicate that your site is up to date:

      configure your PHP version

      Although it isn’t recommended, you can also directly modify your live website. In your DreamHost panel, go to Manage Websites. Then, scroll down to PHP and click on the arrow next to Modify:

      select PHP version in the DreamHost panel

      Lastly, select the new version you want to run on your website. Click on Change PHP Version to finish the process.

      Step 3: Look for Conflicts

      After updating your PHP version, we recommend reviewing your plugins and themes for conflicts. Upgrading PHP may cause common problems such as the White Screen of Death or 500 internal server errors.

      Whether you updated a staging environment or your live site, visit the front end to see if everything is functioning correctly. If you notice any errors after browsing the website, you’ll need to troubleshoot the issue.

      One common reason for WordPress errors is a plugin conflict. When issues arise, try deactivating all of your plugins using the Bulk Actions on your Plugins page:

      deactivate WordPress plugins

      To target the conflicting plugin, reactivate each plugin one by one. Then, you can download a similar plugin or delete it if it’s unnecessary.

      If you face additional problems like exceeded maximum execution time or maintenance mode errors, you might need to edit your wp-config.php file. This process could require more extensive troubleshooting, such as increasing your PHP memory limit.

      Step 4: Publish Changes to Your Live Site

      If you implemented a new PHP version on a staging site, it’s time to publish this change on your live website. Usually, you can do this in your host’s control panel.

      For example, DreamHost provides a simple one-click transfer of your staging data to your website. Once you’re sure you’ve targeted any potential conflicts, you can click on Publish Staging to Live:

      push staging environment to live

      This will successfully update your website’s PHP version. Since you used a staging site, you won’t have to worry about unexpected errors!

      Ready for an Upgrade?

      You might be hesitant to update your PHP version because you’re worried about breaking your site. However, PHP updates ultimately improve the security and performance of your website. You can easily avoid any conflicts by testing changes before making them live.

      To review, here are the four steps you can take to update the PHP version of your website:

      1. Create a staging site.
      2. Change your PHP version.
      3. Look for conflicts.
      4. Publish changes to your live site.

      Although you can manually update your PHP version, you might want to avoid doing this for every new development. Here at DreamHost, our Website Maintenance plans now include automatic PHP updates! This way, you can sit back, relax, and leave this process to us.

      Website and PHP Version Management Made Easy

      Let us handle the backend — we’ll manage and monitor your website so it’s safe, secure, and always up.

      website tech support



      Source link

      Cómo usar ldflags para configurar la información de versión de aplicaciones de Go


      Introducción

      Al implementar aplicaciones en un entorno de producción, la creación de binarios con información de versión y otros metadatos mejorará sus procesos de monitoreo, registro y depuración al agregar información de identificación para ayudar a realizar un seguimiento de sus compilaciones con el tiempo. Esta información de versión, a menudo, puede incluir datos muy dinámicos, como el tiempo de compilación, la máquina o el usuario que compiló el binario y el sistema de control de versiones (VCS) con el que se creó, entre otros. Debido a que estos valores cambian constantemente, codificar estos datos directamente en el código fuente y modificarlos antes de cada compilación nueva es tedioso y está expuesto errores: los archivos de código fuente se pueden mover y las variables y constantes pueden cambiar los archivos a lo largo del desarrollo, lo que interrumpe el proceso de compilación.

      Una manera de resolver esto en Go es usar -ldflags con el comando go build para insertar información dinámica en el binario en el tiempo de compilación, sin necesidad de modificar el código fuente. En este indicador, ld significa enlazador, que es el programa que vincula las diferentes piezas del código fuente compilado en el binario final. Por lo tanto, ldflags quiere decir indicadores de enlazador. Se denomina de esta manera porque pasa un indicador al enlazador subyacente de la cadena de herramientas de Go, cmd/link, que le permite cambiar los valores de los paquetes importados en el tiempo de compilación desde la línea de comandos.

      En este tutorial, usará -ldflags para cambiar el valor de las variables en el tiempo de compilación e introducir su propia información dinámica en un binario usando una aplicación de muestra que imprime información de versión en la pantalla.

      Requisitos previos

      Para seguir el ejemplo de este artículo, necesitará lo siguiente:

      Crear su aplicación de muestra

      Antes de usar ldflags para introducir datos dinámicos, primero, necesita una aplicación para insertar la información. En este paso, creará esta aplicación, que, en esta etapa, solo imprimirá información de control de versiones estática. Crearemos esa aplicación ahora.

      En su directorio src, cree un directorio que lleve el nombre de su aplicación. En ese tutorial, se usará el nombre de aplicaciónapp:

      Cambie su directorio de trabajo a esta carpeta:

      A continuación, usando el editor de texto que prefiera, cree el punto de entrada de su programa, main.go:

      Ahora, haga que su aplicación imprima información de versión añadiendo el siguiente contenido:

      app/main.go

      package main
      
      import (
          "fmt"
      )
      
      var Version = "development"
      
      func main() {
          fmt.Println("Version:t", Version)
      }
      

      Dentro de la función main(), declaró la variable Version, luego imprimió la cadena Version: seguida de un carácter de tabulación, t, y por último la variable declarada.

      En este punto, la variable Version se define como development, que será la versión predeterminada de esta aplicación. Posteriormente, cambiará este valor para que sea un número de versión oficial, que se dispondrá conforme al formato de control de versiones semántico.

      Guarde el archivo y ciérrelo. Una vez hecho esto, cree y ejecute la aplicación para confirmar que imprima la versión correcta:

      Verá lo siguiente:

      Output

      Ahora, dispondrá de una aplicación que imprime información de versión predeterminada, pero todavía no cuenta con una forma de transmitir información de versión actual en el tiempo de compilación. En el siguiente paso, usará -ldflags y go build para resolver este problema.

      Usar ldflags con go build

      Como se mencionó anteriormente, ldflags significa *indicadores de enlazador *y se utiliza para pasar indicadores al enlazador subyacente de la cadena de herramientas de Go. Esto funciona de acuerdo con la siguiente sintaxis:

      • go build -ldflags="-flag"

      En este ejemplo, pasamos flag al comando go tool link subyacente que se ejecuta como parte de go build. En este comando, se utilizan comillas dobles alrededor del contenido que se pasa a ldflags para evitar romper sus caracteres o la presencia de caracteres que la línea de comandos podría interpretar como algo distinto de lo que deseamos. Desde aquí, podría pasar muchos indicadores link diferentes. A los efectos de este tutorial, usaremos el indicador -X para escribir información en la variable en el tiempo de enlace, seguido de la ruta del paquete a la variable y su nuevo valor:

      • go build -ldflags="-X 'package_path.variable_name=new_value'"

      Dentro de las comillas, ahora se encuentran la opción -X y un par clave-valor que representa la variable que se debe cambiar y su nuevo valor. El carácter . separa la ruta del paquete y el nombre de la variable, y se utilizan comillas simples para evitar la ruptura de los caracteres en el par clave-valor.

      Para sustituir la variable Version en su aplicación de ejemplo, utilice la sintaxis del último bloque de comandos a fin de establecer un nuevo valor y compilar el nuevo binario:

      • go build -ldflags="-X 'main.Version=v1.0.0'"

      En este comando, main es la ruta del paquete de la variable Version, dado que esta variable se encuentra en el archivo main.go. Version es la variable en la que escribe y v1.0.0 es el nuevo valor.

      Para usar ldflags, el valor que desea cambiar debe existir y ser una variable de nivel de paquetes de tipo string. Esta variable puede ser exportada o no exportada. El valor no puede ser const y el resultado de la invocación de una función no puede fijarlo. Afortunadamente, Version cumple todos estos requisitos: ya se declaró como variable en el archivo main.go, y tanto el valor actual (development) como el valor deseado (v1.0.0) son cadenas.

      Una vez compilado su nuevo binario app, ejecute la aplicación:

      Recibirá el siguiente resultado:

      Output

      Con -ldflags, cambió de forma exitosa la variable Version de development a v1.0.0.

      De esta manera, modificó una variable string dentro de una aplicación simple en el tiempo de compilación. Con ldflags, puede insertar detalles de versión, información de licenciamiento y otros datos en un binario listo para la distribución usando solo la línea de comandos.

      En este ejemplo, la variable que cambió se encontraba en el programa main, lo que redujo la dificultad de determinar el nombre de la ruta. Sin embargo, a veces la ruta hacia estas variables es más difícil de encontrar. En el siguiente paso, escribirá valores en variables dentro de subpaquetes para demostrar la mejor manera de determinar rutas de paquetes más complejas.

      Proporcionar orientación hacia variables de subpaquetes

      En la última sección, manipuló la variable Version que se encontraba en el paquete de nivel superior de la aplicación. Sin embargo, esto no siempre es así. Suele ser más práctico disponer estas variables en otro paquete, ya que el paquete main no se puede importar. Para simular esto en su aplicación de muestra, creará un nuevo subpaquete, app/build, que almacenará información sobre el momento en que se compiló el binario y el nombre del usuario que ejecutó el comando de compilación.

      Para añadir un nuevo subpaquete, primero agregue a su proyecto un nuevo directorio denominado build:

      A continuación, cree un nuevo archivo llamado build.go para contener las variables nuevas:

      En su editor de texto, añada nuevas variables para Time y User:

      app/build/build.go

      package build
      
      var Time string
      
      var User string
      

      La variable Time contendrá una representación de cadena del momento en que se compiló el binario. La variable User contendrá el nombre del usuario que compiló el binario. Dado que estas dos variables siempre tendrán valores, no es necesario inicializarlas con valores predeterminados, como lo hizo para Version.

      Guarde el archivo y ciérrelo.

      A continuación, abra main.go para añadir estas variables a su aplicación:

      Dentro de main.go, agregue las siguientes líneas resaltadas:

      main.go

      package main
      
      import (
          "app/build"
          "fmt"
      )
      
      var Version = "development"
      
      func main() {
          fmt.Println("Version:t", Version)
          fmt.Println("build.Time:t", build.Time)
          fmt.Println("build.User:t", build.User)
      }
      

      En estas líneas, primero importó el paquete app/build y luego imprimió build.Time y build.User de la misma manera en que imprimió Version.

      Guarde el archivo y cierre su editor de texto.

      A continuación, para brindar orientación a estas variables con ldflags podría usar la ruta de importación app/build seguida de .User o .Time, dado que ya conoce la ruta de importación. Sin embargo, para simular una situación más compleja en la cual la ruta hacia la variable no sea tan evidente, usaremos el comando nm de la cadena de herramientas de Go.

      Con el comando go tool nm se mostrarán los símbolos presentes en un ejecutable, un objeto o un archivo. En este caso, “símbolo” se refiere a un objeto en el código, como una variable o función definida o importada. Generando una tabla de símbolos con nm y usando grep para buscar una variable, puede obtener rápidamente información sobre su ruta.

      Nota: El comando nm no lo ayudará a encontrar la ruta de su variable si el nombre del paquete tiene caracteres no ASCII, o bien los caracteres " o %, ya que es una limitación de la herramienta.

      Para usar este comando, primero, compile el binario para app:

      Ahora que se compiló app, oriente la herramienta nm hacia ella y realice una búsqueda en el resultado:

      • go tool nm ./app | grep app

      Cuando se ejecute, la herramienta nm mostrará muchos datos. Debido a esto, el comando anterior utilizó | para canalizar el resultado al comando grep, que luego buscó términos con la app de nivel superior en el título.

      Recibirá un resultado similar a este:

      Output

      55d2c0 D app/build.Time 55d2d0 D app/build.User 4069a0 T runtime.appendIntStr 462580 T strconv.appendEscapedRune . . .

      En este caso, las primeras dos líneas del resultado establecido contienen las rutas de las dos variables que busca: app/build.Time y app/build.Time.

      Ahora que conoce las rutas, compile la aplicación de nuevo, pero, esta vez, cambie Version, User y Time en el tiempo de compilación. Para hacerlo, pase varios indicadores -X a -ldflags:

      • go build -v -ldflags="-X 'main.Version=v1.0.0' -X 'app/build.User=$(id -u -n)' -X 'app/build.Time=$(date)'"

      Aquí, pasó el comando Bash id -u -n para mostrar el usuario actual y el comando date para mostrar la fecha actual.

      Una vez compilado el ejecutable, ejecute el programa:

      Este comando, cuando se ejecuta en un sistema Unix, genera un resultado similar al siguiente:

      Output

      Version: v1.0.0 build.Time: Fri Oct 4 19:49:19 UTC 2019 build.User: sammy

      Ahora, dispondrá de un binario que contiene información de control de versiones y de compilación, y que puede proporcionar ayuda fundamental para la producción a la hora de resolver problemas.

      Conclusión

      En este tutorial, se demostró que ldflags, cuando se aplica correctamente, puede ser una potente herramienta para introducir información valiosa en binarios en el tiempo de compilación. De esta manera, puede controlar indicadores de características, información de entorno, información de control de versiones y otros elementos sin introducir cambios en su código fuente. Agregando ldflags a su flujo de trabajo de compilación actual, puede maximizar los beneficios del formato de distribución binaria autónoma de Go.

      Si desea obtener más información acerca del lenguaje de programación Go, consulte toda la serie Cómo programar en Go. Si busca más soluciones para el control de versiones, consulte nuestra guía de referencia Cómo usar Git.



      Source link