JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc

Task: Rename a Project with a Windows Batch (.bat) File

You can use a script to rename an existing project from the command line.

This task provides a batch file for renaming a specified analysis, along with some suggestions for modifying the script to suit your needs.

For other scripting options, see:


Permissions Required

The file requires that special user Anonymous has the following permissions for the project P of interest.

If you will be extending the script to derive the project ID from an analysis directory for some analysis A of the project, you will also need the following permissions for A.

See Modifying the Batch File for information on modifying the file to specify credentials for a non-Anonymous user with the required permissions.

Other Requirements

Use the cURL shipped with CodeSonar: $CSONAR/third-party/curl/inst/bin/curl, where $CSONAR is the CodeSonar installation directory. Either:

The Renaming Batch File

The following file will change the name of

@ECHO off
set HUB=%1
set PROJECT_ID=%2
set NEW_NAME=%3

set PROJECT_HTML_URL=%HUB%/project/%PROJECT_ID%.html
set CURL_CMD=curl

:: The Project file has exactly one line containing substring 
:: 'old_name_hash', and the hash value is between the 7th and 8th
:: (1-based) double quotes on that line.

FOR /F delims^=^"^ tokens^=8  %%i IN ('%CURL_CMD% %PROJECT_HTML_URL% ^| findstr -r "old_name_hash" 2^>nul') DO set OLD_NAME_HASH=%%i

(%CURL_CMD% -d old_name_hash=%OLD_NAME_HASH% -d new_name=%NEW_NAME% %PROJECT_HTML_URL%)

exit /b

This batch file uses an HTTP POST request to send the new project name to the hub, just as the web form on the Project page would do if you were changing the name in the web GUI. It outputs the updated Project page HTML.

Note that the HTTP POST request must include both the new project name (new_name) and CodeSonar's hash of the current project name (old_name_hash). The CodeSonar hub requires the hash value as a consistency check, so the script must recover it from a separate initial page request.

Using the Batch File

To use this file with your hub, do the following.

  1. Copy rename_project.bat to a suitable directory. The remainder of these instructions will refer to this directory as rundir.
  2. Run the file:
    cd rundir
    rename_project protocol://host:port pid newname
    where
    protocol is the protocol for your hub: http or https.
    host:port is the location of your hub.
    pid is the project ID for the project whose name you wish to change.
    You can find the project ID:
    • in the GUI Project page URL, which will be of the form http://hub_location/project/project_id.html, or
    • by deriving it based on the analysis ID from the most recent analysis of the project, which in turn is available:
      • in the URL specified at the end build/analysis command output, which will be of the form http://hub_location/analysis/analysis_id.html, or
      • by running the following command, where path\to\projname.prj_files\ is the analysis directory
        codesonar analysis_id.py path\to\projname.prj_files\
        or
      • in file path\to\projname.prj_files\aid.txt, where path\to\projname.prj_files\ is the analysis directory.
      For details, see Derive the project ID from the analysis directory, below.
    newname is new name you wish to set for the project. It must be URL-encoded.
    The file will output information about its progress.
  3. Open the project page protocol://host:port/project/pid.html in your web browser to confirm that its name has changed (or look at the top of the output).

Invocation Example

Using the hub at http://[::1]:7341, change the name of the project with ID 3 to "My Renamed Project ":

rename_project http://[::1]:7341 3 My%20Renamed%20Project

Troubleshooting

Get more verbose output For more verbose curl output, edit rename_project.bat so that curl is invoked with the -v flag. For example:
set CURL_CMD=curl -v
No files downloaded If there is no HTML output, this indicates that cURL did not download anything. There are two possible reasons.
  • curl could not download the HTML file because it doesn't exist.
    Check to make sure that you can open the HTML file URL in a web browser. You may need to pass different hub location or analysis ID arguments to the file.
  • You have an HTTPS-enabled hub with a self-signed hub server certificate. To instruct curl to accept self-signed certificates, edit rename_project.bat so that curl is invoked with the -k flag. For example:
    set CURL_CMD=curl -k
    
Downloaded files contain "Permission Denied" messages If there is an output HTML file but it contains a "Permission Denied" message rather than an updated Project page, this indicates that Anonymous does not have PROJECT_READ and PROJECT_WRITE permission for the analysis. You will need to specify credentials for a user with these permissions.

Modifying the Batch File

You may wish to make one or more of the following modifications.

Stop printing the updated HTML file to output

