Skip to content
Menu
Open World News Open World News
  • Privacy Policy
Open World News Open World News

Tech/News/2023/21

Posted on May 23, 2023 by Michael G
Latest tech news from the Wikimedia technical community. Please tell other users about these changes. Not all changes will affect you. Translations are available. Recent changes Changes later this…

Specbee: How to Adhere to Drupal Coding Standards with Git Hooks

Posted on May 23, 2023 by Michael G
How to Adhere to Drupal Coding Standards with Git Hooks
Prabhu
23 May, 2023

Good code is like well-built Lego creations – it’s strong, looks good, and is easy to change if you need to. The importance of good coding standards is especially high when you’re coding in a team, working on a scalable project, or participating in an open-source community like Drupal.  

As with any other open-source project, Drupal has thousands of developers working on the project. And each of them comes with their own level of expertise. How do you ensure everyone on your team or in the community follows good coding practices? Git Hooks!

Git Hooks are an easy and automated way of ensuring your code always meets Drupal’s coding standards. Implementing Drupal Coding Standards with Git hook will help developers to commit and push the code with proper coding standards as declared by the Drupal community. It can also help improve your project management skills and allows developers to commit code with proper commit message standards. Learn more about Git hooks and how to put them into action.

Specbee: How to Adhere to Drupal Coding Standards with Git Hooks

What is a Git Hook

Git Hooks are scripts that will run automatically every time a Git command is invoked. Just as you would use hook_form_alter to alter the forms in Drupal, you can have separate pre-defined hooks for every Git action.

git hook

The Pictorial Representation of Git hook

Finding Git hooks

You can find Git hooks within your project folder (provided Git is initialized) under .git/hooks.  There, you will find all the hooks with .sample extension to prevent them from executing by default.

To make use of the required hooks, you need to remove the .sample extension and edit your code for the execution.

There are many Git hooks available but we are going to use pre-commit Git hooks for initiating Drupal coding standards. 

Pre-commit Git hooks are hooks that will run before the code gets committed. It checks for the line of code that’s getting committed.

Implementing Git Hooks

Before you start, make sure you have these basic requirements ready:

  • Composer
  • Git
  • Php-code-sniffer
  • drupal/coder:8.3.13

The below procedure is for installing it in Mac devices. You can find the reference link here for installing instructions on other devices.

  • brew install php-code-sniffer
  • composer global require drupal/coder:8.3.13
  • phpcs –config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer
  • phpcs -i  → Will give you installed coding standards.

Let’s begin!

I am creating a new Drupal project called demo. You can use it in your existing project as well.

drupal project demo

 

→ Using cd command we got into the project folder.
     cd demo

→ initializing git into the project
    Git init

→ Adding and making my first commit.
    git commit -m “Initial commit”

Initial commit

 

→ Installing php code sniffer using below command for Mac.
    brew install php-code-sniffer

auto updated

 

→ Installing Drupal coder using composer
composer global require drupal/coder:8.3.13

→ Once the coder and its path are defined you will get the following output as shown below image. 
phpcs –config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer

→ phpcs -i
The above command will give you Drupal and DrupalPractice

sniffer

→ Now you can commit your code. If you have any syntax or coding standard error, you will be notified in the display and your commit process will be aborted.

commit code

→ Below is the code to fix the error automatically

phpcbf –standard=Drupal –extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml web/modules/custom/demo

Any other issues will need to be fixed manually. Commit your code once done.

fix error code

Once your code is clean it will allow you to commit the code

test code

Just copy and paste the code in pre-commit.sample within .git/hooks. Don’t forget to remove sample extensions.

Pre-commit code sample:

#!/bin/bash

# Redirect output to stderr.

exec 1>&2

# Color codes for the error message.

redclr=`tput setaf 1`
greenclr=`tput setaf 2`
blueclr=`tput setaf 4`
reset=`tput sgr0`

# Printing the notification in the display screen.

echo  “${blueclr}”
echo “…………………………… Validating your codes  ……..……………..”
echo “———————————————————–${reset}”

# Mentioning the directories which should be excluded.

dir_exclude=’/kint/|/contrib/|/devel/|/libraries/|/vendor/|.info$|.png$|.gif$|.jpg$|.ico$|.patch$|

.htaccess$|.sh$|.ttf$|.woff$|.eot$|.svg$’

# Checking for the debugging keyword in the commiting code base.

