Create and Edit Projects Programmatically

This example shows how to use the Project API to create a new project and automate project tasks for manipulating files. It covers how to create a project from the command line, add files and folders, set up the project path, define project shortcuts, and create a reference to the new project in another project. It also shows how to programmatically work with modified files, dependencies, shortcuts, and labels.

Set up the Example Files

Create a working copy of the Times Table App example project files and open the project. MATLAB® copies the files to an examples folder so that you can edit them. The project puts the files under Git™ source control. Use currentProject to create a project object from the currently loaded project.

matlab.project.example.timesTable 
mainProject = currentProject;

Examine Project Files

Examine the files in the project.

files = mainProject.Files
files = 
  1×14 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Use indexing to access files in this list. For example, get file number 10. Each file has properties describing its path and attached labels.

mainProject.Files(10)
ans = 
  ProjectFile with properties:

                   Path: "C:\workSpace\examples\TimesTableApp\tests\tNewTimesTable.m"
                 Labels: [1×1 matlab.project.Label]
               Revision: ""
    SourceControlStatus: Unmodified

Examine the labels of the tenth file.

mainProject.Files(10).Labels
ans = 
  Label with properties:

            File: "C:\workSpace\examples\TimesTableApp\tests\tNewTimesTable.m"
        DataType: 'none'
            Data: []
            Name: "Test"
    CategoryName: "Classification"

Get a particular file by name.

myfile = findFile(mainProject,"source/timestable.mlapp")
myfile = 
  ProjectFile with properties:

                   Path: "C:\workSpace\examples\TimesTableApp\source\timestable.mlapp"
                 Labels: [1×1 matlab.project.Label]
               Revision: ""
    SourceControlStatus: Unmodified

Create New Project

Create the Times Table Game project. This project will store the game logic behind the Times Table App. The Times Table Game project will be used by the Times Table App project through a project reference.

Create the project and set the project name.

timesTableGameFolder = fullfile(mainProject.RootFolder,"refs","TimesTableGame");
timesTableGame = matlab.project.createProject(timesTableGameFolder);
timesTableGame.Name = "Times Table Game";

Move the Times Table App game logic from the main project folder to the new project folder, and add it to the Times Table Game project. Then, remove the file from the Times Table App project.

movefile("..\..\source\timesTableGame.m");
addFile(timesTableGame,"timesTableGame.m");

reload(mainProject);
removeFile(mainProject,"source\timesTableGame.m");

Add the Times Table Game project root folder to the Times Table Game project path. This makes the timesTableGame.m file available when the Times Table App project or any project that references the Times Table App project is loaded.

reload(timesTableGame);
addPath(timesTableGame,timesTableGame.RootFolder);

Add a Project Reference

Add the new Times Table Game project to the Times Table App project as a project reference. This allows the Time Table App project to view, edit, and run files in the Times Table Game project.

reload(mainProject);
addReference(mainProject,timesTableGame);

Get Modified Files

Get all the modified files in the Times Table App project. Compare this list with the Files > Modified view in the project. You can see the files for the new Times Table Game project, as well as the removed and modified files in the Times Table App project.

modifiedfiles = listModifiedFiles(mainProject)
modifiedfiles = 
  1×19 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Get the second modified file in the list. Observe that the SourceControlStatus property is Added. The listModifiedFiles function returns any files that are added, modified, conflicted, deleted, and so on.

modifiedfiles(2)
ans = 
  ProjectFile with properties:

                   Path: "C:\workSpace\examples\TimesTableApp\refs\TimesTableGame\resources\project\Project.xml"
               Revision: ""
    SourceControlStatus: Added

Refresh the source control status before querying individual files. You do not need to do this before calling listModifiedFiles.

refreshSourceControl(mainProject)

Get all the project files that are Unmodified. Use the ismember function to get an array of logicals stating which files in the Times Table App project are unmodified. Use the array to get the list of unmodified files.

unmodifiedStatus = ismember([mainProject.Files.SourceControlStatus],matlab.sourcecontrol.Status.Unmodified);
mainProject.Files(unmodifiedStatus)
ans = 
  1×9 ProjectFile array with properties:

    Path
    Labels
    Revision
    SourceControlStatus

Get File Dependencies

Run a dependency analysis to update the known dependencies between project files.

updateDependencies(mainProject)

Get the list of dependencies in the Times Table App project. The Dependencies property contains the graph of dependencies between project files, stored as a MATLAB digraph object.

g = mainProject.Dependencies
g = 
  digraph with properties:

    Edges: [5×1 table]
    Nodes: [9×1 table]

Get the files required by the timestable.mlapp file.

requiredFiles = bfsearch(g, which('source/timestable.mlapp'))
requiredFiles = 2×1 cell array
    {'C:\workSpace\examples\TimesTableApp\source\timestable.mlapp'             }
    {'C:\workSpace\examples\TimesTableApp\refs\TimesTableGame\timesTableGame.m'}

Get the top-level files of all types in the graph. The indegree function finds all the files that are not depended on by any other file.