If you don't want to see the updated HTML file as part of your script's output, you can redirect it to the null location by modifying your curl command. Note that if you make further changes that you need to debug later, you may wish to lift this suppression at least temporarily.

  1. Edit rename_project.bat so that curl is invoked with the -o flag and a suitable value.
    set CURL_CMD=curl -o nul

Derive the project ID from the analysis directory

Instead of specifying the project ID on the command line, you can change the file to read the analysis directory from the command line and derive the project ID by reading the most recent analysis ID from the analysis directory, requesting the corresponding Analysis page from the hub, then reading the project ID from the Analysis page.

Because this approach requires the Analysis page for the analysis A in question, you must have the following permissions for A in addition to the required project permissions.

Once you have verified that you have these permissions, proceed as follows.

  1. Edit rename_project.bat so that the line setting ANALYSIS_ID is replaced with three lines:
    set ANALYSIS_DIR=%2
    set CSONAR=codesonar.exe
    for /F "tokens=*" %%g in ('%CSONAR% analysis_id.py %ANALYSIS_DIR%') do (set ANALYSIS_ID=%%g)
    
    If it is not in your PATH, adjust the setting of CSONAR to include the full path to your codesonar.exe executable.
  2. Delete the line setting PROJECT_HTML_URL and replace it with the following line setting ANALYSIS_HTML_URL.
    ANALYSIS_HTML_URL='{0}/analysis/{1}.html'.format(HUB,ANALYSIS_ID)
  3. Insert the following code at the end of the batch file (after the existing exit /b line). This new function downloads a page using the URL in its first argument, searches the page for the first occurrence of a partial Project page URL, then extracts the ID from the URL and returns it through the second argument.
    :pid_from_analysis_page
    set URL=%1
    
    :: The Analysis page breadcrumbs contain a link of the form
    :: <a href="/project/project_id.html">.
    :: Get the LINE containing this link.
    
    FOR /F "delims=" %%i IN ('%CURL_CMD% %URL% ^| findstr -r  /c:"<a href=\"/project\/[0-9]*.html\"" 2^>nul') DO set LINE=%%i
    
    :: Remove problematic special characters from LINE, then
    :: find the SUBLINE that occurs between '/project/' and the next '/'
    set "LINE=%LINE: =%"
    set "LINE=%LINE:"=%"
    set SUBLINE=""
    set /A PRJ_SEEN=0
    set /A COUNTER=0
    
    :LOOPBEGIN
    set /A COUNTER+=1
    FOR /F  "delims=/ tokens=%COUNTER%" %%A IN ("%LINE%") DO (
        if %PRJ_SEEN%==1 (
            set SUBLINE=%%A
            goto :LOOPEND)
        if "%%A"=="project" set /A PRJ_SEEN=1
        goto :LOOPBEGIN)
    :LOOPEND
    
    :: Set the second function parameter to the first token
    :: obtained when SUBLINE is split by '.'
    FOR /F "delims=. tokens=1"  %%i IN ("%SUBLINE%") DO ( set PID=%%i)
    
    call set %~2=%PID%
    
    exit /b 
  4. Insert the following code after the line setting CURL_CMD. This calls the new pid_from_analysis_page function to derive the required Project ID and return it as the value of PROJECT_ID, then uses PROJECT_ID to construct a suitable value for the PROJECT_HTML_URL variable.
    (call:pid_from_analysis_page %ANALYSIS_HTML_URL% PROJECT_ID)
    set PROJECT_HTML_URL=%HUB%/project/%PROJECT_ID%.html 
  5. When you invoke the script, specify the analysis directory as the second argument.

    For example: using the hub at http://[::1]:7341, rename the project analyzed in directory whose C:\myprojects\projectX.prj_files\ to "Another Renamed Project".

    rename_project http://[::1]:7341 C:\myprojects\projectX.prj_files\ Another%20Renamed%Project

Provide credentials for a non-Anonymous user

If your hub is configured so that special user Anonymous does not have the required permissions, you will need to edit the file to submit credentials for a suitable hub user account.

We recommend using bearer authentication. Alternative mechanisms are described in the table below.

For bearer authentication, do the following.

  1. If you do not already have a suitable session and bearer token to use, generate them now.
    1. Navigate to the User Sessions page for your selected hub user account.
    2. Use the Create Session form to create a new session with a suitably long Expires setting.
      When you click Create Session, the page will be reloaded and the Bearer Token for your new session will be displayed at the top of the page.
      IMPORTANT: Make a note of the Bearer Token now. Once you refresh or navigate away from this page there will be no further opportunity to view the token.
    3. Save the bearer token to a file. The remainder of these instructions will refer to this file as path\to\bearerfile.
  2. Edit rename_project.bat to add the following setting before the HUB setting.
    set /p BEARER_TOKEN=<path\to\bearerfile
    where
    path\to\bearerfile is the path to the file containing the bearer token you want to use.
  3. Edit rename_project.bat to modify the setting of CURL_CMD:
    CURL_CMD=curl -H "Authorization: Bearer %BEARER_TOKEN%" 