keywords=(ddebug_backtrace debug_backtrace dpm print_r var_dump  dump console.log)

keywords_for_grep=$(printf “|%s” “${keywords[@]}”)
keywords_for_grep=${keywords_for_grep:1}

# Flags for the counter.

synatx_error_found=0
debugging_function_found=0
merge_conflict=0
coding_standard_error=0

# Checking for PHP syntax errors.

changed_files=`git diff-index –diff-filter=ACMRT –cached –name-only HEAD — | egrep ‘.theme$|.module$|.inc|.php$’`
if [ -n “$changed_files” ]
then
  for FILE in $changed_files; do
  php -l $FILE > /dev/null 2>&1
  compiler_result=$?
  if [ $compiler_result -eq 255 ]
  then
    if [ $synatx_error_found -eq 0 ]
    then
      echo “${redclr}”
      echo “# Compilation error(s):”
      echo “=========================${reset}”
    fi
    synatx_error_found=1
    `php -l $FILE > /dev/null`
  fi
  done
fi

# Checking for debugging functions.

files_changed=`git diff-index –diff-filter=ACMRT –cached –name-only HEAD — | egrep -v $dir_exclude`
if [ -n “$files_changed” ]
then
  for FILE in $files_changed ; do
    for keyword in “${keywords[@]}” ; do

      pattern=”^+(.*)?$keyword(.*)?”
      resulted_files=`git diff –cached $FILE | egrep -x “$pattern”`
      if [ ! -z “$resulted_files” ]
      then
        if [ $debugging_function_found -eq 0 ]
        then
          echo “${redclr}”
          echo “Validating keywords”
          echo “================================================${reset}”
        fi
        debugging_function_found=1
        echo “Debugging function” $keyword
        git grep -n $keyword $FILE | awk ‘{split($0,a,”:”);
          printf “found in ” a[1] ” in line ” a[2] “n”;
        }’
      fi
    done
  done
fi

# Checking for Drupal coding standards

changed_files=`git diff-index –diff-filter=ACMRT –cached –name-only HEAD — | egrep -v $dir_exclude | egrep ‘.php$|.module$|.inc$|.install$|.test$|.profile$|.theme$|.js$|.css$|.info$|.txt$|.yml$’`
if [ -n “$changed_files” ]
then
    phpcs_result=`phpcs –standard=Drupal –extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml –report=csv $changed_files`
  if [ “$phpcs_result” != “File,Line,Column,Type,Message,Source,Severity,Fixable” ]
  then
    echo “${redclr}”
    echo “# Hey Buddy, The hook found some issue(s).”
    echo “———————————————————————————————${reset}”
    phpcs –standard=Drupal –extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml $changed_files
    echo ” Run below command to fix the issue(s)”
    echo “# phpcbf –standard=Drupal –extensions=php,module,inc,install,test,profile,theme,css,info,txt,md,yml your_custom_module_or_file_path”
    echo “”
    echo “# To skip the Drupal Coding standard issue(s), Please use this commands >”
    echo “—————————————————————————————————————————————–${reset}”
    coding_standard_error=1
  fi
fi

# Checking for merge conflict markers.

files_changed=`git diff-index –diff-filter=ACMRT –cached –name-only HEAD –`
if [ -n “$files_changed” ]
then
  for FILE in $files_changed; do

    pattern=”(>>>)+.*(n)?”
    resulted_files=`egrep -in “$pattern” $FILE`
    if [ ! -z “$resulted_files” ]
    then
      if [ $merge_conflict -eq 0 ]
      then
        echo “${redclr}”
        echo “———————–Unable to commit the file(s):————————“
        echo “———————————–${reset}”
      fi
      merge_conflict=1
      echo $FILE
    fi
  done
fi

# Printing final result

errors_found=$((synatx_error_found+debugging_function_found+merge_conflict+coding_standard_error))
if [ $errors_found -eq 0 ]
then
  echo “${greenclr}”
  echo “Wow! It is clean code”
  echo “${reset}”
else
  echo “${redclr}”
  echo “Please Correct the errors mentioned above. We are aborting your commit.”
  echo “${reset}”
  exit 1
fi

Final Thoughts

I hope you found this article interesting and that it helps you write better code because better code means a better web! Liked what you just read? Consider subscribing to our weekly newsletter and get tech insights like this one delivered to your inbox!

Author: Prabhu