top = g.Nodes.Name(indegree(g)==0)
top = 7×1 cell array
    {'C:\workSpace\examples\TimesTableApp\requirements\TimesTableRequirements.mlx'}
    {'C:\workSpace\examples\TimesTableApp\tests\tAnswerIsCorrect.m'               }
    {'C:\workSpace\examples\TimesTableApp\tests\tCurrentQuestion.m'               }
    {'C:\workSpace\examples\TimesTableApp\tests\tNewTimesTable.m'                 }
    {'C:\workSpace\examples\TimesTableApp\utilities\editTimesTable.m'             }
    {'C:\workSpace\examples\TimesTableApp\utilities\openRequirementsDocument.m'   }
    {'C:\workSpace\examples\TimesTableApp\utilities\runTheseTests.m'              }

Get the top-level files that have dependencies. The indegree function finds all the files that are not depended on by any other file, and the outdegree function finds all the files that have dependencies.

top = g.Nodes.Name(indegree(g)==0 & outdegree(g)>0)
top = 4×1 cell array
    {'C:\workSpace\examples\TimesTableApp\requirements\TimesTableRequirements.mlx'}
    {'C:\workSpace\examples\TimesTableApp\tests\tAnswerIsCorrect.m'               }
    {'C:\workSpace\examples\TimesTableApp\tests\tCurrentQuestion.m'               }
    {'C:\workSpace\examples\TimesTableApp\tests\tNewTimesTable.m'                 }

Find impacted (or "upstream") files by creating a transposed graph. Use the flipedge function to reverse the direction of the edges in the graph.

transposed = flipedge(g)
transposed = 
  digraph with properties:

    Edges: [5×1 table]
    Nodes: [9×1 table]

impacted = bfsearch(transposed,which('source/timestable.mlapp'))
impacted = 2×1 cell array
    {'C:\workSpace\examples\TimesTableApp\source\timestable.mlapp'                }
    {'C:\workSpace\examples\TimesTableApp\requirements\TimesTableRequirements.mlx'}

Get information on the project files, such as the number of dependencies and orphans.

averageNumDependencies = mean(outdegree(g));
numberOfOrphans = sum(indegree(g)+outdegree(g)==0);

Change the sort order of the dependency graph to show project changes from the bottom up.

ordered = g.Nodes.Name(flip(toposort(g)));

You can view the same dependency analysis graph in the Impact View of the project. To plot the graph, save the impact view to an image file.

Query Shortcuts

You can use shortcuts to save frequent tasks and frequently accessed files, or to automate startup and shutdown tasks.

Get the Times Table App project shortcuts.

shortcuts = mainProject.Shortcuts
shortcuts = 
  1×4 Shortcut array with properties:

    Name
    Group
    File

Examine a shortcut in the list.

shortcuts(2)
ans = 
  Shortcut with properties:

     Name: "Edit Times Table App"
    Group: "Launch Points"
     File: "C:\workSpace\examples\TimesTableApp\utilities\editTimesTable.m"

Get the file path of a shortcut.

shortcuts(3).File
ans = 
"C:\workSpace\examples\TimesTableApp\utilities\openRequirementsDocument.m"

Examine all the files in the shortcuts list.

{shortcuts.File}'
ans = 4×1 cell array
    {["C:\workSpace\examples\TimesTableApp\source\timestable.mlapp"             ]}
    {["C:\workSpace\examples\TimesTableApp\utilities\editTimesTable.m"          ]}
    {["C:\workSpace\examples\TimesTableApp\utilities\openRequirementsDocument.m"]}
    {["C:\workSpace\examples\TimesTableApp\utilities\runTheseTests.m"           ]}

Label files

Create a new category of labels of type char. In the Times Table App project, the new Engineers category appears in the Labels pane.

createCategory(mainProject,'Engineers','char')
ans = 
  Category with properties:

                Name: "Engineers"
        SingleValued: 0
            DataType: "char"
    LabelDefinitions: [1×0 matlab.project.LabelDefinition]

Define a new label in the new category.

category = findCategory(mainProject,'Engineers');
createLabel(category,'Bob');

Get the label definition object for the new label.

ld = findLabel(category,'Bob')
ld = 
  LabelDefinition with properties:

            Name: "Bob"
    CategoryName: "Engineers"

Attach a label to a project file. If you select the file in the Times Table App project, you can see this label in the Label Editor pane.

myfile = findFile(mainProject,"source/timestable.mlapp");
addLabel(myfile,'Engineers','Bob');

Get a particular label and attach text data to it.

label = findLabel(myfile,'Engineers','Bob');
label.Data = 'Email: Bob.Smith@company.com'
label = 
  Label with properties:

            File: "C:\workSpace\examples\TimesTableApp\source\timestable.mlapp"
        DataType: 'char'
            Data: 'Email: Bob.Smith@company.com'
            Name: "Bob"
    CategoryName: "Engineers"

Retrieve the label data and store it in a variable.

mydata = label.Data
mydata = 
'Email: Bob.Smith@company.com'

Create a new label category with data type double, the type MATLAB commonly uses for numeric data.

createCategory(mainProject,'Assessors','double');
category = findCategory(mainProject,'Assessors');
createLabel(category,'Sam');

Attach the new label to a specified file and assign data value 2 to the label.

myfile = mainProject.Files(10);
addLabel(myfile, 'Assessors', 'Sam', 2)
ans = 
  Label with properties:

            File: "C:\workSpace\examples\TimesTableApp\utilities"
        DataType: 'double'
            Data: 2
            Name: "Sam"
    CategoryName: "Assessors"

Close Project

Close the project to run shutdown scripts and check for unsaved files.

close(mainProject)

See Also

Related Topics