For more information about bearer authentication in CodeSonar, see User Sessions and Anonymous Sessions: Bearer Authentication.

If you don't want to use bearer authentication, you can choose one of the options from the following table.

Certificate If the hub is configured for certificate-based authentication, you can edit the file to specify a suitable user certificate.
  1. If the account does not already have a user certificate and key, generate them now.
  2. Edit rename_project.bat to add the following settings before the HUB setting.
    set CERT_PATH=path\to\usercert.pem
    set KEY_PATH=path\to\certkey.pem
    set CERT_AUTH=--cert %CERT_PATH% --key %KEY_PATH%
    set POST_ARGS=-X POST -d "sif_sign_in=yes&sif_use_tls=yes&sif_log_out_competitor=yes"
    
    where
    path\to\usercert.pem is the path to the hub user account's user certificate.
    path\to\certkey.pem is the path to the private key corresponding to the user certificate.
  3. Edit rename_project.bat to modify the setting of CURL_CMD:
    If your hub's hub server certificate is self-signed:
    CURL_CMD=curl -k %POST_ARGS% %CERT_AUTH%
    Otherwise:
    CURL_CMD=curl %POST_ARGS% %CERT_AUTH%
Hard-Coded Username/Password If you will be running the batch file under secure conditions, you may be willing to specify the account username and password directly in the file invocation.

For example, if your hub location is http://[::1]:7340 and the hub user account has username jean and password xyz123, the first argument to the file would be http://jean:xyz123@[::1]:7340.

Example: Use the hub user account with username jean and password xyz123 to authorize renaming the project with ID 3 on the hub at http://[::1]:7340 to "IMPORTANT! Keep This!":

rename_project http://jean:xyz123@[::1]:7340 3 IMPORTANT%21%20Keep%20This%21
Username, password, and new name must all be URL-encoded.
Username/Password: Other See the curl man page for alternative username/password authentication mechanisms.

See CodeSonar HTTP API: Authentication for more information on authentication strategies.

Writing Other Batch Files

You can follow the overall structure of this file to create batch files that download other kinds of file from the hub.

In general, the process for constructing a file will be along the following lines.

  1. Determine the GUI page type you are interested in.
  2. Look at the the GUI reference page for your required page type to determine the following information.
    • The page's URL or URL scheme: use this to construct the URL or URLs for your file to download.
    • The alternative page output formats that are available: if you want to process pages in one of these formats rather than HTML, check that your required format is available and construct the download URLs accordingly.
    • The RBAC permissions required to access the page and its contents. If special user Anonymous does not have these permissions, the batch file will need to provide authentication credentials for a hub user account that has the permissions.
  3. If your script will be carrying out a task that modifies the hub database (adding, deleting, or modifying elements), inspect the GUI page HTML to look at the <form ... > element that provides access to the functionality you are interested in. Your script will need to include an HTTP POST request (via curl or similar) that corresponds to the one issued when the form is submitted.
  4. Make sure your batch file includes the following elements.
    • One or more download URLs, or a mechanism for constructing them.
    • Some way of handling the downloaded URLs: one of the following.
      • The location to which the URLs should be downloaded, or a way to obtain the location.
      • An explicit redirect to the null location.
      • No specific handling, so that the downloaded files are all part of the script output.
    • A curl invocation that acts on the the URL or URLs.
  5. See the troubleshooting notes above if you encounter problems.
  6. This task uses a batch file in order to be accessible to as many Windows users as possible. If you have access to PowerShell, you will probably prefer it over batch files for scripted hub interactions.
    You may also be interested in using Python scripts to interact with the hub: if you have no local Python installation, you can use the cspython executable shipped with CodeSonar.

Running Batch Files Automatically

You can use your system tools to arrange for the batch file to be run automatically.

For example, you may choose to use the Windows Task Scheduler.

Links


Note. This page contains references to HTTP API documentation, which is served directly by the hub and cannot be accessed via a file:// URL. For active HTTP API documentation links, start a hub (if one is not already running), then open the manual from the hub.

 

To report problems with this documentation, please visit https://support.codesecure.com/.