Meet E. Prabu, Drupal Developer, and a State Level Handball Player. Prabu remains occupied with his codes during his work hours. And when not, you’ll find him binge-playing outdoor games like Badminton. He fancies a vacation amidst the hills of Kashmir and enjoys petting the local dogs around. If you want to play handball, you know whom NOT to challenge.

Drupal
Drupal Development
Drupal Planet

 

Recent Blogs

Image
git hooks

How to Adhere to Drupal Coding Standards with Git Hooks

Image
accessibility testing teaser

Testing Drupal Websites for Accessibility with WCAG 2.1

Image
Update and Post Update Hooks

Understanding Update and Post Update Hooks for Successful Drupal Site Updates

Want to extract the maximum out of Drupal?
TALK TO US

Featured Case Studies

Itsoc logo

IEEE Itsoc

Upgrading the web presence of IEEE Information Theory Society, the most trusted voice for advanced technology

Explore

Semi 252x91-01.png

Semi

A Drupal powered multi-site, multi-lingual platform to enable a unified user experience at SEMI

Explore

gsh logo

Great Southern Homes

Great Southern Homes, one of the fastest growing home builders in the US, sees greater results with Drupal

Explore

View all Case Studies

Leveling Up For Juniors With CodeWithJulie | Rubber Duck Dev Show 85

Posted on May 23, 2023 by Michael G
In this episode, we discuss leveling up junior developers with CodeWithJulie: https://www.rubberduckdevshow.com/episodes/85-leveling-up-for-juniors-with-codewithjulie/

Python 3.12.0 beta 1 released

Posted on May 23, 2023 by Michael G

I’m pleased to announce the release of Python 3.12 beta 1 (and feature freeze for Python 3.12).

https://www.python.org/downloads/release/python-3120b1/

This is a beta preview of Python 3.12

Python 3.12 is still in development. This release, 3.12.0b1, is the first of four planned beta release previews of 3.12.

Beta release previews are intended to give the wider community the opportunity to test new features and bug fixes and to prepare their projects to support the new feature release.

We strongly encourage maintainers of third-party Python projects to test with 3.12 during the beta phase and report issues found to [the Python bug tracker (Issues · python/cpython · GitHub) as soon as possible. While the release is planned to be feature complete entering the beta phase, it is possible that features may be modified or, in rare cases, deleted up until the start of the release candidate phase (Monday, 2023-07-31). Our goal is to have no ABI changes after beta 4 and as few code changes as possible after 3.12.0rc1, the first release candidate. To achieve that, it will be extremely important to get as much exposure for 3.12 as possible during the beta phase.

Please keep in mind that this is a preview release and its use is not recommended for production environments.

Major new features of the 3.12 series, compared to 3.11

Some of the new major new features and changes in Python 3.12 are:

  • New type annotation syntax for generic classes (PEP 695).
  • More flexible f-string parsing, allowing many things previously disallowed (PEP 701).
  • Even more improved error messages. More exceptions potentially caused by typos now make suggestions to the user.
  • Many large and small performance improvements (like PEP 709).
  • Support for the Linux perf profiler to report Python function names in traces.
  • The deprecated wstr and wstr_length members of the C implementation of unicode objects were removed, per PEP 623.
  • In the unittest module, a number of long deprecated methods and classes were removed. (They had been deprecated since Python 3.1 or 3.2).
  • The deprecated smtpd and distutils modules have been removed (see PEP 594 and PEP 632. The setuptools package (installed by default in virtualenvs and many other places) continues to provide the distutils module.
  • A number of other old, broken and deprecated functions, classes and methods have been removed.
  • Invalid backslash escape sequences in strings now warn with SyntaxWarning instead of DeprecationWarning, making them more visible. (They will become syntax errors in the future.)
  • The internal representation of integers has changed in preparation for performance enhancements. (This should not affect most users as it is an internal detail, but it may cause problems for Cython-generated code.)
  • (Hey, fellow core developer, if a feature you find important is missing from this list, let Thomas know.)

For more details on the changes to Python 3.12, see What’s new in Python 3.12. The next pre-release of Python 3.12 will be 3.12.0b2, currently scheduled for 2023-05-29.

More resources

Online Documentation.
PEP 693, the Python 3.12 Release Schedule.
Report bugs via GitHub Issues.
Help fund Python and its community.

And now for something completely different

As the first beta release marks the point at which we fork off the release branch from the main development branch, here’s a poem about forks in the road.

Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;

Then took the other, as just as fair,
And having perhaps the better claim,
Because it was grassy and wanted wear;
Though as for that the passing there
Had worn them really about the same,

And both that morning equally lay
In leaves, no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way,
I doubted if I should ever come back.

I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I —
I took the one less traveled by,
And that has made all the difference.
The Road Not Taken, by Robert Frost.

Enjoy the new release

Thanks to all of the many volunteers who help make Python Development and these releases possible! Please consider supporting our efforts by volunteering yourself or through organization contributions to the Python Software Foundation.
Your release team,
Thomas Wouters
Ned Deily
Steve Dower

Un Amor Hermoso Capitulo 24 FINAL Español Audio Latino – VR CHINA

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source Un Amor Hermoso Capítulos en Español Audio Latino – VR CHINA, Ver Doramas Películas y Series Online Gratis en Audio Latino ,https://doramaslatinox.blogspot.com/,https://doramasonlinelatino.blogspot.com/,https://doramaexpresslatino.blogspot.com/,Telegram : Updates : https://t.me/DORAMAEXPRESS ,VK : https://vk.com/doramaexpress, Doramas en audio español latino,doramas completos online,anime doramas y series,doramas doblados al español,doramas gratis Go to Source

Best Homestays in Wayanad _ Best Budget Stay In Wayanad _ Top 5 Homestays in Wayanad _ Bag2Bag

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source Homestay in Wayanad is an ideal choice for travelers seeking a unique and authentic experience, away from the typical tourist crowds. Whether you’re looking to immerse yourself in nature, learn about local culture, or simply relax and unwind, a homestay in Wayanad is sure to provide an unforgettable experience. Book…

IS THE SHORTY OP IN VALORANT? | VALORANT Shotgun | Valorant | @AvengerGaming71

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source ➤Subscribe (It’s FREE): https://www.youtube.com/c/avengergaming71 If You Like This Video Don’t Forget To Hit On Like Button And Drop Your Valuable Comment | Must Share This video on Your Favorite Platforms (Facebook, Twitter, Instagram, and others)! ➤Watch More Gaming Video: #avengergaming71 #valorant #SHORTY #IS_THE_SHORTY_OP? #valorantshotgun #valorantshotgunonly #shotgunsage #shotgun #valorantshotgunsage #shotgunvalorant #shotgunonly…

Aubrey Plaza Rewatches Parks & Rec, White Lotus, Ingrid Goes West & More

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source Aubrey Plaza sits down to rewatch scenes from her own movies and television series, including ‘Parks and Recreation,’ ‘The White Lotus,’ ‘Ingrid Goes West’ and ‘Scott Pilgrim vs. the World.’ Director: Adam Lance GarciaDirector of Photography: Jack BelisleEditor: Michael SuyedaCelebrity Talent: Aubrey PlazaProducer: Madison CoffeyAssociate Producer: Rafael VasquezLine Producer: Jen…

video…ministerial staff…कर्मचारी क्यों चल पड़ा जयपुर के लिए पैदल

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source राजस्थान राज्य मंत्रालयिक कर्मचारी महासंघ के तत्वावधान में मंत्रालयिक कर्मचारी 10 अप्रेल से सामूहिक अवकाश पर है। कर्मचारी 17 अप्रेल से जयपुर के ​शिप्रा पथ पर महापड़ाव कर रहे है। कर्मचारियों की हड़ताल के कारण सरकारी कार्य बा​धित हो रहे है। सरकार के महापड़ाव के बावजूद Go to Source

ChatGPT Ya Tiene Aplicación Móvil

Posted on May 22, 2023 by Michael G

Video by via Dailymotion Source ChatGPT estará finalmente disponible como aplicación para smartphones. La aplicación gratuita ya está disponible para iPhones y iPads en EE.UU., y pronto lo estará también para dispositivos Android. La versión móvil de ChatGPT también incluye reconocimiento de voz, lo que permite a los usuarios interactuar con ella utilizando su voz….

  • Previous
  • 1
  • …
  • 1,030
  • 1,031
  • 1,032
  • 1,033
  • 1,034
  • 1,035
  • 1,036
  • …
  • 1,531
  • Next

Recent Posts

  • Qwen3-Coder
  • Open Source is Back
  • An easy way to develop Home Assistant integrations
  • SmartEsq has launched an AI-powered MFN Election tool
  • Open Source email Clients

Categories

  • Android
  • Linux
  • News
  • Open Source
©2025 Open World News | Powered by Superb Themes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT